May 30 - June 1, 2017 Anand Chitipothu
These notes are available online at https://notes.pipal.in/2017/vizag-interns
1 + 2
2 ** 1000
%%file hello.py
print("hello everyone")
!python hello.py
x = 3
print(x)
print(x*x)
name = "Alice"
print("hello", name)
Python has integers.
1 + 2
Python has floating point numbers.
1.2 + 2.3
Python has strings.
print("Hello world")
Strings are enclosed in either single quotes or double quotes. Both mean the same.
"Hello" + ' python'
"hello" * 3
print("=" * 40)
len("hello")
Python has support for usual escape codes.
print("a\nb\nc")
print("a\tb\tc")
Python supports multi-lines strings as well. They are enclosed in three single quotes or double quotes.
text = """This is a multi-line string.
Line 2.
Line three.
Yet another line with "quotes in it".
"""
print(text)
text
Python has lists.
x = ["a", "b", "c"]
x
len(x)
x[0]
x[1]
x[2]
matrix = [[1, 2], [3, 4], [5, 6]]
matrix
len(matrix)
matrix[0]
matrix[1]
matrix[0][0]
Python has another data-type called tuple for representing fixed width records.
point = (2, 3)
print(point)
yellow = (255, 255, 0) # R, G, B
yellow
r, g, b = yellow
r
g
b
dark_yellow = (0.8 * r, 0.8 * g, 0.8 * b)
dark_yellow
Python has dictionaries for storing name-value pairs.
person = {"name": "Alice", "email": "alice@example.com"}
person["name"]
person["email"]
Python has a boolean type with True and False as values.
True
False
Python has a special type called None to represent nothing.
x = None
print(x)
name = "Alice"
print("Hello", name)
print("Hello", "name")
print("Hello", Alice)
It treats Alice as a variable, not string.
Python has many built-in functions.
print("hello")
len("helloworld")
len("abrakadabra")
len([1,2,3])
Python doesn't support operations on incompatible data types.
1 + "2"
int("2")
str(1)
1 + int("2")
str(1) + "2"
12345
2 ** 100
2 ** 1000
str(12345)
len(str(12345))
len(str(2**100))
len(str(2**1000))
len(str(2**100000))
def square(x):
return x*x
square(4)
def square(x):
y = x*x
return y
square(4)
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.
a = 23
a2 = square(a)
print("square of", a, "is", a2)
%%file square.py
def square(x):
return x*x
print(square(4))
!python square.py
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
def square1(x):
return x*x
def square2(x):
print(x*x)
print(square1(4))
square2(4)
square1(4) + 1
square1(square1(1234))
It is better to make functions return values.
Except in cases where the function is written to just print something.
def say_hello(name):
print("Hello", name)
say_hello("Python")
def square(x):
return x*x
print(square(3))
print(square)
f = square
print(f(4))
x = 4
y = x
print(y)
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))
def sumof(f, x, y):
return f(x) + f(y)
print(sumof(square, 3, 4))
print(sumof(cube, 3, 4))
print(sumof(len, "hello", "everyone"))
max([3, 4, 9, 5])
max(["one", "two", "three", "four", "five"])
How to find the longest word?
max(["one", "two", "three", "four", "five"], key=len)
def mylen(x):
print("mylen", x)
return len(x)
max(["one", "two", "three", "four", "five"], key=mylen)
# records of students with marks
records = [
("A", 78),
("B", 96),
("C", 94)
]
def get_marks(record):
print("get_marks", record)
marks = record[1]
return marks
x = max(records, key=get_marks)
print(x)
print(x[0])
Methods are special kind of functions that work on an object.
x = "Hello"
x.upper()
y = "Python"
y.upper()
"mathematics".count("mat")
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
def count_zeros(number):
return str(number).count("0")
print(count_zeros(0))
print(count_zeros(100))
print(count_zeros(2030405))
Let us look at some more useful methods on strings.
sentence = "Anything that can go wrong, will go wrong"
sentence.split()
The split method by default, splits the string on any white space. We can optionally specify a delimiter.
sentence.split(",")
Let us look at join, the reverse of split.
words = ["one", "two", "three"]
" ".join(words)
"-".join(words)
" :o: ".join(words)
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'
def count_words(sentence):
words = sentence.split()
return len(words)
print(count_words("one two three four five"))
def longest_word(sentence):
words = sentence.split()
return max(words, key=len)
print(longest_word("one two three four five"))
import time
time.asctime()
time.asctime()
%%file date.py
import time
print(time.asctime())
!python date.py
!python date.py
There is another way to import it.
from time import asctime
asctime()
Let us look at some more modules in Python.
os module¶import os
# get the current working directory
os.getcwd()
# all files in the current directory.
# path "." means the current directory
os.listdir(".")
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?
os.path.getsize("square.py")
How to find the largest file in the current directory?
help("os.path.getsize")
If the module is already imported, you can say:
help(os.path.getsize)
random module¶import random
words = ["one", "two", "three", "four", "five"]
random.choice(words)
random.choice(words)
random.choice(words)
How to find a random word from a sentence?
def random_word(sentence):
return random.choice(sentence.split())
random_word("one two three four five")
random_word("one two three four five")
Let us try a fun program.
Write a function say_hello to greet a person in a random language.
%%file args.py
import sys
print(sys.argv)
!python args.py
!python args.py hello python
By convention, the first element in that list is the program name.
!python args.py 1 2 3 4 5
Remember that the arguments are always considered as strings.
Let us write a program to print the first command-line argument.
%%file echo.py
import sys
print(sys.argv[1])
!python echo.py 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
%%file square.py
import sys
print(sys.argv)
n = int(sys.argv[1])
print(n*n)
!python square.py 4
Try:
conda install -c tlatorre pygame=1.9.2