March 27-31, 2017
Anand Chitipothu
These notes are available online at https://notes.pipal.in/2017/symantec
© Pipal Academy LLP
1 + 2
print("hello world")
%%file hello.py
print("Hello world from Jupyter")
!python hello.py
Let us look at various datatypes in Python.
Python has integers.
1 + 2
2 ** 1000
Python has floating point numbers.
1.2 + 2.3
Python has strings.
"Hello world"
Strings can be enclosed either in double quotes or single quotes. Both exactly mean the same.
"Hello" + 'python'
"Hello" * 5
print("Hello", "Python")
Q: Can we use comma in print function call? What is the difference between comma and plus?
"Hello" + "Python" # concatination
print("Hello" + "Python") # one argument is passed to print
print("Hello", "Python") # two arguments are passed to print function
print("Hello", 1, 2, 3) # pass a string and three numbers as args to print
# this will fail
print("Hello" + 1)
Python supports usual escape characters in strings.
print("a\nb\nc")
print("a\tb\tc")
Python has support for multi-line strings too.
message = """This is multi-line string.
Second line.
Line number 3.
"""
message
print(message)
Multi-line strings are enclosed in three double quotes or three single quotes.
Python strings can handle any unicode characters.
print("\u0c05\u0c06\u0c07\u0c08")
print("\u0b85\u0b86\u0b87\u0b88")
name = "\u0b85\u0b86\u0b87\u0b88"
len(name)
Python has a type called bytes for handling binary data.
x = b"hello"
type(x)
Adding a prefix b before a literal string, makes it bytes.
x = b'\x12\xc4\x9b'
There are ways to convert bytes to strings and vice-versa. We'll look into that later.
Python has lists.
x = ["a", "b", "c"]
x
The length of a list can be found using the len function.
len(x)
The individual elements can be accessed using [].
x[0]
x[1]
Q: Is it possible to access multiple elements of a list at once?
print(x[0], x[1])
Python has more advanced ways to slice and dice lists.
x[:2] # take first 2 elements
We'll more about them later.
Python has another datatype called tuple for representing fixed-width records.
point = (3, 4)
print(point)
point[0]
point[1]
x, y = point
print(x, y)
yellow = 255, 255, 0 # RGB
print(yellow)
r, g, b = yellow
print(r, g, b)
Python has dictionaries for representing name-value pairs.
person = {"name": "Alice", "email": "alice@example.com"}
print(person)
Dictionary is an unordered collection. The order of elements is not guaranteed.
person["name"]
person["email"]
student = {"name": "alice", "marks": {"science": 87, "maths": 48}}
student["marks"]
student["marks"]["science"]
Python has sets too.
x = {1, 3, 2, 3, 1}
x
Q: Can we use values of any datatype as elements of a set?
Some data types like lists and dictionaries can't be used because they can be changed after adding a set.
red = (255, 0, 0)
blue = (0, 0, 255)
yellow = (255, 255, 0)
colors = {red, blue, yellow, blue, red}
print(colors)
set maintains unique elements.
Python has a boolean data type. It has two special values True and False.
True
False
Python has a special dataype to represent nothing. There is a special value None.
print(None)
x = None
print(x)
x # nothing will be printed because the interpreter ignores None values
If there is a function that does't return any value, then None is returned.
x = print("hello")
print(x)
x = 4
x
print(x*x)
Python doesn't have type declarations like in other languages.
x = "hello"
print(x)
It is an error to use a variable that is not defined.
yy
Python has many built-in functions.
print("hello")
print(1, 2, 3, 4)
len("hello")
Python doesn't support operations on incompatible datatypes.
1 + "2"
int("2")
str(1)
1 + int("2")
str(1) + "2"
How to count number of digits in a number?
12345
2 ** 100
2 ** 1000
len(12345) # len doesn't work on numbers
str(12345)
len(str(12345))
len(str(2 ** 1000))
Q: What are different operators used in Python?
Arthematic operations:
+
-
*
/ (division)
// (integer division)
** (power)
% (remainder)
List and Dictionary operations:
[] (indexing)
str = "hello"
print(str)
str(1) + "2"
str
The only way out is to delete that variable.
del str
str
str(1) + "2"
def square(x):
return x*x
print(square(3))
Please note that the indentation is very important in Python. The body of the function has to be indented, usually 4 spaces are used for indentation.
def square(x):
y = x*x
return y
print(square(3))
Problem: Write a function cube to compute cube of a number.
>>> cube(2)
8
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
def count_digits(number):
return len(str(number))
print(count_digits(12345))
print(count_digits(2**1000))
# this doesn't work
def count_digits1(number):
str(number)
return len(number)
# right way
def count_digits2(number):
x = str(number)
return len(x)
Q: Can we write the two line the square function as a single line.
Python has expressions and statements. Expressions can be combined, not statements.
1 + 2 # expression
4 * (1+2)
x = 1 # statement
4 * (x=1) # error!
However, you can write multiple statements in a single line by separeting them using semicolon.
def square(x):
y = x*x; return y
print(square(3))
However, that is not a recommended practice.
def square(x):
return x*x
print(square(4))
print(square) # print the function it self
print(square()) # call square without any arguments and print the result
f = square
f(4)
print(f)
Is there any practical use of this?
def square(x):
return x*x
def sum_of_squares(x, y):
return square(x) + square(y)
print(sum_of_squares(3, 4))
def cube(x):
return x*x*x
def sum_of_cubes(x, y):
return cube(x) + cube(y)
print(sum_of_cubes(3, 4))
Both sum_of_squares and sum_of_cubes are doing almost the same thing. Can we generalize these two functions into a single function?
def sumof(f, x, y):
return f(x) + f(y)
sumof(square, 3, 4)
sumof(cube, 3, 4)
sumof(len, "Hello", "Python")
Python even has some built-in functions that take functions as arguments.
max([2, 3])
max(2, 3) # it even takes multiple arguments like this
max(["one", "two", "three", "four", "five"])
The comparison is based on dictionary ordering (comparing the characters).
How to find the longest element?
max(["one", "two", "three", "four", "five"], key=len)
tell max to use the function len when comparing.
def mylen(x):
print("mylen", x)
return len(x)
max(["one", "two", "three", "four", "five"], key=mylen)
Methods are special type of functions that work on an object.
x = "Hello"
x.upper()
y = "Python"
y.upper()
x.lower()
"mathematics".count("mat")
"mathematics".replace("mat", "rat")
Q: Is there a way to list all available methods on an object.
dir("hello")
The dir function gives all attributes of an object. They can be simple values, need not be methods.
You can also look at help using the the help function.
help(str)
...
Problem: Write a function count_zeros to count the number of zeros in a number.
>>> count_zeros(1003)
2
def count_zeros(number):
return str(number).count("0")
count_zeros(1003)
Q: sibi - my solution is not working.
# sibi's code
def count_zeros(x):
str.count(sub, start= 0,end=len(x))
return x
x(100)
What is x here?
# sibi's code
def count_zeros(x):
str.count(str(x), "0")
return x
count_zeros(100)
# sibi's code
def count_zeros(x):
y = str.count(str(x), "0")
return y
count_zeros(100)
A better approach would be to call count as a method.
# sibi's code
def count_zeros(x):
y = str(x).count("0")
return y
count_zeros(100)
Let us look at more useful methods on strings.
sentence = "anything that can go wrong, will go wrong"
sentence.split()
The split function splits a string on any whitespace.
Optionally, we can specify a delimiter.
sentence.split(",")
The reverse is done using the join method.
"-".join(["a", "b", "c"])
Problem: Write a function count_words that takes a sentence as argument and returns the number of words in it.
>>> count_words("one two three")
3
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'