lecture 3
lecture 3
If condition
a = 200
b = 33
if b > a:
print("b is greater than a")
elif a == b:
print("a and b are equal")
else:
print("a is greater than b")
For Loops
for x in adj:
for y in fruits:
print(x, y)
function
Select this paragraph to edit
Why even use functions?
• you should use functions when you plan on using a block of code
multiple times. The function will allow you to call the same block of
code without having to write it multiple times. This in turn will allow
you to create more complex Python scripts.
• It is very important to get practice combining everything you’ve
learned so far (control flow, loops, etc.) with functions to become an
effective programmer.
• Creating a function requires a very specific syntax, including the def
keyword, correct indentation, and proper structure.
Select this paragraph to edit
def my_function():
print("Hello from a function")
my_function()
Arguments
• Arguments are specified after the function name, inside the parentheses. You can add as many
arguments as you want, just separate them with a comma.
• The terms parameter and argument can be used for the same thing: information that are passed
into a function.
def my_function(arg1,arg2):
'''
This is where the function's Document String (docstring) goes.
When you call help() on your function it will be printed out.
'''
# Do stuff here
# Return desired result
my_function(x,y)
Select this paragraph to edit
def name_of_function():
Keyword telling
Python this is a
function.
Select this paragraph to edit
def name_of_function():
A colon indicates an
upcoming indented block.
Everything indented is then
“inside” the function
Select this paragraph to edit
def name_of_function():
’’’
Docstring explains function.
’’’
>> Hello
Select this paragraph to edit
def name_of_function():
’’’
Docstring explains function.
’’’
print(“Hello”)
>> name_of_function()
>> Hello
Resulting Output
Select this paragraph to edit
def name_of_function(name):
’’’
Docstring explains function.
’’’
print(“Hello ”+name)
>> print(result)
>> 3
Select this paragraph to edit
def add_function(num1,num2):
return num1+num2
Most functions will
>> result = add_function(1,2) use return. Rarely
>>
will a function only
print()
>> print(result)
>> 3
Return and print
def sum_numbers(x,y):
return x+y
total=sum_numbers(8,7)
------------------------------------------
def sum_numbers(x,y):
print(x+y)
total=sum_numbers(8,7)
Arguments
● By default, a function must be called with the correct number of
arguments. Meaning that if your function expects 2 arguments, you have
to call the function with 2 arguments, not more, and not less.
def my_function(a, b):
print(a + " " + b)
my_function("Emil")
Default Parameter Value
● The following example shows how to use a default parameter value.
● If we call the function without argument, it uses the default value:
def my_function(country = "Norway"):
print("I am from " + country)
my_function("India")
my_function()
my_function("Brazil")
-------------------------------------
def sum(a=0,b=3,c=10):
print(a+b+c)
sum(1,3)
sum(3,9,-2)
sum()
Select this paragraph to edit
def details(item,price,disc=0):
print(f'The price of the {item} is {price} and the discount is {disc}%')
details('Ball',45)
details('Bat',100,5)
details('Cap') ------------------(TypeError)
Keyword Arguments
● You can also send arguments with the key = value syntax.
● This way the order of the arguments does not matter.
def func():
x=2
print('This function is now using the global x!')
print('Because of global x is: ', x)
def func():
global x
print('This function is now using the global x!')
print('Because of global x is: ', x)
x=2
print('Ran func(), changed global x to', x)
lesser_of_two_evens(2,4) --> 2
lesser_of_two_evens(2,5) --> 5
exception
• An exception is an event, which occurs during the execution of a
program that disrupts the normal flow of the program's instructions.
In general, when a Python script encounters a situation that it cannot
cope with, it raises an exception. An exception is a Python object that
represents an error.
• When a Python script raises an exception, it must either handle the
exception immediately otherwise it terminates and quits.
exception
• If you have some suspicious code that may raise an exception, you
can defend your program by placing the suspicious code in a try:
block. After the try: block, include an except: statement, followed by
a block of code which handles the problem as elegantly as possible.
• The try block lets you test a block of code for errors.
• The except block lets you handle the error.
• The else block lets you execute code when there is no error.
• The finally block lets you execute code, regardless of the result of the
try- and except blocks.
Syntax
try:
You do your operations here;
......................
except ExceptionI:
If there is ExceptionI, then execute this block.
except ExceptionII:
If there is ExceptionII, then execute this block.
......................
else:
If there is no exception then execute this block.
Exception Handling
• When an error occurs, or exception as we call it, Python will normally stop
and generate an error message.
• These exceptions can be handled using the try statement:
• Example
• The try block will generate an exception, because x is not defined:
try:
print(x)
except:
print("An exception occurred")
• Since the try block raises an error, the except block will be executed.
• Without the try block, the program will crash and raise an error:
Many Exceptions
• You can define as many exception blocks as you want, e.g. if you want to
execute a special block of code for a special kind of error:
• Example
• Print one message if the try block raises a NameError and another for other
errors:
try:
print(x)
except NameError:
print("Variable x is not defined")
except:
print("Something else went wrong")
Else
• You can use the else keyword to define a block of code to be executed if no
errors were raised:
• In this example, the try block does not generate any error:
try:
print("Hello")
except:
print("Something went wrong")
else:
print("Nothing went wrong")
Finally