0% found this document useful (0 votes)
11 views

lecture 3

تتت

Uploaded by

medoameen763023
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
11 views

lecture 3

تتت

Uploaded by

medoameen763023
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 41

Review for previous lecture

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

• The range() Function


for x in range(6):
print(x)
--------------------------------
for x in range(2, 30, 3):
print(x)
Else in For Loop

• The else keyword in a for loop specifies a block of code to be


executed when the loop is finished:
for x in range(6):
print(x)
else:
print("Finally finished!")
While loop
•i=1
while i < 6:
print(i)
i += 1
else:
print("i is no longer less than 6")
Nested Loops

• A nested loop is a loop inside a loop.


• The "inner loop" will be executed one time for each iteration of the
"outer loop":
adj = ["red", "big", "tasty"]
fruits = ["apple", "banana", "cherry"]

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():

You decide on the


function name. Notice
“snake casing”
Select this paragraph to edit
def name_of_function():

Snake casing is all


lowercase with underscores
between words
Select this paragraph to edit
def name_of_function():

Parenthesis at the end.


Later on we can pass in
arguments/parameters into
the 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.
’’’

Optional: Multi-line string to


describe function.
Select this paragraph to edit
def name_of_function():
’’’
Docstring explains function.
’’’
Note: Everything
inside the function
is indented
Select this paragraph to edit
def name_of_function():
’’’
Docstring explains function.
’’’
print(“Hello”)
Code then goes
inside the function.
Select this paragraph to edit
def name_of_function():
’’’
Docstring explains function.
’’’
print(“Hello”)
Function can then
be executed/called
>> name_of_function() to see the result.

>> 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)

>> name_of_function(“Jose”) Functions can


accept arguments
>> Hello Jose to be passed by the
user.
Select this paragraph to edit
def name_of_function(name):
’’’
Docstring explains function.
’’’
print(“Hello ”+name)

>> name_of_function(“Jose”) Functions can


accept arguments
>> Hello Jose to be passed by the
user.
Return and print
● Typically we use the return keyword to send back the result of the
function, instead of just printing it out.
● return allows us to assign the output of the function to a new
variable.
Select this paragraph to edit
def add_function(num1,num2):
return num1+num2

>> result = add_function(1,2) Return allows to


save the result to a
>> variable.

>> 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 my_function(child3, child2, child1):


print("The youngest child is " + child3)

my_function(child1 = "Emil", child2 = "Tobias", child3 = "Linus")


The pass Statement
● function definitions cannot be empty, but if you for some reason have a
function definition with no content, put in the pass statement to avoid
getting an error.
def myfunction():
pass
The global statement
x = 50

def func():
x=2
print('This function is now using the global x!')
print('Because of global x is: ', x)

print('Before calling func(), x is: ', x)


func()
print('Value of x (outside of func()) is: ', x)
Select this paragraph to edit
x = 50

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)

print('Before calling func(), x is: ', x)


func()
print('Value of x (outside of func()) is: ', x)
Try Except
Select this paragraph to edit
Exersise
● Q1. Write a function to checks if the number is divisible by the second number or not.
● Q2. Write a program to take the marks of the students and find the percentage. All the scores should
have the value zero by default.
● Write a function takes a two-word string and returns True if both words begin with same letter
animal_crackers('Levelheaded Llama') --> True
animal_crackers('Crazy Kangaroo') --> False
● write a code to find second largest number in a list
● write a code to find factorial of a number
● write a code to check whether a number is Prime or not
● LESSER OF TWO EVENS: Write a function that returns the lesser of two given numbers if both numbers
are even, but returns the greater if one or both numbers are odd

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

• The finally block, if specified, will be executed regardless if the try


block raises an error or not.
try:
print(x)
except:
print("Something went wrong")
finally:
print("The 'try except' is finished")

You might also like