Download as pdf or txt
Download as pdf or txt
You are on page 1of 23

Programming Essentials in Python

Introduction to Python
You will learn about:
• Defining and using functions;
• Different ways of passing arguments;
• Name scopes;
• Tuples and dictionaries;
• Data processing.
• Modules, packages
function
def functionName():
4 spaces |tab functionBody
Your first function
def message():
print("Enter a value: ")
a = int(input())
print("Enter a value: ")

print("Enter a value: ") message()


def message():
b = int(input()) a = int(input())
print("Enter a value: ")
message()
print("Enter a value: ") b = int(input())
c = int(input()) message()
c = int(input())
To invoke this function in your code, use message()
Notes
1 : Python reads your code from top to bottom.
2 : You mustn't have a function and a variable of the same name.
Parametrized functions
A parameter is a variable. There are two types of variables
• parameters exist only inside functions in which they have been defined, and the only place where the parameter
can be defined is a space between a pair of parentheses in the def statement;
• assigning a value to the parameter is done at the time of the function's invocation, by specifying the
corresponding argument.

def message(number): shadowing:


#As many parameters as you want
### to have a variable named the same as
def message(what, number):
a function's parameter.
print("Enter", what, "number", number)
def message(number):
Task 1 min print("Enter a number:", number)
message("telephone", 11)
Run this code message("price", 5)
def message(number): number = 1234
message("number", "number")
print("Enter a number:", number) message(1)
print(number)
#Output
message() Enter telephone number 11
#Output
Enter price number 5
# How to solve it ? 1
Enter number number number
1234
Keyword argument passing
the meaning of the argument is dictated by its name. mustn't use a non-existent parameter name.

default (predefined) parameters values


def introduction(firstName, lastName): def introduction(firstName, lastName="Smith"):
print("Hello, my name is", firstName, lastName) print("Hello, my name is", fistName, lastName)
….
introduction(firstName = "James", lastName = "Bond") introduction("James", "Doe")
introduction(lastName = "Skywalker", firstName = "Luke") introduction("Henry")
introduction(firstName="William")

def sum(a, b, c):


print(a, "+", b, "+", c, "=", a + b + c)
What is the output ?
sum(1, 2, 3) 1+2+3=6
sum(c = 1, a = 2, b = 3) 2+3+1=6 def intro(a="James Bond", b="Bond"): def intro(a, b="Bond"):
print("My name is", b + ".", a + ".") print("My name is", b + ".", a + ".")
sum(3, c = 1, b = 2) 3+2+1=6 intro() intro("Susan")

sum(3, a = 1, b = 2) error def intro(a="James Bond", b="Bond"): def sum(a, b=2, c):
print("My name is", b + ".", a + ".") print(a + b + c)
intro(b="Sean Connery") sum(a=1, c=3)
Returning a result from a function
return with an expression
return without an expression function():
it causes the immediate termination return expression
of the function's execution.
def boringFuncton():
NOTE: return, terminates a function's activities on return 123
demand, before the control reaches the function's x = boringFunction()
last line. print("The boringFunction has returned its result. It's:", x)
def happyNewYear(wishes = True): NOTE:
print("Three...") The keyword None doesn't represent any reasonable value , it's not a value at
print("Two...") all; it mustn't take part in any expressions. Ex: print(None + 2) → error
print("One...")
if not wishes: Function and lists (Try this code) Example-1
return def sumOfList(lst):
print("Happy New Year!") What is the result ? Try in your PC sum = 0
….. def strangeFunction(n): for elem in lst:
happyNewYear() if(n % 2 == 0): sum += elem
happyNewYear(False) return True return sum
print(strangeFunction(2)) print(sumOfList([5, 4, 3])) → 12
print(strangeFunction(1)) print(sumOfList([5])) -→ ?
print(sumOfList(5,))→ ?
Continue from the previous slide (Example-2)
def strangeListFunction(n):
strangeList = []
LAB_3.1
Your task is to write and test a function which takes one for i in range(0, n):
strangeList.insert(0, i)
From example -1,2 we
argument (a year) and returns True if the year is a leap year, can conclude that List
or False otherwise. return strangeList can be sent and received
by a function
print(strangeListFunction(5))
The seed of the function is already sown in the skeleton code
in the editor.

Note: we've also prepared a short testing code, which you can def isYearLeap(year):
use to test your function. #
# put your code here
#
The code uses two lists - one with the test data, and the other
containing the expected results. The code will tell you if any of testData = [1900, 2000, 2016, 1987]
your results are invalid. testResults = [False, True, True, False]
for i in range(len(testData)):
yr = testData[i]
print(yr,"->",end="")
result = isYearLeap(yr)
if result == testResults[i]:
print("OK")
else:
print("Failed")
def isYearLeap(year):
#
LAB-3.2 # your code from LAB 4.1.3.6
Your task is to write and test a function which takes two #
arguments (a year and a month) and returns the number of
days for the given month/year pair (while only February is def daysInMonth(year, month):
sensitive to the year value, your function should be universal). #
# put your new code here
The initial part of the function is ready. Now, convince the #
function to return None if its arguments don't make sense.
testYears = [1900, 2000, 2016, 1987]
Of course, you can (and should) use the previously written and testMonths = [2, 2, 1, 11]
tested function (LAB 3.1). It may be very helpful. We encourage testResults = [28, 29, 31, 30]
you to use a list filled with the months' lengths. You can create for i in range(len(testYears)):
it inside the function - this trick will significantly shorten the yr = testYears[i]
code. mo = testMonths[i]
print(yr, mo, "->", end="")
We've prepared a testing code. Expand it to include more test result = daysInMonth(yr, mo)
cases. if result == testResults[i]:
print("OK")
else:
print("Failed")
def scopeTest():
x = 123

Functions and scopes The scope of a name (e.g., a variable name) is the part of scopeTest()
a code where the name is properly recognizable. print(x)
#1) a variable existing outside a function has a scope inside the functions' bodies. #OT NameError: name 'x' is not defined
#1)
#2) A variable existing outside a function has a scope inside the functions’ def myFunction():
bodies, excluding those of them which define a variable of the same name. print("Do I know that variable?", var)
#3) The global keyword extend a variable's scope in a way which includes var = 1
the functions' bodies. global name myFunction()
Example global name1, name2, ... print(var)
def myFunction(n): #OT
print("I got", n) #3)
n += 1 def myFunction():
print("I have", n) global var #2)
var = 2 def myFunction():
var = 1 print("Do I know that variable?", var) var = 2
myFunction(var) var = 1 print("Do I know that variable?", var)
print(var) myFunction() var = 1
#OT print(var) myFunction()
I got 1 #OT print(var)
I have 2 Do I know that variable? 2 OT#
1 2 Do I know that variable? 2
1
Checkpoint ( What is the output?)
1 def hi(): 5 def message():
return alt = 1
print("Hi!") print("Hello, World!")
hi()
print(alt)

2 def isInt(data): 6 a=1


if type(data) == int: def fun():
return True a=2
elif type(data) == float: print(a)
return False fun()
print(isInt(5)) print(a)
print(isInt(5.0))
print(isInt("5"))

3 def evenNumLst(ran): 7 a=1


lst = [] def fun():
for num in range(ran): global a
if num % 2 == 0: a=2
lst.append(num) print(a)
return lst fun()
a=3
print(evenNumLst(11)) print(a)

4 def listUpdater(lst): 8 a=1


updList = []
for elem in lst: def fun():
elem **= 2 global a
updList.append(elem) a=2
return updList print(a)

l = [1, 2, 3, 4, 5] a=3
print(listUpdater(l)) fun()
print(a)
Task 2 min
Task 1 min Analyze the code
What is this code for ? def fib(n):
def factorialFun(n): if n < 1:
if n < 0: return None
return None if n < 3:
if n < 2: return 1
return 1
elem1 = elem2 = 1
product = 1 sum = 0
for i in range(2, n + 1): for i in range(3, n + 1):
product *= i sum = elem1 + elem2
return product elem1, elem2 = elem2, sum
return sum
for n in range(1, 6): # testing
print(n, factorialFun(n)) for n in range(1, 10): # testing
print(n, "->", fib(n))
Commas for tuples, no commas will produce
tuple1 = (1, 2, 4, 8) ordinary variables not tuples.
Tuples . A tuple is an immutable sequence type. tuple2 = 1., .5, .25, .125
Each tuple element may be of a different type (floating-point, integer, or any other not-as-yet-introduced kind of data).

Task 1 min (try) Task 2 min ( try)


myTuple = (1, 10, 100, 1000) var = 123
Task 1 min ( try)
myTuple = (1, 10, 100) t1 = (1, )
print(myTuple[0])
print(myTuple[-1]) t2 = (2, )
t1 = myTuple + (1000, 10000) t3 = (3, var)
print(myTuple[1:])
t2 = myTuple * 4
print(myTuple[:-2])
t1, t2, t3 = t2, t3, t1
print(len(t2))
for elem in myTuple:
print(t1) print(t1, t2, t3)
print(elem)
print(t2) Note1 : it should be clear why t1
print(10 in myTuple) becomes t2, t2 becomes t3, and t3
Note: same operations in list but
print(-10 not in myTuple) becomes t1, its clear right ?
remember to not modify the
tuple. Note2 :variables can be used in the
tuples as well.
What is a dictionary?
The dictionary is another Python data structure. It's not a sequence type and it is mutable.
a dictionary is a set of key-value pairs. Example cat : chat
dict = {"cat" : "chat", "dog" : "chien", "horse" : "cheval"}
phoneNumbers = {'boss' : 5551234567, 'Suzy' : 22657854310}
1. Each key must be unique - it's not possible to emptyDictionary = {}
have more than one key of the same value;
2. A key may be data of any type: it may be a print(dict)
number (integer or float), or even a string; print(phoneNumbers)
3. A dictionary is not a list - a list contains a set print(emptyDictionary)
of numbered values, while a dictionary holds
pairs of values; How to use a dictionary? print(dict['cat'])
4. The len() function works for dictionaries, too - • you have to deliver a valid key value print(phoneNumbers['Suzy'])
it returns the numbers of key-value elements • you mustn't use a non-existent key.
in the dictionary;
5. A dictionary is a one-way tool - if you have an dict = {"cat" : "chat", "dog" : "chien", "horse" : "cheval"}
words = ['cat', 'lion', 'horse']
English-French dictionary, you can look for
Pay attention to the use of
French equivalents of English terms, but not for word in words:
if word in dict: the keyword in to avoid non-
vice versa. print(word, "->", dict[word]) existent key
else:
print(word, "is not in dictionary")
How to use a dictionary: the keys() What do you think ?
Can dictionaries be browsed using the for loop, like lists or tuples?
dict = {"cat" : "chat", "dog" : "chien", "horse" : "cheval"}
for key in dict.keys():
print(key)
print(key, "->", dict[key]) You can use also the sort() method to get sorted
for key in sorted(dict.keys()):

How to use a dictionary: The item() and values() methods


There is also a method named values(), which works similarly
The items(). method returns a list of tuples
to keys(), but returns a list of values.

dict = {"cat" : "chat", "dog" : "chien", "horse" : "cheval"} dict = {"cat" : "chat", "dog" : "chien", "horse" : "cheval"}
for english, french in dict.items(): for value in dict.values():
print(english, "->", french) print(value)

How to use a dictionary: modifying and adding values


Modifying Adding
dict = {"cat" : "chat", "dog" : "chien", "horse" : "cheval"} dict = {"cat" : "chat", "dog" : "chien", dict = {"cat" : "chat", "dog" : "chien",
"horse" : "cheval"} "horse" : "cheval"}
dict['cat'] = 'minou' dict.update({"duck" : "canard"})
dict['swan'] = 'cygne'
print(dict) print(dict) print(dict)
dict = {"cat" : "chat", "dog" : "chien", "horse" : "cheval"}

Removing a key del dict['dog']


removing a key will always cause the removal of the associated print(dict)
value. Values cannot exist without their keys.
dict = {"cat" : "chat", "dog" : "chien", "horse" : "cheval"}
To remove the last item in a dictionary, you can use the
dict.popitem()
popitem() method: print(dict) # outputs: {'cat' : 'chat', 'dog' : 'chien'}
What is the output ?
#Task ( analyze the code) (important !)
1 myTup = (1, 2, 3) 5* l = ["car", "Ford", "flower", "Tulip"] # this is list
print(myTup[2]) t = tuple(l)
while True:
print(t) name = input("Enter the student's name (or type exit to stop): ")
if name == 'exit':
2 tup = 1, 2, 3 6* colors = (("green", "#008000"), ("blue", "#0000FF")) break
a, b, c = tup colDict = dict(colors)
print(a * b * c) print(colDict)
score = int(input("Enter the student's score (0-10): "))
3 Complete the code to correctly use the 7 myDict = {"A":1, "B":2}
count() method to find the number of copyMyDict = myDict.copy() if name in schoolClass:
duplicates of 2 in the following tuple. myDict.clear() schoolClass[name] += (score,)
tup = 1, 2, 3, 2, 4, 5, 6, 2, 7, 2, 8, 9 print(copyMyDict) else:
duplicates = # your code schoolClass[name] = (score,)
print(duplicates)
4 Write a program that will "glue" the two 8 colors = { for name in sorted(schoolClass.keys()):
dictionaries (d1 and d2) together and "white" : (255, 255, 255), sum = 0
create a new one (d3) "grey" : (128, 128, 128), counter = 0
d1 = {'Adam Smith':'A', 'Judy Paxton':'B+'} "red" : (255, 0, 0), for score in schoolClass[name]:
d2 = {'Mary Louis':'A', 'Patrick White':'C'} "green" : (0, 128, 0) sum += score
d3 = {} }
counter += 1
for item in (d1, d2): for col, rgb in colors.items():
# your code print(col, ":", rgb)
print(name, ":", sum / counter)
print(d3)
What is a module? https://docs.python.org/3/library/index.html

• The first (probably the most common) happens when you want to use an already existing module, written by
someone else, or created by yourself during your work on some complex project - in this case you are the module's
user;
• The second occurs when you want to create a brand new module, either for your own use, or to make other
programmers' lives easier - you are the module's supplier.
To make use of module:
#First method Each module consists of entities (like a book
import math, sys consists of chapters). These entities can be
functions, variables, constants, classes, and
objects. If you know how to access a particular
Namespace module, you can make use of any of the entities it
stores.

To use an entity from a module


• the name of the module (math here) import math
To implement sin(1/2π) in python math.pi • a dot; print(math.sin(math.pi/2))
• the name of the entity (pi here) # output is 1.0
useing math module math.sin
from math import sin, pi Task, try in your PC. Why pi in the
#Second method function is the same pi from
from math import pi print(sin(pi/2)) math?
#Output is 1.0 import math

def sin(x):
The names of the imported entities are accessible without qualification. In this way if 2 * x == pi:
return 0.99999999
the pi from the module supersede the existing one. else:
return None

pi = 3.14
#Third method
from module import * print(sin(pi/2))
from math import pi print(math.sin(math.pi/2))

imports all entities from the indicated module

Importing a module: the as keyword


If you use the import module variant and you don't like a particular module's name (e.g., it's the same as one of your already
defined entities, so qualification becomes troublesome) you can give it any name you like - this is called aliasing.
import math as m import math as m
import module as alias print(m.sin(m.pi/2))
print(m.sin(m.pi/2))

from module import name as alias from math import pi as PI, sin as sine
print(sine(PI/2))
Working with standard modules( some modules )

from math import ceil, floor, trunc #Try this code in your PC
x = 1.4 from random import choice, sample
y = 2.6
print(floor(x), floor(y)) dir() function in pyhton
print(floor(-x), floor(-y))
lst = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
print(ceil(x), ceil(y))
it can reveal all the names provided through a
print(ceil(-x), ceil(-y)) print(choice(lst)) particular module.
print(trunc(x), trunc(y)) print(sample(lst, 5)) dir(module)
print(trunc(-x), trunc(-y))impo
print(sample(lst, 10))
Try in your PC. Try in your PC.
Import math Import socket
dir (math) dir (socket)
#platform(aliased = False, terse = False)
from platform import platform

print(platform())
print(platform(1))
Please see the entities of the socket lab
print(platform(0, 1))
https://docs.python.org/3/library/socket.html
#print(machine()) → make it useable
#print(system()) → make it useable For all the modules in Python
#print(processor())→ make it useable https://docs.python.org/3/py-modindex.html.
#print (version())
Packages in Pyhthon
• A module is a kind of container filled with functions
• Group your functions carefully and name the module containing them in a
clear and intuitive way
• Group your modules exactly in the same way as you've previously grouped
functions - is there a more general container than a module?
• Package plays a similar role to a folder/directory in the world of files.

Your first module

TASK: create your first module


1- create new folder Continue the previous Task
2- create empty file module.py Continue the previous TASK 1-in module.py print something
3- create another file main.py 1- open the folder that you 2- run main.py
4- in main.py import module.py created. 3- in module write print (__name__)
What do you see? 4- run module.py
5- run main.py
5-run main.py
If every thig went ok, you will
see ________
__name__ is just a variable
Your first module: continued Analyze each line carfully

Continue the previous Task


1- in module.py create counter = 0
2- amend the main.py by adding print 1- The line starting with #! has many names - it
(module.counter) may be called shabang, shebang, hashbang,
3- run main.py poundbang
2-a string (maybe a multiline) placed before
Unlike many other programming any module instructions (including imports) is
languages, Python has no means of called the doc-string, and should briefly
allowing you to hide such variables explain the purpose and contents of the
module.
from the eyes of the module's users.
2- the functions defined inside the module
There is a convention to put only _ or (suml() and prodl()) are available for import.
__ preceds the variable. 3- use the __name__ variable to detect when
the file is run stand-alone, and seized this
opportunity to perform some simple tests.
Question : why there are two \\
How Python searches for modules
not \ ?

Creating package from modules


1- assume that extra is the name of a newly created package (think of it
as the package's root), it will impose a naming rule which allows you to
clearly name every entity from the tree.
the location of a function named funT() from the tau package may be
described as: extra.good.best.tau.funT() extra.ugly.psi.funP()
Creating package from modules (cont.)
• How do you transform such a tree (actually, a subtree) into a real Python package
Python expects that there is a file with a very unique name inside the package's folder: __init__.py.
The content of the file is executed when any of the package's modules is imported. You can leave the file empty, but you
mustn't omit it.
• Where do you put the subtree to make it accessible to Python?
anywhere You only have to ensure that Python is aware of the package's location. You already know how to do that! Right?
LAB_3.3
We’ve send a zip file containing all the files from the packages branch. You can download it
and use it for your this experiments, but remember to unpack it in the folder presented in
the scheme, otherwise, it won't be accessible to the code from the main file.
You'll be continuing your experiments using the main2.py file.
1- access the funI() function from the iota module from the top of the extra package

2- get access to the sigma and tau modules. # 1 main2.py


from sys import
#2 pathpath.append('..\\packages’)
from sys import path ######### enter your code here
##### print(extra.iota.funI())
#####
#####
print(extra.good.best.sigma.funS()) # 3 main2.py
print(funT()) from sys import path
path.append('..\\packages’)
3- You can make your life easier by using aliasing import extra.good.best.sigma as sig
import extra.good.alpha as alp
print(#.funS())
print(#.funA())
• The defining and using of functions - their rationale, purpose, conventions, and traps;
• The concept of passing arguments in different ways and setting their default values, along
with the mechanisms of returning the function's results;
• Name scope issues;
• New data aggregates: tuples and dictionaries, and their role in data processing.
• What is the module and how to create new module
• Collect group of modules in a package and how to use a modules in a package

You might also like