Python Training - Vizag Interns

May 30 - June 1, 2017 Anand Chitipothu

These notes are available online at https://notes.pipal.in/2017/vizag-interns

© Pipal Academy LLP

Home | Day 1 | Day 2 | Day 3

In [1]:
1 + 2
Out[1]:
3
In [2]:
2 ** 1000
Out[2]:
10715086071862673209484250490600018105614048117055336074437503883703510511249361224931983788156958581275946729175531468251871452856923140435984577574698574803934567774824230985421074605062371141877954182153046474983581941267398767559165543946077062914571196477686542167660429831652624386837205668069376
In [3]:
%%file hello.py
print("hello everyone")
Overwriting hello.py
In [4]:
!python hello.py
hello everyone

Variables

In [5]:
x = 3
In [6]:
print(x)
3
In [7]:
print(x*x)
9
In [8]:
name = "Alice"
In [9]:
print("hello", name)
hello Alice

Datatypes

Python has integers.

In [10]:
1 + 2
Out[10]:
3

Python has floating point numbers.

In [11]:
1.2 + 2.3
Out[11]:
3.5

Python has strings.

In [12]:
print("Hello world")
Hello world

Strings are enclosed in either single quotes or double quotes. Both mean the same.

In [13]:
"Hello" + ' python'
Out[13]:
'Hello python'
In [14]:
"hello" * 3
Out[14]:
'hellohellohello'
In [15]:
print("=" * 40)
========================================
In [16]:
len("hello")
Out[16]:
5

Python has support for usual escape codes.

In [17]:
print("a\nb\nc")
a
b
c
In [18]:
print("a\tb\tc")
a	b	c

Python supports multi-lines strings as well. They are enclosed in three single quotes or double quotes.

In [19]:
text = """This is a multi-line string.
Line 2.
Line three.

Yet another line with "quotes in it".
"""
In [20]:
print(text)
This is a multi-line string.
Line 2.
Line three.

Yet another line with "quotes in it".

In [21]:
text
Out[21]:
'This is a multi-line string.\nLine 2.\nLine three.\n\nYet another line with "quotes in it".\n'

Python has lists.

In [22]:
x = ["a", "b", "c"]
In [23]:
x
Out[23]:
['a', 'b', 'c']
In [24]:
len(x)
Out[24]:
3
In [25]:
x[0]
Out[25]:
'a'
In [26]:
x[1]
Out[26]:
'b'
In [27]:
x[2]
Out[27]:
'c'
In [28]:
matrix = [[1, 2], [3, 4], [5, 6]]
In [29]:
matrix
Out[29]:
[[1, 2], [3, 4], [5, 6]]
In [30]:
len(matrix)
Out[30]:
3
In [31]:
matrix[0]
Out[31]:
[1, 2]
In [32]:
matrix[1]
Out[32]:
[3, 4]
In [33]:
matrix[0][0]
Out[33]:
1

Python has another data-type called tuple for representing fixed width records.

In [34]:
point = (2, 3)
In [35]:
print(point)
(2, 3)
In [36]:
yellow = (255, 255, 0) # R, G, B
In [37]:
yellow
Out[37]:
(255, 255, 0)
In [43]:
r, g, b = yellow
In [44]:
r
Out[44]:
255
In [40]:
g
Out[40]:
255
In [41]:
b
Out[41]:
0
In [45]:
dark_yellow = (0.8 * r, 0.8 * g, 0.8 * b)
In [46]:
dark_yellow
Out[46]:
(204.0, 204.0, 0.0)

Python has dictionaries for storing name-value pairs.

In [47]:
person = {"name": "Alice", "email": "alice@example.com"}
In [48]:
person["name"]
Out[48]:
'Alice'
In [49]:
person["email"]
Out[49]:
'alice@example.com'

Python has a boolean type with True and False as values.

In [50]:
True
Out[50]:
True
In [51]:
False
Out[51]:
False

Python has a special type called None to represent nothing.

In [52]:
x = None
In [53]:
print(x)
None

Variables and Strings

In [54]:
name = "Alice"
print("Hello", name)
Hello Alice
In [55]:
print("Hello", "name")
Hello name
In [56]:
print("Hello", Alice)
---------------------------------------------------------------------------
NameError                                 Traceback (most recent call last)
<ipython-input-56-c1c4c2e2a21b> in <module>()
----> 1 print("Hello", Alice)

NameError: name 'Alice' is not defined

It treats Alice as a variable, not string.

Functions

Python has many built-in functions.

In [57]:
print("hello")
hello
In [58]:
len("helloworld")
Out[58]:
10
In [59]:
len("abrakadabra")
Out[59]:
11
In [60]:
len([1,2,3])
Out[60]:
3

Python doesn't support operations on incompatible data types.

In [61]:
1 + "2"
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-61-b88986c5ffd8> in <module>()
----> 1 1 + "2"

TypeError: unsupported operand type(s) for +: 'int' and 'str'
In [62]:
int("2")
Out[62]:
2
In [63]:
str(1)
Out[63]:
'1'
In [64]:
1 + int("2")
Out[64]:
3
In [65]:
str(1) + "2"
Out[65]:
'12'

Example: Counting the number of digits in a number

In [66]:
12345
Out[66]:
12345
In [67]:
2 ** 100
Out[67]:
1267650600228229401496703205376
In [68]:
2 ** 1000
Out[68]:
10715086071862673209484250490600018105614048117055336074437503883703510511249361224931983788156958581275946729175531468251871452856923140435984577574698574803934567774824230985421074605062371141877954182153046474983581941267398767559165543946077062914571196477686542167660429831652624386837205668069376
In [69]:
str(12345)
Out[69]:
'12345'
In [70]:
len(str(12345))
Out[70]:
5
In [71]:
len(str(2**100))
Out[71]:
31
In [72]:
len(str(2**1000))
Out[72]:
302
In [74]:
len(str(2**100000))
Out[74]:
30103

Writing Custom Functions

In [75]:
def square(x):
    return x*x
In [76]:
square(4)
Out[76]:
16
In [77]:
def square(x):
    y = x*x
    return y
In [78]:
square(4)
Out[78]:
16

Remember that the body of the function must be indented. Typically 4 spaces are used for indentation. Python identifies the body of the function using indentation only.

In [79]:
a = 23
a2 = square(a)
print("square of", a, "is", a2)
square of 23 is 529
In [80]:
%%file square.py

def square(x):
    return x*x

print(square(4))
Writing square.py
In [81]:
!python square.py
16

Problem: Write a function cube to compute cube of a number.

>>> cube(2)
8
>>> cube(3)
27

Problem: Write a function count_digits that takes a number as argument and returns the number of digits it has.

>>> count_digits(12345)
5
>>> count_digits(2**1000)
302

print vs. return

In [82]:
def square1(x):
    return x*x

def square2(x):
    print(x*x)
    
print(square1(4))
square2(4)
16
16
In [83]:
square1(4) + 1
Out[83]:
17
In [84]:
square1(square1(1234))
Out[84]:
2318785835536

It is better to make functions return values.

Except in cases where the function is written to just print something.

In [85]:
def say_hello(name):
    print("Hello", name)
In [86]:
say_hello("Python")
Hello Python

Functions are values too!

In [88]:
def square(x):
    return x*x

print(square(3))
9
In [89]:
print(square)
<function square at 0x103ec2e18>
In [90]:
f = square
In [91]:
print(f(4))
16
In [92]:
x = 4
y = x
print(y)
4
In [94]:
def square(x):
    return x*x

def sum_of_squares(x, y):
    return square(x) + square(y)

print(sum_of_squares(3, 4))
25
In [96]:
def cube(x):
    return x*x*x

def sum_of_cubes(x, y):
    return cube(x) + cube(y)

print(sum_of_cubes(3, 4))
91
In [97]:
def sumof(f, x, y):
    return f(x) + f(y)

print(sumof(square, 3, 4))
print(sumof(cube, 3, 4))
25
91
In [98]:
print(sumof(len, "hello", "everyone"))
13
In [99]:
max([3, 4, 9, 5])
Out[99]:
9
In [100]:
max(["one", "two", "three", "four", "five"])
Out[100]:
'two'

How to find the longest word?

In [101]:
max(["one", "two", "three", "four", "five"], key=len)
Out[101]:
'three'
In [102]:
def mylen(x):
    print("mylen", x)
    return len(x)

max(["one", "two", "three", "four", "five"], key=mylen)
mylen one
mylen two
mylen three
mylen four
mylen five
Out[102]:
'three'
In [103]:
# records of students with marks
records = [
    ("A", 78),
    ("B", 96),
    ("C", 94)
]
In [106]:
def get_marks(record):
    print("get_marks", record)
    marks = record[1]
    return marks

x = max(records, key=get_marks)
print(x)
print(x[0])
get_marks ('A', 78)
get_marks ('B', 96)
get_marks ('C', 94)
('B', 96)
B

Methods

Methods are special kind of functions that work on an object.

In [107]:
x = "Hello"
In [108]:
x.upper()
Out[108]:
'HELLO'
In [109]:
y = "Python"
In [110]:
y.upper()
Out[110]:
'PYTHON'
In [111]:
"mathematics".count("mat")
Out[111]:
2

Problem: Write a function count_zeros to count the number of zeros in the given number.

>>> count_zeros(0)
1
>>> count_zeros(100)
2
>>> count_zeros(2030405)
3 
In [116]:
def count_zeros(number):
    return str(number).count("0")

print(count_zeros(0))
print(count_zeros(100))
print(count_zeros(2030405))
1
2
3

Let us look at some more useful methods on strings.

In [117]:
sentence = "Anything that can go wrong, will go wrong"
In [118]:
sentence.split()
Out[118]:
['Anything', 'that', 'can', 'go', 'wrong,', 'will', 'go', 'wrong']

The split method by default, splits the string on any white space. We can optionally specify a delimiter.

In [119]:
sentence.split(",")
Out[119]:
['Anything that can go wrong', ' will go wrong']

Let us look at join, the reverse of split.

In [120]:
words = ["one", "two", "three"]
In [121]:
" ".join(words)
Out[121]:
'one two three'
In [122]:
"-".join(words)
Out[122]:
'one-two-three'
In [123]:
" :o: ".join(words)
Out[123]:
'one :o: two :o: three'

Problem: Write a function count_words that takes a sentence as argument and returns the number of words it has.

>>> count_words("one two three four five")
5

Bonus Problem: Write a function longest_word that takes a sentence as argument and returns the longest word from it.

>>> longest_word("one two three four five")
'three'
In [124]:
def count_words(sentence):
    words = sentence.split()
    return len(words)

print(count_words("one two three four five"))
5
In [125]:
def longest_word(sentence):
    words = sentence.split()
    return max(words, key=len)

print(longest_word("one two three four five"))
three

Modules

In [126]:
import time
In [127]:
time.asctime()
Out[127]:
'Tue May 30 15:03:41 2017'
In [128]:
time.asctime()
Out[128]:
'Tue May 30 15:03:45 2017'
In [129]:
%%file date.py
import time
print(time.asctime())
Writing date.py
In [130]:
!python date.py
Tue May 30 15:04:18 2017
In [131]:
!python date.py
Tue May 30 15:04:22 2017

There is another way to import it.

In [132]:
from time import asctime
In [133]:
asctime()
Out[133]:
'Tue May 30 15:06:47 2017'

Let us look at some more modules in Python.

The os module

In [134]:
import os
In [135]:
# get the current working directory
os.getcwd()
Out[135]:
'/Users/anand/trainings/2017/vizag-interns'
In [137]:
# all files in the current directory. 
# path "." means the current directory
os.listdir(".")
Out[137]:
['.ipynb_checkpoints',
 'Makefile',
 'date.py',
 'day1.html',
 'day1.ipynb',
 'day2.html',
 'day2.ipynb',
 'day3.html',
 'day3.ipynb',
 'hello.py',
 'index.html',
 'index.ipynb',
 'push',
 'square.py']

Problem: Write a function count_files that takes path to a directory as argument and returns the number of files in it. The number of files includes both the regular files and sub directories.

>>> count_files(".")
14
>>> count_files("/tmp") # or "c:\\" on windows
9

How to find size of a file?

In [139]:
os.path.getsize("square.py")
Out[139]:
48

How to find the largest file in the current directory?

help! help! help!

In [140]:
help("os.path.getsize")
Help on function getsize in os.path:

os.path.getsize = getsize(filename)
    Return the size of a file, reported by os.stat().

If the module is already imported, you can say:

In [141]:
help(os.path.getsize)
Help on function getsize in module genericpath:

getsize(filename)
    Return the size of a file, reported by os.stat().

The random module

In [142]:
import random
In [143]:
words = ["one", "two", "three", "four", "five"]
random.choice(words)
Out[143]:
'three'
In [144]:
random.choice(words)
Out[144]:
'one'
In [145]:
random.choice(words)
Out[145]:
'five'

How to find a random word from a sentence?

In [146]:
def random_word(sentence):
    return random.choice(sentence.split())
In [147]:
random_word("one two three four five")
Out[147]:
'one'
In [148]:
random_word("one two three four five")
Out[148]:
'three'

Let us try a fun program.

Write a function say_hello to greet a person in a random language.

Reading command-line arguments

In [149]:
%%file args.py
import sys
print(sys.argv)
Writing args.py
In [150]:
!python args.py
['args.py']
In [151]:
!python args.py hello python
['args.py', 'hello', 'python']

By convention, the first element in that list is the program name.

In [152]:
!python args.py 1 2 3 4 5
['args.py', '1', '2', '3', '4', '5']

Remember that the arguments are always considered as strings.

Example: echo.py

Let us write a program to print the first command-line argument.

In [153]:
%%file echo.py
import sys
print(sys.argv[1])
Writing echo.py
In [154]:
!python echo.py hello
hello

Problem: Write a program square.py that takes a number as command-line argument and prints square of that number.

$ python square.py 4
16

Problem: Write a program add.py that takes two numbers as command-line arguments and prints their sum.

$ python add.py 2 3
5
In [157]:
%%file square.py
import sys
print(sys.argv)
n = int(sys.argv[1])
print(n*n)
Overwriting square.py
In [158]:
!python square.py 4
['square.py', '4']
16

Installing pygame on Anaconda Python

Try:

conda install -c tlatorre pygame=1.9.2
In [ ]: