May 30 - June 1, 2017
Anand Chitipothu
These notes are available online at https://notes.pipal.in/2017/vizag-interns
import random
def say_hello(name):
hello_options = ["Namaskaram", "Hello", "Vanakkam", "Namaskar"]
hello = random.choice(hello_options)
print(hello, name)
say_hello("Python")
say_hello("Python")
say_hello("Python")
How to greet with both a message and a suffix (like "Hello Python Garu")?
# this version is not correct
def say_hello(name):
hello_options = ["Namaskaram", "Hello", "Vanakkam", "Namaskar"]
hello = random.choice(hello_options)
suffix_options = ["Garu", "Sir", "Anna", "Ji"]
suffix = random.choice(suffix_options)
print(hello, name, suffix)
say_hello("Python")
This says hello in one language and the suffix in another language. That is not what we wanted.
def say_hello(name):
hello_options = [
("Namaskaram", "Garu"),
("Hello", "Sir"),
("Vanakkam", "Anna"),
("Namaskar", "Ji")
]
hello, suffix = random.choice(hello_options)
print(hello, name, suffix)
say_hello("Python")
say_hello("Python")
say_hello("Python")
score = 47
score > 35
score < 35
name = "Alice"
name == "Alice"
name == "Alice" and score > 35
The in operator can be used to check if an element is part of another.
"hell" in "hello"
"yell" in "hello"
"yell" not in "hello"
"a" in ["a", "b", "c"]
vowels = ["a", "e", "i", "o", "u"]
def is_vowel(c):
return c in vowels
is_vowel('x')
is_vowel('e')
Strings have other useful methods to check for prefix and suffix matching.
"hello".startswith("hell")
"hello".endswith("lo")
def is_python_file(filename):
return filename.endswith(".py")
is_python_file("hello.py")
is_python_file("hello.c")
if Statement¶n = 35
if n % 2 == 0:
print("even")
else:
print("odd")
def check_even(n):
if n % 2 == 0:
print("even")
else:
print("odd")
check_even(34)
check_even(345)
Checking multiple conditions can be done using elif statements.
def check_number(n):
if n < 10:
print(n, "is a single digit number")
elif n < 100:
print(n, "is a double digit number")
else:
print(n, "is a big number")
check_number(3)
check_number(34)
check_number(345)
Problem: Write a function minimum to compute the minimum of two numbers, without using the built-in min function. Please note that the function should return the minimum value, not print.
>>> minimum(3, 7)
3
>>> minimum(33, 7)
7
>>> 1 + minimum(3, 7)
4
Bonus Problem: Write a function mimimum3 to compute minimum of three numbers. Can you do this using the minimum function defined above?
>>> minimum3(3, 4, 5)
3
>>> minimum3(13, 4, 5)
4
>>> minimum3(13, 14, 5)
5
x = ["a", "b", "c", "d"]
len(x)
x[0]
x[1]
x = ["a", "b", "c", "d"]
for element in x:
print(element)
names = ["Alice", "Bob", "Charlie", "Dave"]
for name in names:
print("Hello", name)
How to print all words in a sentence?
sentence = "when in doubt, use brute force"
Problem: Write a program ls.py that takes path to a directory as command-line argument and prints all the files in that directory. The output should contain one filename per line.
$ python ls.py .
Makefile
day1.ipynb
day1.html
day2.ipynb
day2.html
square.py
%%file ls.py
import sys
import os
path = sys.argv[1]
files = os.listdir(path)
for f in files:
print(f)
!python ls.py .
Python has a built-in function range to iterate over a sequence of numbers.
for i in range(5):
print(i)
range(5) gives values from 0 to 4.
# we can optionally provide begin as well.
for i in range(2, 5):
print(i)
# say hello n times
def say_hello(name, n):
for i in range(n):
print("Hello", name)
say_hello("Python", 5)
Python has a built-in function sum to compute sum of a list of numbers.
sum([1, 2, 3, 4, 5])
sum(range(10))
# sum of all numbers below one million
sum(range(1000000))
Let us try to implement our own sum function.
def my_sum(numbers):
result = 0
for n in numbers:
result = result + n
return result
my_sum([1, 2, 3, 4, 5])
my_sum(range(1000000))
Problem: Write a function product that takes a list of numbers and computes their product.
>>> product([1, 2, 3, 4])
24
Problem: Write a function factorial that takes a number as argument and computes its factorial. Can you use the above implementation of product in computing it?
>>> factorial(4)
24
x = ["a", "b", "c", "d"]
x
x[0]
x[1]
x[1] = 'bb'
x
x.append('e')
x
Notice that the append method doesn't return any value, it just modifies the list in-place.
Let us write a function squares to compute squares of all numbers in a list.
def squares(numbers):
result = []
for n in numbers:
result.append(n*n)
return result
squares([1, 2, 3, 4, 5])
# How to compute sum of squares of all numbers
# below one million?
sum(squares(range(1000000)))
Problem: Write a function evens that takes a list of numbers as argument and returns a new list containing only the even numbers out of them.
>>> evens([1, 2, 3, 4, 5, 6])
[2, 4, 6]
x = [1, 2, 3, 4, 5, 6]
[a*a for a in x]
[a*a for a in x if a % 2 == 0]
names = ["a", "b", "c", "d"]
upper_names = [name.upper() for name in names]
upper_names
List comprehensions are used to transform one list to another.
They are usually written as:
[expr for var in alist]
[expr for var in alist if some_condition]
Problem: Write a function list_pyfiles that takes path to a directory as argument and returns all python files in that directory.
>>> list_pyfiles(".")
["args.py", "echo.py", "square.py"]
import os
def list_pyfiles(path):
files = os.listdir(path)
return [f for f in files if f.endswith(".py")]
list_pyfiles(".")
# all python files
[f for f in os.listdir(".") if f.endswith(".py")]
# size of each python file
[os.path.getsize(f) for f in os.listdir(".") if f.endswith(".py")]
# total size of all python files in the current directory
sum([os.path.getsize(f) for f in os.listdir(".")
if f.endswith(".py")])
x = ["a", "b", "c", "d"]
for a in x:
print(a)
x = ["a", "b", "c", "d"]
for a in x:
print(a.upper())
x_upper = [a.upper() for a in x]
print(x_upper)
for i in range(5):
print(i, i*i)
for i in range(2, 5):
print(i, i*i)
[i*i for i in range(10)]
names = ["a", "b", "c", "d"]
scores = [10, 20, 30, 40]
for name, score in zip(names, scores):
print(name, score)
list(zip(names, scores))
Problem: write a function vector_add to add two vectors.
>>> vector_add([1, 2, 3, 4], [10, 20, 30, 40])
[11, 22, 33, 44]
names = ["a", "b", "c", "d"]
for i, name in enumerate(names):
print(i, name)
Let us look at a simple example.
chapters = ["Getting Started", "Lists", "Building Games"]
for i, title in enumerate(chapters):
print("chapter", i+1, ":", title)
for i, title in enumerate(chapters, start=1):
print("chapter", i, ":", title)
x = ["a", "b", "c", "d"]
x[1]
x[len(x)-1]
x[-1]
def get_last_word(sentence):
return sentence.split()[-1]
get_last_word("one tow three")
how to find extension of a file?
def getext(filename):
return filename.split(".")[-1]
getext("hello.py")
getext("a.tar.gz")
x = ["a", "b", "c", "d", "e", "f", "g", "h"]
x[0:2]
x[:2] # upto index 2 (index 2 not included)
x[2:] # index 2 onwards
x[2:6] # from index 2 to index 6
x[:] # copy of x
x[1:6:2] # every second element from index 1 to 6
x[::-1] # reverse of a list
The range function can take optional third argument.
for i in range(0, 100, 25):
print(i)