Programming Essentials in Python
Programming Essentials in Python
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: ")
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)
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).
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)
• 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.
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))
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.