You are on page 1of 37

11/20/2019 Python_Slides_SudentCopy

Hello, World!
Python is a very simple language, and has a very straightforward syntax. It encourages programmers to
program without boilerplate (prepared) code. The simplest directive in Python is the "print" directive - it simply
prints out a line (and also includes a newline, unlike in C).

There are two major Python versions, Python 2 and Python 3. Python 2 and 3 are quite different. This tutorial
uses Python 3, because it more semantically correct and supports newer features.

For example, one difference between Python 2 and 3 is the print statement. In Python 2, the "print"
statement is not a function, and therefore it is invoked without parentheses. However, in Python 3, it is a
function, and must be invoked with parentheses.

To print a string in Python 3, just write:

In [ ]:

print("This line will be printed.")

Indentation

Python uses indentation for blocks, instead of curly braces.

Both tabs and spaces are supported, but the standard indentation requires standard Python code to use four
spaces. For example:

In [ ]:

x = 1
if x == 1:
print("x is 1.")
else:
print("x is not 1.")

Basic I/O
In [ ]:

input_val = input("Enter your name: ")

In [ ]:

print(input_val)

file:///home/krdevkota/Downloads/Python_Slides_SudentCopy.html 1/37
11/20/2019 Python_Slides_SudentCopy

In [ ]:

my_name = "Sam"
input_name = input("Enter your name: ")
if input_name == my_name:
print("You got selected!")
else:
print("Sorry, try next time!")

In [ ]:

my_name = "Sam"
input_name = input("Enter your name: ")
if input_name == my_name:
print("You got selected!")
acc_num = input("Account number please: ")
else:
print("Sorry, try next time!")

Variables and Types


Python is completely object oriented, and not "statically typed". You do not need to declare variables before
using them, or declare their type. Every variable in Python is an object.

This tutorial will go over a few basic types of variables.

Numbers

Python supports two types of numbers - integers and floating point numbers. (It also supports complex
numbers, which will not be explained in this tutorial).

To define an integer, use the following syntax:

In [ ]:

myint = 7
print(myint)

In [ ]:

type(myint)

In [ ]:

myint = str(myint) # type-casting


print(type(myint))
print(myint)

To define a floating point number, you may use one of the following notations:

file:///home/krdevkota/Downloads/Python_Slides_SudentCopy.html 2/37
11/20/2019 Python_Slides_SudentCopy

In [ ]:

myfloat = 7.0
print(myfloat)

In [ ]:

myfloat = float(7)
print(myfloat)

Strings

In [ ]:

mystring = 'hello'
print(mystring)

In [ ]:

mystring = "hello"
print(mystring)

The difference between the two is that using double quotes makes it easy to include apostrophes (whereas
these would terminate the string if using single quotes)

In [ ]:

mystring = "Don't worry about apostrophes"


print(mystring)

There are additional variations on defining strings that make it easier to include things such as carriage
returns, backslashes and Unicode characters. These will be covered later.

Simple operators can be executed on numbers and strings:

In [ ]:

x = 1
y = 2
three = x + y
print(three)

In [ ]:

x = 1
y = 2
z = x + y
print(z)

In [ ]:

x = "hello"
y = "world"
z = x + " " + y
print(z)

file:///home/krdevkota/Downloads/Python_Slides_SudentCopy.html 3/37
11/20/2019 Python_Slides_SudentCopy

Assignments can be done on more than one variable "simultaneously" on the same line like this

In [ ]:

a, b = 3, 4
print(a,b)

Mixing operators between numbers and strings is not supported:

In [ ]:

# This will not work!


one = 1
two = 2
hello = "hello"

print(one + two + hello)

Exercise
The target of this exercise is to create a string, an integer, and a floating point number. The string should be
named mystring and should contain the word "hello". The floating point number should be named
myfloat and should contain the number 10.0, and the integer should be named myint and should contain
the number 20.

In [ ]:

# change this code


mystring = None
myfloat = None
myint = None

# testing code
if mystring == "hello":
print("String: %s" % mystring)
if isinstance(myfloat, float) and myfloat == 10.0:
print("Float: %f" % myfloat)
if isinstance(myint, int) and myint == 20:
print("Integer: %d" % myint)

Lists

Lists are very similar to arrays. They can contain any type of variable, and they can contain as many
variables as you wish. Lists can also be iterated over in a very simple manner. Here is an example of how to
build a list.

In [ ]:

mylist = [2]
print(mylist)
mylist.append(3)
print(mylist)

file:///home/krdevkota/Downloads/Python_Slides_SudentCopy.html 4/37
11/20/2019 Python_Slides_SudentCopy

In [ ]:

my_details = ["Python", "Teacher"]


print(my_details)
my_details.append("Kathmandu")
print(my_details)
my_details.append(5)
print(my_details)
my_details.insert(1,200)
print(my_details)

In [ ]:

my_details.remove(200)
print(my_details)

In [ ]:

my_details.copy? # to get help regarding any method

In [ ]:

my_details.insert(3,100)
print(my_details)
my_details.reverse()
print(my_details)

In [ ]:

my_details.pop()
print(my_details)
my_details.reverse()
print(my_details)

In [ ]:

marks = [20,10,92,43,65,90,54,49,97,81]
print(marks)
marks.sort()
print(marks)
# marks.reverse()
# print(marks)

In [ ]:

marks.sort(reverse=True)
print(marks)

In [ ]:

print(marks[:3])
print(marks[2:])

In [ ]:

num = [1,2,3,4,5,6,7,8,9,10]
l = len(num)
print(num[0:l:2])

file:///home/krdevkota/Downloads/Python_Slides_SudentCopy.html 5/37
11/20/2019 Python_Slides_SudentCopy

In [ ]:

mylist = []
print(mylist)
mylist.append(1)
mylist.append(2)
mylist.append(3)
print(mylist[0]) # prints 1
print(mylist[1]) # prints 2
print(mylist[2]) # prints 3

In [ ]:

# prints out 1,2,3


for i in mylist:
print(i)

Exercise
In this exercise, you will need to add numbers and strings to the correct lists using the "append" list method.
You must add the numbers 1,2, and 3 to the "numbers" list, and the words 'hello' and 'world' to the strings
variable.

You will also have to fill in the variable second_name with the second name in the names list, using the
brackets operator [] Note that the index is zero-based, so if you want to access the second item in the list,
its index will be 1.

In [ ]:

numbers = []
strings = []
names = ["John", "Eric", "Jessica"]

# write your code here


second_name = None

# this code should write out the filled arrays and the second name in the names
list (Eric).
print(numbers)
print(strings)
print("The second name on the names list is %s" % second_name)

Basic Operators

Arithmetic Operators

Just as any other programming languages, the addition, subtraction, multiplication, and division operators
can be used with numbers.

file:///home/krdevkota/Downloads/Python_Slides_SudentCopy.html 6/37
11/20/2019 Python_Slides_SudentCopy

Try to predict what the answer will be. Does python follow order of operations?

In [ ]:

number = 1 + 2 * 3 / 4.0
print(number)

In [ ]:

a = 5.0 ** 2
type(a)

In [ ]:

# type casting
a = str(a)
a

In [ ]:

70 // 3 # floor division

Another operator available is the modulo (%) operator, which returns the integer remainder of the division.
dividend % divisor = remainder.

In [ ]:

remainder = 7 % 3
print(remainder)

Using two multiplication symbols makes a power relationship.

In [ ]:

squared = 7 ** 2
cubed = 2 ** 3

In [ ]:

print(squared)
print(cubed)

Using Operators with Strings


Python supports concatenating strings using the addition operator:

In [ ]:

x = 7 + 8
x

file:///home/krdevkota/Downloads/Python_Slides_SudentCopy.html 7/37
11/20/2019 Python_Slides_SudentCopy

In [ ]:

x = "hello" +" "+ "world" #concatination


print(x)

Python also supports multiplying strings to form a string with a repeating sequence:

In [ ]:

lotsofhellos = "hello " * 4


print(lotsofhellos)

Using Operators with Lists


Lists can be joined with the addition operators:

In [ ]:

even_numbers = [2,4,6,8]
odd_numbers = [1,3,5,7]
all_numbers = odd_numbers + even_numbers
print(all_numbers)

Compare this with append operation:

In [ ]:

test = []
test.append(even_numbers)
test.append(odd_numbers)
print(test)

Just as in strings, Python supports forming new lists with a repeating sequence using the multiplication
operator:

In [ ]:

print([1,2,3] * 3)

Exercise
The target of this exercise is to create two lists called x_list and y_list, which contain 10 instances of
the variables x and y, respectively. You are also required to create a list called big_list, which contains
the variables x and y, 10 times each, by concatenating the two lists you have created.

file:///home/krdevkota/Downloads/Python_Slides_SudentCopy.html 8/37
11/20/2019 Python_Slides_SudentCopy

In [ ]:

x = 2
y = 4

# TODO: change this code


x_list = [x]*10
y_list = [y]*10
big_list = x_list + y_list

print(big_list)
print("x_list contains %d objects" % len(x_list))
print("y_list contains %d objects" % len(y_list))
print("big_list contains %d objects" % len(big_list))

# testing code
if x_list.count(x) == 10 and y_list.count(y) == 10:
print("Almost there...")
if big_list.count(x) == 10 and big_list.count(y) == 10:
print("Great!")

String Formatting
Python uses C-style string formatting to create new, formatted strings. The "%" operator is used to format a
set of variables enclosed in a "tuple" (a fixed size list), together with a format string, which contains normal
text together with "argument specifiers", special symbols like "%s" and "%d".

Let's say you have a variable called "name" with your user name in it, and you would then like to print(out a
greeting to that user.)

In [ ]:

name = "John"
age = 22
print("Hello, %s!" % name)
print ("Hello, %s! You are %d years old" % (name,age))
print ("Hello, {}! You are {} years old.".format(name,age))

To use two or more argument specifiers, use a tuple (parentheses):

In [ ]:

# This prints out "John is 23 years old."


name = "John"
age = 23
print("%s is %d years old." % (name, age))

In [ ]:

a = 5.00765
print("%.2f" %a) # floating point precision

Any object which is not a string can be formatted using the %s operator as well. The string which returns
from the "repr" method of that object is formatted as the string. For example:

file:///home/krdevkota/Downloads/Python_Slides_SudentCopy.html 9/37
11/20/2019 Python_Slides_SudentCopy

In [ ]:

# This prints out: A list: [1, 2, 3]


mylist = [1,2,3]
print("A list: %s" % mylist)

Here are some basic argument specifiers you should know:

%s - String (or any object with a string representation, like numbers)

%d - Integers

%f - Floating point numbers

%.<number of digits>f - Floating point numbers with a fixed amount of digits to


the right of the dot.

%x/%X - Integers in hex representation (lowercase/uppercase)

Exercise
You will need to write a format string which prints out the data using the following syntax: Hello John
Doe. Your current balance is $53.44.

In [ ]:

data = ("John", "Doe", 53.44)


format_string = "Hello"

print(format_string % data)

Basic String Operations


Strings are bits of text. They can be defined as anything between quotes:

In [ ]:

astring = "Hello world!"

As you can see, the first thing you learned was printing a simple sentence. This sentence was stored by
Python as a string. However, instead of immediately printing strings out, we will explore the various things
you can do to them. You can also use single quotes to assign a string. However, you will face problems if the
value to be assigned itself contains single quotes.For example to assign the string in these bracket(single
quotes are ' ') you need to use double quotes only like this

In [ ]:

print("single quotes are ' '")


astring = "Hello world!"
print(len(astring))

file:///home/krdevkota/Downloads/Python_Slides_SudentCopy.html 10/37
11/20/2019 Python_Slides_SudentCopy

That prints out 12, because "Hello world!" is 12 characters long, including punctuation and spaces.

In [ ]:

astring = "Hello world!"


print(astring.index("o"))

That prints out 4, because the location of the first occurrence of the letter "o" is 4 characters away from the
first character. Notice how there are actually two o's in the phrase - this method only recognizes the first.

But why didn't it print out 5? Isn't "o" the fifth character in the string? To make things more simple, Python
(and most other programming languages) start things at 0 instead of 1. So the index of "o" is 4.

In [ ]:

astring = "Hello world!"


print(astring.count("l"))

For those of you using silly fonts, that is a lowercase L, not a number one. This counts the number of l's in
the string. Therefore, it should print 3.

In [ ]:

astring = "Hello world!"


print(astring)
print(astring[3:7])

This prints a slice of the string, starting at index 3, and ending at index 6. But why 6 and not 7? Again, most
programming languages do this - it makes doing math inside those brackets easier.

If you just have one number in the brackets, it will give you the single character at that index. If you leave out
the first number but keep the colon, it will give you a slice from the start to the number you left in. If you leave
out the second number, if will give you a slice from the first number to the end.

You can even put negative numbers inside the brackets. They are an easy way of starting at the end of the
string instead of the beginning. This way, -3 means "3rd character from the end".

In [ ]:

astring = "Hello world!"


print(astring[3:7:2])

This prints the characters of string from 3 to 7 skipping one character. This is extended slice syntax. The
general form is [start:stop:step].

In [ ]:

print(astring[0:7:1])
print(astring[0:7])

file:///home/krdevkota/Downloads/Python_Slides_SudentCopy.html 11/37
11/20/2019 Python_Slides_SudentCopy

Note that both of them produce same output

There is no function like strrev in C to reverse a string. But with the above mentioned type of slice syntax you
can easily reverse a string like this

In [ ]:

astring = "Hello world!"

print(astring[11::-1])

In [ ]:

astring = "Hello world!"


print(astring.upper())
print(astring.lower())

In [ ]:

astring = "Hello world!"


splitted = astring.split(" ")
print(splitted)

These make a new string with all letters converted to uppercase and lowercase, respectively.

In [ ]:

astring = "Hello world!"


print(astring.startswith("Hello"))
print(astring.endswith("asdfasdfasdf"))

This is used to determine whether the string starts with something or ends with something, respectively. The
first one will print True, as the string starts with "Hello". The second one will print False, as the string certainly
does not end with "asdfasdfasdf".

In [ ]:

astring = "Hello world!"


afewwords = astring.split(" ")
print(afewwords)

This splits the string into a bunch of strings grouped together in a list. Since this example splits at a space,
the first item in the list will be "Hello", and the second will be "world!".

Exercise

file:///home/krdevkota/Downloads/Python_Slides_SudentCopy.html 12/37
11/20/2019 Python_Slides_SudentCopy

In [ ]:

s = "Hey there! what should this string be?"


# Length should be 20
print("Length of s = %d" % len(s))

# First occurrence of "a" should be at index 8


print("The first occurrence of the letter a = %d" % s.index("a"))

# Number of a's should be 2


print("a occurs %d times" % s.count("a"))

# Slicing the string into bits


print("The first five characters are '%s'" % s[:5]) # Start to 5
print("The next five characters are '%s'" % s[5:10]) # 5 to 10
print("The thirteenth character is '%s'" % s[12]) # Just number 12
print("The characters with odd index are '%s'" %s[1::2]) #(0-based indexing)
print("The last five characters are '%s'" % s[-5:]) # 5th-from-last to end

# Convert everything to uppercase


print("String in uppercase: %s" % s.upper())

# Convert everything to lowercase


print("String in lowercase: %s" % s.lower())

# Check how a string starts


if s.startswith("Str"):
print("String starts with 'Str'. Good!")

# Check how a string ends


if s.endswith("ome!"):
print("String ends with 'ome!'. Good!")

# Split the string into three separate strings,


# each containing only a word
print("Split the words of the string: %s" % s.split(" "))

Conditions
Python uses boolean variables to evaluate conditions. The boolean values True and False are returned when
an expression is compared or evaluated. For example:

In [ ]:

x = 2 # assignment operator
print(x == 2) # prints out True
print(x == 3) # prints out False
print(x < 3) # prints out True

Notice that variable assignment is done using a single equals operator "=", whereas comparison between
two variables is done using the double equals operator "==". The "not equals" operator is marked as "!=".

Boolean operators
file:///home/krdevkota/Downloads/Python_Slides_SudentCopy.html 13/37
11/20/2019 Python_Slides_SudentCopy

The "and" and "or" boolean operators allow building complex boolean expressions, for example:

In [ ]:

name = "John"
age = 23

if name == "John" and age == 23:


print("Your name is John, and you are also 23 years old.")

if name == "John" or name == "Rick":


print("Your name is either John or Rick.")

The "in" operator


The "in" operator could be used to check if a specified object exists within an iterable object container, such
as a list:

In [ ]:

name = "John"
mylist = ["John", "Rick"]
if name in mylist:
print("Your name is either John or Rick.")

In [ ]:

luckynumbers = [12, 11, 45,34, 68, 7, 77]


user_choice = int(input("Please enter a number to win: "))

if user_choice in luckynumbers:
print("Congratulations, you won!")
else:
print("Sorry, try again!")

Note that the number input form the keyboard is of type string. You'll have to cast it into either integer or float
to perform numerical operations on it.

In [ ]:

a = "4"
type(a)

In [ ]:

a = int(a)
print(type(a))
a

file:///home/krdevkota/Downloads/Python_Slides_SudentCopy.html 14/37
11/20/2019 Python_Slides_SudentCopy

In [ ]:

luckynumbers = [12, 11, 45,34, 68, 7, 77]


user_choice = int(input("Please enter a number to win: "))
print(type(user_choice))

if user_choice in luckynumbers:
print("Congratulations, you won!")
contact = input("Please enter your contact number: ")
else:
print("Sorry, try again!")

Python uses indentation to define code blocks, instead of brackets. The standard Python indentation is 4
spaces, although tabs and any other space size will work, as long as it is consistent. Notice that code blocks
do not need any termination.

Here is an example for using Python's "if" statement using code blocks:

if : .... .... elif : # else if .... .... else: .... ....

For exampe:

In [ ]:

x = 2
if x == 2:
print("x equals two!")
else:
print("x does not equal to two.")

A statement is evaulated as true if one of the following is correct: 1. The "True" boolean variable is given, or
calculated using an expression, such as an arithmetic comparison. 2. An object which is not considered
"empty" is passed.

Here are some examples for objects which are considered as empty: 1. An empty string: "" 2. An empty list: []
3. The number zero: 0 4. The false boolean variable: False

The 'is' operator


Unlike the double equals operator "==", the "is" operator does not match the values of the variables, but the
instances themselves. For example:

In [ ]:

x = [1,2,3]
y = [1,2,3]
print(x == y) # Prints out True
print(x is y) # Prints out False

The "not" operator

file:///home/krdevkota/Downloads/Python_Slides_SudentCopy.html 15/37
11/20/2019 Python_Slides_SudentCopy

Using "not" before a boolean expression inverts it:

In [ ]:

print(not False) # Prints out True


print((not False) == (False)) # Prints out False

Exercise
Change the variables in the first section, so that each if statement resolves as True.

In [ ]:

# change this code


number = 16
second_number = 0
first_array = [1,2,3]
second_array = [1,2]

if number > 15:


print("1")

if first_array:
print("2")

if len(second_array) == 2:
print("3")

if len(first_array) + len(second_array) == 5:
print("4")

if first_array and first_array[0] == 1:


print("5")

if not second_number:
print("6")

Loops
There are two types of loops in Python, for and while.

The "for" loop

For loops iterate over a given sequence. Here is an example:

file:///home/krdevkota/Downloads/Python_Slides_SudentCopy.html 16/37
11/20/2019 Python_Slides_SudentCopy

In [ ]:

primes = [2, 3, 5, 7]
print(primes[0])
print(primes[1])
print(primes[2])
print(primes[3])

This can be done using a loop easily as follows:

In [ ]:

for x in primes:
print(x)

Range operator

Used to generate a range of values.

In [ ]:

for i in range(0,20,2):
print(i)

In [ ]:

# program to print square of even numbers and cube of odd numbers

for i in range(0,20):
if i % 2 == 0:
print(i**2)
else:
print(i**3)

In [ ]:

primes = [2, 3, 5, 7]
for i in range(0,len(primes)):
print(primes[i])

For loops can iterate over a sequence of numbers using the "range" and "xrange" functions. The difference
between range and xrange is that the range function returns a new list with numbers of that specified range,
whereas xrange returns an iterator, which is more efficient. (Python 3 uses the range function, which acts like
xrange). Note that the range function is zero based.

In [ ]:

# Prints out the numbers 0,1,2,3,4


for x in range(5):
print(x)

In [ ]:

# Prints out 3,4,5


for x in range(3, 6):
print(x)

file:///home/krdevkota/Downloads/Python_Slides_SudentCopy.html 17/37
11/20/2019 Python_Slides_SudentCopy

In [ ]:

# Prints out 3,5,7


for x in range(3, 8, 2):
print(x)

"while" loops

While loops repeat as long as a certain boolean condition is met. For example:

In [ ]:

# Prints out 0,1,2,3,4

count = 0
while count < 5:
print(count)
count += 1 # This is the same as count = count + 1

"break" and "continue" statements

break is used to exit a for loop or a while loop, whereas continue is used to skip the current block, and
return to the "for" or "while" statement. A few examples:

In [ ]:

# Prints out 0,1,2,3,4

count = 0
while True:
print(count)
count += 1
if count >= 5:
break

In [ ]:

Q = [1,4,5,7,9,"f",0,0,4,4,4,5]

In [ ]:

Q = [1,4,5,7,9,"f",0,0,4,4,4,5]
count = 0
while count < len(Q):
print (Q[count])
count = count + 1
if Q[count] == "f":
break

file:///home/krdevkota/Downloads/Python_Slides_SudentCopy.html 18/37
11/20/2019 Python_Slides_SudentCopy

In [ ]:

names = ["Ashish", 5, "Binod", "Cera", 4]


for n in names:
if type(n) == int:
continue
print(n)

In [ ]:

for x in range(10):
# Check if x is even
if x % 2 == 0:
continue
print(x)

can we use "else" clause for loops?

unlike languages like C,CPP.. we can use else for loops. When the loop condition of "for" or "while"
statement fails then code part in "else" is executed. If break statement is executed inside for loop then the
"else" part is skipped. Note that "else" part is executed even if there is a continue statement.

Here are a few examples:

In [ ]:

count=0
while(count<5):
print(count)
count +=1
else:
print("count value reached %d" %(count))

In [ ]:

for i in range(1, 10):


print("input: ",i)
if(i%5==0):
break
print(i)
else:
print("this is not printed because for loop is terminated because of break b
ut not due to fail in condition")

Functions

What are Functions?

Functions are a convenient way to divide your code into useful blocks, allowing us to order our code, make it
more readable, reuse it and save some time. Also functions are a key way to define interfaces so
programmers can share their code.

file:///home/krdevkota/Downloads/Python_Slides_SudentCopy.html 19/37
11/20/2019 Python_Slides_SudentCopy

How do you write functions in Python?


As we have seen on previous tutorials, Python makes use of blocks.

A block is a area of code of written in the format of:

block_head: 1st block line 2nd block line ...

Where a block line is more Python code (even another block), and the block head is of the following format:
block_keyword block_name(argument1,argument2, ...) Block keywords you already know are "if", "for", and
"while".

Functions in python are defined using the block keyword "def", followed with the function's name as the
block's name. For example:

In [ ]:

def my_function():
print("Hello From My Function!")

# my_function()
y = my_function()
print(y)

Functions may also receive arguments (variables passed from the caller to the function). For example:

In [ ]:

def my_function_with_args(username, greeting):


print("Hello, %s , From My Function!, I wish you %s"%(username, greeting))

my_function_with_args("Ram", "Good afternoon!")


my_function_with_args("Hari", "Good night!")

Functions may return a value to the caller, using the keyword- 'return' . For example:

In [ ]:

def sum_two_numbers(a, b):


s = a + b
return s

In [ ]:

y = sum_two_numbers(5,7)
print(y)

How do you call functions in Python?


Simply write the function's name followed by (), placing any required arguments within the brackets. For
example, lets call the functions written above (in the previous example):

file:///home/krdevkota/Downloads/Python_Slides_SudentCopy.html 20/37
11/20/2019 Python_Slides_SudentCopy

In [ ]:

# Define our 3 functions


def my_function():
print("Hello From My Function!")

def my_function_with_args(username, greeting):


print("Hello, %s , From My Function!, I wish you %s"%(username, greeting))

def sum_two_numbers(a, b):


return a + b

# print(a simple greeting)


my_function()

#prints - "Hello, John Doe, From My Function!, I wish you a great year!"
my_function_with_args("John Doe", "a great year!")

# after this line x will hold the value 3!


x = sum_two_numbers(1,2)
print(x)

Exercise
In this exercise you'll use an existing function, and while adding your own to create a fully functional program.

1. Add a function named list_benefits() that returns the following list of strings: "More organized
code", "More readable code", "Easier code reuse", "Allowing programmers to share and connect
code together"
2. Add a function named build_sentence(info) which receives a single argument containing a
string and returns a sentence starting with the given string and ending with the string " is a benefit of
functions!"
3. Run and see all the functions work together!

In [ ]:

# Modify this function to return a list of strings as defined above


def list_benefits():
lst=[ "More organized code", "More readable code", "Easier code reuse",
"Allowing programmers to share and connect code together"]
return lst

# Modify this function to concatenate to each benefit - " is a benefit of functi


ons!"
def build_sentence(info1):
return

def name_the_benefits_of_functions():
listA = list_benefits()
for x in listA:
print(build_sentence(x))

name_the_benefits_of_functions()

file:///home/krdevkota/Downloads/Python_Slides_SudentCopy.html 21/37
11/20/2019 Python_Slides_SudentCopy

In [ ]:

# Solution

# Modify this function to return a list of strings as defined above


def list_benefits():
return "More organized code", "More readable code", "Easier code reuse", "Al
lowing programmers to share and connect code together"

# Modify this function to concatenate to each benefit - " is a benefit of functi


ons!"
def build_sentence(info1):
print(str(info1) + "is a benefit of functions!")
return "%s is a benefit of functions!" % info1

def name_the_benefits_of_functions():
list_of_benefits = list_benefits()
for benefit in list_of_benefits:
print(build_sentence(benefit))

name_the_benefits_of_functions()

Dictionaries
A dictionary is a data type similar to arrays, but works with keys and values instead of indexes. Each value
stored in a dictionary can be accessed using a key, which is any type of object (a string, a number, a list, etc.)
instead of using its index to address it.

For example, a database of phone numbers could be stored using a dictionary like this:

In [ ]:

phonebook = {}
phonebook["John"] = 938477566
phonebook["Jack"] = 938377264
phonebook["Jill"] = 947662781
print(phonebook)

In [ ]:

mylist = [1,4,6,8,9,23]
print(mylist[0])
print(mylist[1])
print(mylist[2])
for i in mylist:
print(i)

file:///home/krdevkota/Downloads/Python_Slides_SudentCopy.html 22/37
11/20/2019 Python_Slides_SudentCopy

In [ ]:

mydetails = {"name" : "Karen", "address" : "Kathmandu", "phone":987964678}

print(mydetails["address"])
print(mydetails.keys())
print(mydetails.values())
print(mydetails.items())

In [ ]:

for i in mydetails.keys():
print(i)

In [ ]:

for i in mydetails.values():
print(i)

In [ ]:

for i, j in mydetails.items():
print(i,j)

Alternatively, a dictionary can be initialized with the same values in the following notation:

In [ ]:

phonebook = {"John" : 938477566, "Jack" : 938377264, "Jill" : 947662781


}

# print(phonebook.keys())
# print(phonebook.values())
phonebook["Jill"]

In [ ]:

phonebook = {
"John" : "Prasad",
"Jack" : "Shrestha",
"Jill" : "K.C."
}
phonebook

Iterating over dictionaries


Dictionaries can be iterated over, just like a list. However, a dictionary, unlike a list, does not keep the order of
the values stored in it. To iterate over key value pairs, use the following syntax:

file:///home/krdevkota/Downloads/Python_Slides_SudentCopy.html 23/37
11/20/2019 Python_Slides_SudentCopy

In [ ]:

phonebook = {"John" : 938477566,"Jack" : 938377264,"Jill" : 947662781}


for name, number in phonebook.items():
print("Phone number of %s is %d" % (name, number))
print("\n")
for name in phonebook.keys():
print("Phone number of %s is %d" % (name, phonebook[name]))
print("\n")
for i, j in phonebook.items():
print(i,j)

In [ ]:

phonebook.values()

Removing a value
To remove a specified index, use either one of the following notations:

In [ ]:

phonebook = {
"John" : 938477566,
"Jack" : 938377264,
"Jill" : 947662781
}
del phonebook["John"]
print(phonebook)

Alternatively:

In [ ]:

phonebook = {
"John" : 938477566,
"Jack" : 938377264,
"Jill" : 947662781
}
phonebook.pop("Jack")
print(phonebook)
phonebook["Jack"] = 98786547
print (phonebook)

Exercise
Add "Jake" to the phonebook with the phone number 938273443, and remove Jill from the phonebook.

file:///home/krdevkota/Downloads/Python_Slides_SudentCopy.html 24/37
11/20/2019 Python_Slides_SudentCopy

In [ ]:

phonebook = {
"John" : 938477566,
"Jack" : 938377264,
"Jill" : 947662781
}

# write your code here

# testing code
if "Jake" in phonebook:
print("Jake is listed in the phonebook.")
if "Jill" not in phonebook:
print("Jill is not listed in the phonebook.")

In [ ]:

phonebook = {
"John" : 938477566,
"Jack" : 938377264,
"Jill" : 947662781
}

# write your code here


phonebook["Jake"] = 938273443
del phonebook["Jill"]

# testing code
if "Jake" in phonebook:
print("Jake is listed in the phonebook.")
if "Jill" not in phonebook:
print("Jill is not listed in the phonebook.")

Modules and Packages


In programming, a module is a piece of software that has a specific functionality. For example, when building
a ping pong game, one module would be responsible for the game logic, and another module would be
responsible for drawing the game on the screen. Each module is a different file, which can be edited
separately.

Writing modules

Modules in Python are simply Python files with a .py extension. The name of the module will be the name of
the file. A Python module can have a set of functions, classes or variables defined and implemented. In the
example above, we will have two files, we will have:

mygame/ mygame/game.py mygame/draw.py

file:///home/krdevkota/Downloads/Python_Slides_SudentCopy.html 25/37
11/20/2019 Python_Slides_SudentCopy

The Python script game.py will implement the game. It will use the function draw_game from the file
draw.py, or in other words, the draw module, that implements the logic for drawing the game on the screen.

Modules are imported from other modules using the import command. In this example, the game.py script
may look something like this:

# game.py # import the draw module import draw def play_game(): ... def main(): result = play_game()
draw.draw_game(result) # this means that if this script is executed, then # main() will be executed if __name__
== '__main__': main()

The draw module may look something like this:

# draw.py def draw_game(): ... def clear_screen(screen): ...

In this example, the game module imports the load module, which enables it to use functions implemented
in that module. The main function would use the local function play_game to run the game, and then draw
the result of the game using a function implemented in the draw module called draw_game. To use the
function draw_game from the draw module, we would need to specify in which module the function is
implemented, using the dot operator. To reference the draw_game function from the game module, we would
need to import the draw module and only then call draw.draw_game().

When the import draw directive will run, the Python interpreter will look for a file in the directory which the
script was executed from, by the name of the module with a .py prefix, so in our case it will try to look for
draw.py. If it will find one, it will import it. If not, he will continue to look for built-in modules.

You may have noticed that when importing a module, a .pyc file appears, which is a compiled Python file.
Python compiles files into Python bytecode so that it won't have to parse the files each time modules are
loaded. If a .pyc file exists, it gets loaded instead of the .py file, but this process is transparent to the user.

Importing module objects to the current namespace

We may also import the function draw_game directly into the main script's namespace, by using the from
command.

# game.py # import the draw module from draw import draw_game def main(): result = play_game()
draw_game(result)

You may have noticed that in this example, draw_game does not precede with the name of the module it is
imported from, because we've specified the module name in the import command.

The advantages of using this notation is that it is easier to use the functions inside the current module
because you don't need to specify which module the function comes from. However, any namespace cannot
have two objects with the exact same name, so the import command may replace an existing object in the
namespace.

Importing all objects from a module

We may also use the import * command to import all objects from a specific module, like this:

file:///home/krdevkota/Downloads/Python_Slides_SudentCopy.html 26/37
11/20/2019 Python_Slides_SudentCopy

# game.py # import the draw module from draw import * def main(): result = play_game() draw_game(result)

This might be a bit risky as changes in the module might affect the module which imports it, but it is shorter
and also does not require you to specify which objects you wish to import from the module.

Custom import name

We may also load modules under any name we want. This is useful when we want to import a module
conditionally to use the same name in the rest of the code.

For example, if you have two draw modules with slighty different names - you may do the following:

# game.py # import the draw module if visual_mode: # in visual mode, we draw using graphics import
draw_visual as draw else: # in textual mode, we print out text import draw_textual as draw def main(): result =
play_game() # this can either be visual or textual depending on visual_mode draw.draw_game(result)## Module
initialization

The first time a module is loaded into a running Python script, it is initialized by executing the code in the
module once. If another module in your code imports the same module again, it will not be loaded twice but
once only - so local variables inside the module act as a "singleton" - they are initialized only once.

This is useful to know, because this means that you can rely on this behavior for initializing objects. For
example:

# draw.py def draw_game(): # when clearing the screen we can use the main screen object initialized in this
module clear_screen(main_screen) ... def clear_screen(screen): ... class Screen(): ... # initialize main_screen as
a singleton main_screen = Screen()

Extending module load path

There are a couple of ways we could tell the Python interpreter where to look for modules, aside from the
default, which is the local directory and the built-in modules. You could either use the environment variable
PYTHONPATH to specify additional directories to look for modules in, like this:

PYTHONPATH=/foo python game.py

This will execute game.py, and will enable the script to load modules from the foo directory as well as the
local directory.

Another method is the sys.path.append function. You may execute it before running an import
command:

sys.path.append("/foo")

This will add the foo directory to the list of paths to look for modules in as well.

Exploring built-in modules

You can find the full list of built-in modules in the Python standard library at https://docs.python.org/3/library/
(https://docs.python.org/3/library/)

file:///home/krdevkota/Downloads/Python_Slides_SudentCopy.html 27/37
11/20/2019 Python_Slides_SudentCopy

Two very important functions come in handy when exploring modules in Python - the dir and help
functions.

If we want to import the module urllib, which enables us to create read data from URLs, we simply
import the module:

# import the library import urllib # use it urllib.urlopen(...)

We can look for which functions are implemented in each module by using the dir function:

>>> import urllib >>> dir(urllib)

When we find the function in the module we want to use, we can read about it more using the help function,
inside the Python interpreter:

help(urllib.urlopen)

Writing packages

Packages are namespaces which contain multiple packages and modules themselves. They are simply
directories, but with a twist.

Each package in Python is a directory which MUST contain a special file called __init__.py. This file can
be empty, and it indicates that the directory it contains is a Python package, so it can be imported the same
way a module can be imported.

If we create a directory called foo, which marks the package name, we can then create a module inside that
package called bar. We also must not forget to add the __init__.py file inside the foo directory.

To use the module bar, we can import it in two ways:

import foo.bar

or:

from foo import bar

In the first method, we must use the foo prefix whenever we access the module bar. In the second method,
we don't, because we import the module to our module's namespace.

The __init__.py file can also decide which modules the package exports as the API, while keeping other
modules internal, by overriding the __all__ variable, like so:

__init__.py: __all__ = ["bar"]

Exercise

In this exercise, you will need to print an alphabetically sorted list of all functions in the re module, which
contain the word find.

file:///home/krdevkota/Downloads/Python_Slides_SudentCopy.html 28/37
11/20/2019 Python_Slides_SudentCopy

In [ ]:

import re
print(dir(re))
# Your code goes here

In [ ]:

import re
old_list = dir(re)
for member in old_list:
if "find" in member:
print (member)

Generators
Generators are very easy to implement, but a bit difficult to understand.

Generators are used to create iterators, but with a different approach. Generators are simple functions which
return an iterable set of items, one at a time, in a special way.

When an iteration over a set of item starts using the for statement, the generator is run. Once the generator's
function code reaches a "yield" statement, the generator yields its execution back to the for loop, returning a
new value from the set. The generator function can generate as many values (possibly infinite) as it wants,
yielding each one in its turn.

Here is a simple example of a generator function which returns 7 random integers:

In [ ]:

import random

def lottery():
# returns 6 numbers between 1 and 40
for i in range(6):
yield random.randint(1, 40)

# returns a 7th number between 1 and 15


yield random.randint(1,15)

for random_number in lottery():


print("And the next number is... %d!" %(random_number))

This function decides how to generate the random numbers on its own, and executes the yield statements
one at a time, pausing in between to yield execution back to the main for loop.

Exercise

file:///home/krdevkota/Downloads/Python_Slides_SudentCopy.html 29/37
11/20/2019 Python_Slides_SudentCopy

Write a generator function which returns the Fibonacci series. They are calculated using the following
formula: The first two numbers of the series is always equal to 1, and each consecutive number returned is
the sum of the last two numbers. Hint: Can you use only two variables in the generator function? Remember
that assignments can be done simultaneously. The code

In [ ]:

a = 1
b = 2
a, b = b, a
print(a,b)

will simultaneously switch the values of a and b.

In [ ]:

# fill in this function


def fib():
pass #this is a null statement which does nothing when executed, useful as a
placeholder.

# testing code
import types
if type(fib()) == types.GeneratorType:
print("Good, The fib function is a generator.")

counter = 0
for n in fib():
print(n)
counter += 1
if counter == 10:
break

In [ ]:

# fill in this function


def fib():
a, b = 1, 1
while 1:
yield a
a, b = b, a + b

# testing code
import types
if type(fib()) == types.GeneratorType:
print("Good, The fib function is a generator.")

counter = 0
for n in fib():
print(n)
counter += 1
if counter == 10:
break

List Comprehensions
file:///home/krdevkota/Downloads/Python_Slides_SudentCopy.html 30/37
11/20/2019 Python_Slides_SudentCopy

List Comprehensions is a very powerful tool, which creates a new list based on another list, in a single,
readable line.

For example, let's say we need to create a list of integers which specify the length of each word in a certain
sentence, but only if the word is not the word "the".

In [ ]:

sentence = "the quick brown fox jumps over the lazy dog"
words = sentence.split()
word_lengths = []
for word in words:
if word != "the":
word_lengths.append(len(word))
print(words)
print(word_lengths)

Using a list comprehension, we could simplify this process to this notation:

In [ ]:

sentence = "the quick brown fox jumps over the lazy dog"
words = sentence.split()
word_lengths = [len(word) for word in words if word != "the"]
print(words)
print(word_lengths)

Exercise
Using a list comprehension, create a new list called "newlist" out of the list "numbers", which contains only
the positive numbers from the list, as integers.

In [ ]:

numbers = [34.6, -203.4, 44.9, 68.3, -12.2, 44.6, 12.7]


newlist = []
print(newlist)

In [ ]:

numbers = [34.6, -203.4, 44.9, 68.3, -12.2, 44.6, 12.7]


newlist = [int(x) for x in numbers if x > 0]
print(newlist)

Multiple Function Arguments


Every function in Python receives a predefined number of arguments, if declared normally, like this:

def myfunction(first, second, third): # do something with the 3 variables ...

It is possible to declare functions which receive a variable number of arguments, using the following syntax:

file:///home/krdevkota/Downloads/Python_Slides_SudentCopy.html 31/37
11/20/2019 Python_Slides_SudentCopy

In [ ]:

def foo(first, second, third, *therest):


print("First: %s" % first)
print("Second: %s" % second)
print("Third: %s" % third)
print("And all the rest... %s" % list(therest))

The "therest" variable is a list of variables, which receives all arguments which were given to the "foo"
function after the first 3 arguments. So calling foo(1,2,3,4,5) will print out:

In [ ]:

def foo(first, second, third, *therest):


print("First: %s" %(first))
print("Second: %s" %(second))
print("Third: %s" %(third))
print("And all the rest... %s" %(list(therest)))

foo(1,2,3,4,5)

It is also possible to send functions arguments by keyword, so that the order of the argument does not
matter, using the following syntax. The following code yields the following output: The sum is: 6
Result: 1

In [ ]:

def bar(first, second, third, **options):


if options.get("action") == "sum":
print("The sum is: %d" %(first + second + third))

if options.get("number") == "first":
return first

result = bar(1, 2, 3, action = "sum", number = "first")


print("Result: %d" %(result))

The "bar" function receives 3 arguments. If an additional "action" argument is received, and it instructs on
summing up the numbers, then the sum is printed out. Alternatively, the function also knows it must return the
first argument, if the value of the "number" parameter, passed into the function, is equal to "first".

Exercise
Fill in the foo and bar functions so they can receive a variable amount of arguments (3 or more) The foo
function must return the amount of extra arguments received. The bar must return True if the argument with
the keyword magicnumber is worth 7, and False otherwise.

file:///home/krdevkota/Downloads/Python_Slides_SudentCopy.html 32/37
11/20/2019 Python_Slides_SudentCopy

In [ ]:

# edit the functions prototype and implementation


def foo(a, b, c):
pass

def bar(a, b, c):


pass

# test code
if foo(1,2,3,4) == 1:
print("Good.")
if foo(1,2,3,4,5) == 2:
print("Better.")
if bar(1,2,3,magicnumber = 6) == False:
print("Great.")
if bar(1,2,3,magicnumber = 7) == True:
print("Awesome!")

In [ ]:

# edit the functions prototype and implementation


def foo(a, b, c, *args):
return len(args)

def bar(a, b, c, **kwargs):


return kwargs["magicnumber"] == 7

# test code
if foo(1,2,3,4) == 1:
print("Good.")
if foo(1,2,3,4,5) == 2:
print("Better.")
if bar(1,2,3,magicnumber = 6) == False:
print("Great.")
if bar(1,2,3,magicnumber = 7) == True:
print("Awesome!")

Regular Expressions
Regular Expressions (sometimes shortened to regexp, regex, or re) are a tool for matching patterns in text. In
Python, we have the re module. The applications for regular expressions are wide-spread, but they are fairly
complex, so when contemplating using a regex for a certain task, think about alternatives, and come to
regexes as a last resort.

An example regex is r"^(From|To|Cc).*?python-list@python.org" Now for an explanation: the


caret ^ matches text at the beginning of a line. The following group, the part with (From|To|Cc) means that
the line has to start with one of the words that are separated by the pipe |. That is called the OR operator,
and the regex will match if the line starts with any of the words in the group. The .*? means to un-greedily
match any number of characters, except the newline \n character. The un-greedy part means to match as
few repetitions as possible. The . character means any non-newline character, the * means to repeat 0 or
more times, and the ? character makes it un-greedy.

file:///home/krdevkota/Downloads/Python_Slides_SudentCopy.html 33/37
11/20/2019 Python_Slides_SudentCopy

So, the following lines would be matched by that regex: From: python-list@python.org To: !asp]
<,. python-list@python.org

Exercise
In [ ]:

# Example:
import re
pattern = re.compile(r"\[(on|off)\]") # Slight optimization
print(re.search(pattern, "Mono: Playback 65 [75%] [-16.50dB] [on]"))
# Returns a Match object!
print(re.search(pattern, "Nada...:-("))
# Doesn't return anything.
# End Example

# Exercise: make a regular expression that will match an email


def test_email(your_pattern):
pattern = re.compile(your_pattern)
emails = ["john@example.com", "python-list@python.org", "wha.t.`1an?ug{}ly@e
mail.com"]
for email in emails:
if not re.match(pattern, email):
print("You failed to match %s" % (email))
elif not your_pattern:
print("Forgot to enter a pattern!")
else:
print("Pass")
pattern = r"" # Your pattern here!
test_email(pattern)

In [ ]:

# Exercise: make a regular expression that will match an email


import re
def test_email(your_pattern):
pattern = re.compile(your_pattern)
emails = ["john@example.com", "python-list@python.org", "wha.t.`1an?ug{}ly@e
mail.com"]
for email in emails:
if not re.match(pattern, email):
print("You failed to match %s" % (email))
elif not your_pattern:
print("Forgot to enter a pattern!")
else:
print("Pass")
# Your pattern here!
pattern = r"\"?([-a-zA-Z0-9.`?{}]+@\w+\.\w+)\"?"
test_email(pattern)

Exception Handling

file:///home/krdevkota/Downloads/Python_Slides_SudentCopy.html 34/37
11/20/2019 Python_Slides_SudentCopy

When programming, errors happen. It's just a fact of life. Perhaps the user gave bad input. Maybe a network
resource was unavailable. Maybe the program ran out of memory. Or the programmer may have even made
a mistake!

Python's solution to errors are exceptions. You might have seen an exception before.

In [ ]:

print(a)

#error
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
NameError: name 'a' is not defined
</module></stdin>

Oops! Forgot to assign a value to the 'a' variable.

But sometimes you don't want exceptions to completely stop the program. You might want to do something
special when an exception is raised. This is done in a try/except block.

Here's a trivial example: Suppose you're iterating over a list. You need to iterate over 20 numbers, but the list
is made from user input, and might not have 20 numbers in it. After you reach the end of the list, you just
want the rest of the numbers to be interpreted as a 0. Here's how you could do that:

In [ ]:

def do_stuff_with_number(n):
print(n)

the_list = (1, 2, 3, 4, 5)

There, that wasn't too hard! You can do that with any exception. For more details on handling exceptions,
look no further than https://docs.python.org/3/tutorial/errors.html#handling-exceptions
(https://docs.python.org/3/tutorial/errors.html#handling-exceptions)

Exercise

file:///home/krdevkota/Downloads/Python_Slides_SudentCopy.html 35/37
11/20/2019 Python_Slides_SudentCopy

In [ ]:

# Handle all the exceptions!


#Setup
actor = {"name": "John Cleese", "rank": "awesome"}

#Function to modify, should return the last name of the actor - think back to pr
evious lessons for how to get it
def get_last_name():
return actor["last_name"]

#Test code
get_last_name()
print("All exceptions caught! Good job!")
print("The actor's last name is %s" % get_last_name())

In [ ]:

actor = {"name": "John Cleese", "rank": "awesome"}

def get_last_name():
return actor["name"].split()[1]

get_last_name()
print("All exceptions caught! Good job!")
print("The actor's last name is %s" % get_last_name())

Sets
Sets are lists with no duplicate entries. Let's say you want to collect a list of words used in a paragraph:

In [ ]:

print(set("my name is Eric and Eric is my name".split()))

In [ ]:

a = [1,2,1,3,4,5,7,5]
b = set(a)

This will print out a list containing "my", "name", "is", "Eric", and finally "and". Since the rest of the sentence
uses words which are already in the set, they are not inserted twice.

Sets are a powerful tool in Python since they have the ability to calculate differences and intersections
between other sets. For example, say you have a list of participants in events A and B:

In [ ]:

a = set(["Jake", "John", "Eric"])


print(a)
b = set(["John", "Jill"])
print(b)

To find out which members attended both events, you may use the "intersection" method:

file:///home/krdevkota/Downloads/Python_Slides_SudentCopy.html 36/37
11/20/2019 Python_Slides_SudentCopy

In [ ]:

a = set(["Jake", "John", "Eric"])


b = set(["John", "Jill"])

print(a.intersection(b))
print(b.intersection(a))

To find out which members attended only one of the events, use the "symmetric_difference" method:

To find out which members attended only one event and not the other, use the "difference" method:

In [ ]:

a = set(["Jake", "John", "Eric"])


b = set(["John", "Jill"])

print(a.difference(b))
print(b.difference(a))

To receive a list of all participants, use the "union" method:

In [ ]:

a = set(["Jake", "John", "Eric"])


b = set(["John", "Jill"])

print(a.union(b))

Exercise
In the exercise below, use the given lists to print out a set containing all the participants from event A which
did not attend event B.

In [ ]:

a = ["Jake", "John", "Eric"]


b = ["John", "Jill"]

In [ ]:

a = ["Jake", "John", "Eric"]


b = ["John", "Jill"]

A = set(a)
B = set(b)

print(A.difference(B))

file:///home/krdevkota/Downloads/Python_Slides_SudentCopy.html 37/37

You might also like