SlideShare a Scribd company logo
Introduction to Python
Programming
By Mohamed Gamal
© Mohamed Gamal 2024
The topics of today’s lecture:
Agenda
Introduction to Python Prog. - Lecture 2
Loops
print("Hello World")
print("Hello World")
print("Hello World")
print("Hello World")
print("Hello World")
print("Hello World")
print("Hello World")
print("Hello World")
print("Hello World")
print("Hello World")
What if someone asks you to print 'Hello World'
10 times?
- One way is to write the print statement 10 times.
But that is definitely not a good idea if you have
to write it 5000 times!
We have two types of loops in Python:
1. for
2. while
1) For Loop
for counter_var in sequence:
# code to be executed
for count in range(10):
print(count)
Syntax:
Example:
range(start, stop, step)
Example 1
number = int(input("Enter a number: "))
for i in range(1, 11, 1):
print(f"{number} * {i} = {number * i}")
Multiplication table using for loop:
Example 2
n = int(input("Enter a number: "))
for i in range(2, n):
if n % i == 0:
print("It's not prime; divisible by", i)
exit()
print(f"{n} is a prime number!")
Checking if a number is prime or not.
Example 3
number = int(input("Enter a positive integer: "))
sum = 0
for i in range(1, number + 1):
sum += i
print(f"Sum = {sum}")
Example 4
n = 5
for i in range(1, n + 1):
j = n - i
print(f"i = {i}, j = {j}")
Output:
str = "Mohamed"
for ch in str:
print(ch, end=" ")
Output:
Example 5
names = [ "Mohamed", "Ahmed", "Omar", "Mona", "Aya" ]
for name in names:
print(name)
names = [ "Mohamed", "Ahmed", "Omar", "Mona", "Aya" ]
for (i, name) in enumerate(names):
print(f"Person {i}: {name}")
Nested For Loops
rows = 5
for i in range(1, rows + 1):
for j in range(i):
print('*', end='')
print()
Print a triangle of stars Output:
n = 5
for i in range(n + 1):
print ("Iteration no. {}".format(i))
else:
print ("for loop is over, now in else block")
Python For-Else Loop
• Python supports an optional else block to be associated with a for loop. If an else block is
used with a for loop, it is executed only when the for loop terminates normally.
n = int(input("Enter a number: "))
for i in range(2, n):
if n % i == 0:
print("It's not prime; divisible by", i)
break
else:
print(f"{n} is a prime number!")
Example
x = 0
while x != 50:
print("Hello")
x += 1
2
2) While Loop
while (expression):
statements
Syntax: Example:
1
3
4
Example 1
ch = 'y'
while ch != 'n':
dividend = int(input("Enter dividend: "))
divisor = int(input("Enter divisor: "))
print(f"Result is {dividend / divisor}, quotient is {dividend //
divisor}, remainder is {dividend % divisor}")
ch = input("Do another operation (y/n)? ")
Program to divide two numbers and display the result, quotient and remainder.
Example 2
import random
secret_number = random.randint(1, 20)
guess = None
while guess != secret_number:
guess = int(input("Guess the secret number between 1 and 20: "))
if guess < secret_number:
print("Too low! Try again.")
elif guess > secret_number:
print("Too high! Try again.")
else:
print("Congratulations! You've guessed the number!")
A simple guessing game where the user has to guess a secret number.
Example 3
a, b = 0, 1
limit = 100
print(f"Fibonacci sequence up to {limit}: ")
while a < limit:
print(a, end=" ")
a, b = b, a + b
A while loop to generate and print Fibonacci numbers up to a certain limit.
Fibonacci Forumla: 𝐹(𝑛) = 𝐹(𝑛 − 1) + 𝐹(𝑛 − 2)
Infinite loop
i = 0
while True:
print(f"i = {i}")
i += 1
i = 0
i = 1
i = 2
i = 3
i = 4
⋮
Output:
Which type of loop to use?
– The for loop is appropriate when you know in advance how many times the
loop will be executed.
– The while loop is used when you don’t know in advance when the loop will
terminate and when you may not want to execute the loop body even once.
Break Statement
– The break is a keyword in Python which is used to bring the program
control out of the loop.
– The break statement breaks the loop one by one (i.e., in the case of nested
loops) it breaks the inner loop first and then proceeds to outer loops.
break
Break Statement – Example
for i in range(10):
print(i, end=" ")
if (i == 5):
break
print(f"nCame outside of loop (i = {i}).")
Output:
Continue Statement
● The continue statement in Python language is used to bring the
program control to the beginning of the loop.
● The continue statement skips some lines of code inside the loop and
continues with the next iteration.
● It is mainly used for a condition so that we can skip some code for a
particular condition.
# loop statements
continue
# some lines of the code which is to be skipped
Example
for i in range(10):
print(i)
if i == 5:
continue
Other Examples:
>>> string = "Hello, 123 World"
>>> uppercase_letters = [char.upper() for char in string if char.isalpha()]
>>> print(uppercase_letters)
>>> list1 = [ 1, 2, 3 ]
>>> list2 = [ 4, 5, 6 ]
>>> combList = [(x,y) for x in list1 for y in list2]
>>> [(1, 4), (1, 5), (1, 6), (2, 4), (2, 5), (2, 6), (3, 4), (3, 5), (3, 6)]
>>> list1 = [x for x in range(1,21) if x%2==0]
>>> [2, 4, 6, 8, 10, 12, 14, 16, 18, 20]
Introduction to Python Prog. - Lecture 2
Functions in Python
– A function is a “black box” that we've locked part of our program into.
– The idea behind a function is that it groups part of the program and in
particular, that the code within the function is reusable.
– A function has:
• a name that you call it by.
• a list of zero or more arguments or parameters that you
hand to it for it to act on or to direct its work.
• a body containing the actual instructions (statements).
• a return value, of a particular type.
def multbytwo(x):
return x * 2
name
keyword
argument(s)/parameter(s)
return value
Functions in Python (Cont.)
– How do we call a function? We've been doing so informally since day one, but
now we have a chance to call one that we've written.
# ---- function multbytwo ---- #
def multbytwo(x):
return x * 2
result = multbytwo(3) # call the function
print(f"{result}")
Functions in Python (Cont.)
– What makes a good function? The most important aspect of a good “building
block” is that have a single, well-defined task to perform.
– Other reasons:
• When you find that a program is hard to manage
• It appeared in the main program several times (be abstract).
• The main program was getting too big, so it could be made (presumably)
smaller and more manageable.
When you call a function, you only have to know what it does, not how it does it.
Functions in Python (Cont.)
– We should say a little more about the mechanism by which an argument is passed down
from a caller into a function.
– Formally, Python is call by value, which means that a function receives copies of the values of
its arguments.
def swap(a, b):
a, b = b, a
x = 5
y = 10
print(f"Before: x = {x}, y = {y}")
swap(x, y)
print(f"After: x = {x}, y = {y}")
Functions in Python (Cont.)
– However, there is an exception to this rule. When the argument you pass to a function is not a
single variable, but is rather an array (sequence), the function does not receive a copy of the
array, and it therefore can modify the array in the caller. (reason is that it is too expensive to
copy the array!)
def addTwo(arr):
for i in range(len(arr)):
arr[i] += 2
list = [1, 2, 3, 4, 5]
print(f"Before: {list}")
addTwo(list)
print(f"After: {list}")
None Return Functions
– None functions are created and used just like value-returning functions except they do not
return a value after the function executes.
– Instead of a data type, these functions use the keyword "None" implicitly.
def printHello(times):
for _ in range(times):
print("Hello")
return None # optional
printHello(10) # call the function
Variables Visibility and Lifetime
– A variable declared within the block of a function is visible only within that function.
– Variables declared within functions are called local variables.
– On the other hand, a variable declared outside of any function is a global variable,
and it is potentially visible anywhere within the program.
– How long do variables last?
• By default, local variables (those declared within a function) have automatic
duration: they spring into existence when the function is called, and they (and
their values) disappear when the function returns.
Local Variables
def myFunc():
localVar = 5
print(f"localVar = {localVar}")
myFunc() # function call
Global Variables
globalVar = 10 # Global variable
def myFunc():
print(f"globalVar = {globalVar}")
globalVar = 25
myFunc() # function call
Memory Layout
– Text section
• Program instructions
– Program counter
• Next instruction
– Stack
• Local variables
• Return addresses
• Method parameters
– Data section
• Global variables
Positional Arguments
def info(name, age):
print(f"Hello {name}, your age is {age}.")
info("Mohamed", 32)
info(age=19, name="Ahmed")
Default Arguments
def info(name="Empty", age=0):
print(f"Hello {name}, your age is {age}.")
info()
Variable length arguments
def printinfo(arg1, *vartuple):
print(arg1)
for var in vartuple:
print(var)
printinfo(1, "Python", 24, 5, ['A', 'B', 'C'], 100)
Variable length keyword arguments
def addr(**kwargs):
for k,v in kwargs.items():
print (f"{k}: {v}")
addr(Name="Ahmed", Country="USA")
addr(Name="Mohamed", Country="Egypt", phone="123456789", ID="400001")
Docstrings
def add(a, b):
"""Return the sum of two numbers."""
return a + b
result = add(5, 3)
print("Sum:", result)
Docstrings (Cont.)
def multiply(a, b):
"""
Multiply two numbers and return the result.
Parameters:
a (int or float): The first number.
b (int or float): The second number.
Returns:
int or float: The result of multiplying a and b.
"""
return a * b
result = multiply(5, 3)
print("Product:", result)
Functions annotations
def myfunction(a: "physics", b: "Maths" = 20) -> int:
c = a + b
return c
print(myfunction.__annotations__)
• The function annotation feature of Python enables you to add additional explanatory metadata about the
arguments declared in a function definition, and also the return data type. They are not considered by Python
interpreter while executing the function. They are mainly for the Python IDEs for providing a detailed
documentation to the programmer.
def myfunction2(*args: "arbitrary args", **kwargs: "arbitrary keyword args") -> int:
pass
print(myfunction2.__annotations__)
End of lecture 2
ThankYou!

More Related Content

Similar to Introduction to Python Prog. - Lecture 2 (20)

PDF
Q-Step_WS_02102019_Practical_introduction_to_Python.pdf
Michpice
 
PPTX
made it easy: python quick reference for beginners
SumanMadan4
 
PPTX
Programming with python
sarogarage
 
PDF
python.pdf
BurugollaRavi1
 
PPTX
UNIT – 3.pptx for first year engineering
SabarigiriVason
 
PDF
pythonQuick.pdf
PhanMinhLinhAnxM0190
 
PDF
python 34💭.pdf
AkashdeepBhattacharj1
 
PDF
python notes.pdf
RohitSindhu10
 
PDF
Python: An introduction A summer workshop
ForrayFerenc
 
PPTX
python BY ME-2021python anylssis(1).pptx
rekhaaarohan
 
PPT
Python-review1.ppt
jaba kumar
 
PPTX
Python_Unit-1_PPT_Data Types.pptx
SahajShrimal1
 
PDF
Introduction to Python Programming | InsideAIML
VijaySharma802
 
PDF
Python Cheatsheet_A Quick Reference Guide for Data Science.pdf
zayanchutiya
 
PPTX
python-presentationpython-presentationpython-presentation.pptx
rkameshwaran50
 
PDF
PythonStudyMaterialSTudyMaterial.pdf
data2businessinsight
 
PPTX
GE8151 Problem Solving and Python Programming
Muthu Vinayagam
 
PDF
2 Python Basics II meeting 2 tunghai university pdf
Anggi Andriyadi
 
PPTX
PYTHON PPT.pptx python is very useful for day to day life
NaitikSingh33
 
PPT
Python
Vishal Sancheti
 
Q-Step_WS_02102019_Practical_introduction_to_Python.pdf
Michpice
 
made it easy: python quick reference for beginners
SumanMadan4
 
Programming with python
sarogarage
 
python.pdf
BurugollaRavi1
 
UNIT – 3.pptx for first year engineering
SabarigiriVason
 
pythonQuick.pdf
PhanMinhLinhAnxM0190
 
python 34💭.pdf
AkashdeepBhattacharj1
 
python notes.pdf
RohitSindhu10
 
Python: An introduction A summer workshop
ForrayFerenc
 
python BY ME-2021python anylssis(1).pptx
rekhaaarohan
 
Python-review1.ppt
jaba kumar
 
Python_Unit-1_PPT_Data Types.pptx
SahajShrimal1
 
Introduction to Python Programming | InsideAIML
VijaySharma802
 
Python Cheatsheet_A Quick Reference Guide for Data Science.pdf
zayanchutiya
 
python-presentationpython-presentationpython-presentation.pptx
rkameshwaran50
 
PythonStudyMaterialSTudyMaterial.pdf
data2businessinsight
 
GE8151 Problem Solving and Python Programming
Muthu Vinayagam
 
2 Python Basics II meeting 2 tunghai university pdf
Anggi Andriyadi
 
PYTHON PPT.pptx python is very useful for day to day life
NaitikSingh33
 

More from Faculty of Computers and Informatics, Suez Canal University, Ismailia, Egypt (20)

PDF
How to install CS50 Library (Step-by-step guide)
Faculty of Computers and Informatics, Suez Canal University, Ismailia, Egypt
 
PDF
Understanding Singular Value Decomposition (SVD)
Faculty of Computers and Informatics, Suez Canal University, Ismailia, Egypt
 
PDF
Understanding K-Nearest Neighbor (KNN) Algorithm
Faculty of Computers and Informatics, Suez Canal University, Ismailia, Egypt
 
PDF
Understanding Convolutional Neural Networks (CNN)
Faculty of Computers and Informatics, Suez Canal University, Ismailia, Egypt
 
PDF
Luhn's algorithm to validate Egyptian ID numbers
Faculty of Computers and Informatics, Suez Canal University, Ismailia, Egypt
 
PDF
Complier Design - Operations on Languages, RE, Finite Automata
Faculty of Computers and Informatics, Suez Canal University, Ismailia, Egypt
 
PDF
Object Oriented Programming (OOP) using C++ - Lecture 5
Faculty of Computers and Informatics, Suez Canal University, Ismailia, Egypt
 
PDF
Object Oriented Programming (OOP) using C++ - Lecture 2
Faculty of Computers and Informatics, Suez Canal University, Ismailia, Egypt
 
PDF
Object Oriented Programming (OOP) using C++ - Lecture 1
Faculty of Computers and Informatics, Suez Canal University, Ismailia, Egypt
 
PDF
Object Oriented Programming (OOP) using C++ - Lecture 3
Faculty of Computers and Informatics, Suez Canal University, Ismailia, Egypt
 
PDF
Object Oriented Programming (OOP) using C++ - Lecture 4
Faculty of Computers and Informatics, Suez Canal University, Ismailia, Egypt
 
Understanding Convolutional Neural Networks (CNN)
Faculty of Computers and Informatics, Suez Canal University, Ismailia, Egypt
 
Complier Design - Operations on Languages, RE, Finite Automata
Faculty of Computers and Informatics, Suez Canal University, Ismailia, Egypt
 
Object Oriented Programming (OOP) using C++ - Lecture 5
Faculty of Computers and Informatics, Suez Canal University, Ismailia, Egypt
 
Object Oriented Programming (OOP) using C++ - Lecture 2
Faculty of Computers and Informatics, Suez Canal University, Ismailia, Egypt
 
Object Oriented Programming (OOP) using C++ - Lecture 1
Faculty of Computers and Informatics, Suez Canal University, Ismailia, Egypt
 
Object Oriented Programming (OOP) using C++ - Lecture 3
Faculty of Computers and Informatics, Suez Canal University, Ismailia, Egypt
 
Object Oriented Programming (OOP) using C++ - Lecture 4
Faculty of Computers and Informatics, Suez Canal University, Ismailia, Egypt
 
Ad

Recently uploaded (20)

PDF
Basic_Concepts_in_Clinical_Biochemistry_2018كيمياء_عملي.pdf
AdelLoin
 
PPTX
UNIT 1 - INTRODUCTION TO AI and AI tools and basic concept
gokuld13012005
 
PDF
aAn_Introduction_to_Arcadia_20150115.pdf
henriqueltorres1
 
PPTX
Final Major project a b c d e f g h i j k l m
bharathpsnab
 
PPTX
Numerical-Solutions-of-Ordinary-Differential-Equations.pptx
SAMUKTHAARM
 
PDF
Submit Your Papers-International Journal on Cybernetics & Informatics ( IJCI)
IJCI JOURNAL
 
PPTX
darshai cross section and river section analysis
muk7971
 
PDF
Water Industry Process Automation & Control Monthly July 2025
Water Industry Process Automation & Control
 
PPTX
DATA BASE MANAGEMENT AND RELATIONAL DATA
gomathisankariv2
 
PPTX
MODULE 05 - CLOUD COMPUTING AND SECURITY.pptx
Alvas Institute of Engineering and technology, Moodabidri
 
PDF
Viol_Alessandro_Presentazione_prelaurea.pdf
dsecqyvhbowrzxshhf
 
PDF
NTPC PATRATU Summer internship report.pdf
hemant03701
 
PPTX
Water Resources Engineering (CVE 728)--Slide 4.pptx
mohammedado3
 
PPTX
OCS353 DATA SCIENCE FUNDAMENTALS- Unit 1 Introduction to Data Science
A R SIVANESH M.E., (Ph.D)
 
PPTX
仿制LethbridgeOffer加拿大莱斯桥大学毕业证范本,Lethbridge成绩单
Taqyea
 
PDF
methodology-driven-mbse-murphy-july-hsv-huntsville6680038572db67488e78ff00003...
henriqueltorres1
 
PPTX
Worm gear strength and wear calculation as per standard VB Bhandari Databook.
shahveer210504
 
PPTX
Alan Turing - life and importance for all of us now
Pedro Concejero
 
PDF
mbse_An_Introduction_to_Arcadia_20150115.pdf
henriqueltorres1
 
PPTX
原版一样(EC Lille毕业证书)法国里尔中央理工学院毕业证补办
Taqyea
 
Basic_Concepts_in_Clinical_Biochemistry_2018كيمياء_عملي.pdf
AdelLoin
 
UNIT 1 - INTRODUCTION TO AI and AI tools and basic concept
gokuld13012005
 
aAn_Introduction_to_Arcadia_20150115.pdf
henriqueltorres1
 
Final Major project a b c d e f g h i j k l m
bharathpsnab
 
Numerical-Solutions-of-Ordinary-Differential-Equations.pptx
SAMUKTHAARM
 
Submit Your Papers-International Journal on Cybernetics & Informatics ( IJCI)
IJCI JOURNAL
 
darshai cross section and river section analysis
muk7971
 
Water Industry Process Automation & Control Monthly July 2025
Water Industry Process Automation & Control
 
DATA BASE MANAGEMENT AND RELATIONAL DATA
gomathisankariv2
 
MODULE 05 - CLOUD COMPUTING AND SECURITY.pptx
Alvas Institute of Engineering and technology, Moodabidri
 
Viol_Alessandro_Presentazione_prelaurea.pdf
dsecqyvhbowrzxshhf
 
NTPC PATRATU Summer internship report.pdf
hemant03701
 
Water Resources Engineering (CVE 728)--Slide 4.pptx
mohammedado3
 
OCS353 DATA SCIENCE FUNDAMENTALS- Unit 1 Introduction to Data Science
A R SIVANESH M.E., (Ph.D)
 
仿制LethbridgeOffer加拿大莱斯桥大学毕业证范本,Lethbridge成绩单
Taqyea
 
methodology-driven-mbse-murphy-july-hsv-huntsville6680038572db67488e78ff00003...
henriqueltorres1
 
Worm gear strength and wear calculation as per standard VB Bhandari Databook.
shahveer210504
 
Alan Turing - life and importance for all of us now
Pedro Concejero
 
mbse_An_Introduction_to_Arcadia_20150115.pdf
henriqueltorres1
 
原版一样(EC Lille毕业证书)法国里尔中央理工学院毕业证补办
Taqyea
 
Ad

Introduction to Python Prog. - Lecture 2

  • 1. Introduction to Python Programming By Mohamed Gamal © Mohamed Gamal 2024
  • 2. The topics of today’s lecture: Agenda
  • 4. Loops print("Hello World") print("Hello World") print("Hello World") print("Hello World") print("Hello World") print("Hello World") print("Hello World") print("Hello World") print("Hello World") print("Hello World") What if someone asks you to print 'Hello World' 10 times? - One way is to write the print statement 10 times. But that is definitely not a good idea if you have to write it 5000 times! We have two types of loops in Python: 1. for 2. while
  • 5. 1) For Loop for counter_var in sequence: # code to be executed for count in range(10): print(count) Syntax: Example: range(start, stop, step)
  • 6. Example 1 number = int(input("Enter a number: ")) for i in range(1, 11, 1): print(f"{number} * {i} = {number * i}") Multiplication table using for loop:
  • 7. Example 2 n = int(input("Enter a number: ")) for i in range(2, n): if n % i == 0: print("It's not prime; divisible by", i) exit() print(f"{n} is a prime number!") Checking if a number is prime or not.
  • 8. Example 3 number = int(input("Enter a positive integer: ")) sum = 0 for i in range(1, number + 1): sum += i print(f"Sum = {sum}")
  • 9. Example 4 n = 5 for i in range(1, n + 1): j = n - i print(f"i = {i}, j = {j}") Output: str = "Mohamed" for ch in str: print(ch, end=" ") Output:
  • 10. Example 5 names = [ "Mohamed", "Ahmed", "Omar", "Mona", "Aya" ] for name in names: print(name) names = [ "Mohamed", "Ahmed", "Omar", "Mona", "Aya" ] for (i, name) in enumerate(names): print(f"Person {i}: {name}")
  • 11. Nested For Loops rows = 5 for i in range(1, rows + 1): for j in range(i): print('*', end='') print() Print a triangle of stars Output:
  • 12. n = 5 for i in range(n + 1): print ("Iteration no. {}".format(i)) else: print ("for loop is over, now in else block") Python For-Else Loop • Python supports an optional else block to be associated with a for loop. If an else block is used with a for loop, it is executed only when the for loop terminates normally.
  • 13. n = int(input("Enter a number: ")) for i in range(2, n): if n % i == 0: print("It's not prime; divisible by", i) break else: print(f"{n} is a prime number!") Example
  • 14. x = 0 while x != 50: print("Hello") x += 1 2 2) While Loop while (expression): statements Syntax: Example: 1 3 4
  • 15. Example 1 ch = 'y' while ch != 'n': dividend = int(input("Enter dividend: ")) divisor = int(input("Enter divisor: ")) print(f"Result is {dividend / divisor}, quotient is {dividend // divisor}, remainder is {dividend % divisor}") ch = input("Do another operation (y/n)? ") Program to divide two numbers and display the result, quotient and remainder.
  • 16. Example 2 import random secret_number = random.randint(1, 20) guess = None while guess != secret_number: guess = int(input("Guess the secret number between 1 and 20: ")) if guess < secret_number: print("Too low! Try again.") elif guess > secret_number: print("Too high! Try again.") else: print("Congratulations! You've guessed the number!") A simple guessing game where the user has to guess a secret number.
  • 17. Example 3 a, b = 0, 1 limit = 100 print(f"Fibonacci sequence up to {limit}: ") while a < limit: print(a, end=" ") a, b = b, a + b A while loop to generate and print Fibonacci numbers up to a certain limit. Fibonacci Forumla: 𝐹(𝑛) = 𝐹(𝑛 − 1) + 𝐹(𝑛 − 2)
  • 18. Infinite loop i = 0 while True: print(f"i = {i}") i += 1 i = 0 i = 1 i = 2 i = 3 i = 4 ⋮ Output:
  • 19. Which type of loop to use? – The for loop is appropriate when you know in advance how many times the loop will be executed. – The while loop is used when you don’t know in advance when the loop will terminate and when you may not want to execute the loop body even once.
  • 20. Break Statement – The break is a keyword in Python which is used to bring the program control out of the loop. – The break statement breaks the loop one by one (i.e., in the case of nested loops) it breaks the inner loop first and then proceeds to outer loops. break
  • 21. Break Statement – Example for i in range(10): print(i, end=" ") if (i == 5): break print(f"nCame outside of loop (i = {i}).") Output:
  • 22. Continue Statement ● The continue statement in Python language is used to bring the program control to the beginning of the loop. ● The continue statement skips some lines of code inside the loop and continues with the next iteration. ● It is mainly used for a condition so that we can skip some code for a particular condition. # loop statements continue # some lines of the code which is to be skipped
  • 23. Example for i in range(10): print(i) if i == 5: continue
  • 24. Other Examples: >>> string = "Hello, 123 World" >>> uppercase_letters = [char.upper() for char in string if char.isalpha()] >>> print(uppercase_letters) >>> list1 = [ 1, 2, 3 ] >>> list2 = [ 4, 5, 6 ] >>> combList = [(x,y) for x in list1 for y in list2] >>> [(1, 4), (1, 5), (1, 6), (2, 4), (2, 5), (2, 6), (3, 4), (3, 5), (3, 6)] >>> list1 = [x for x in range(1,21) if x%2==0] >>> [2, 4, 6, 8, 10, 12, 14, 16, 18, 20]
  • 26. Functions in Python – A function is a “black box” that we've locked part of our program into. – The idea behind a function is that it groups part of the program and in particular, that the code within the function is reusable. – A function has: • a name that you call it by. • a list of zero or more arguments or parameters that you hand to it for it to act on or to direct its work. • a body containing the actual instructions (statements). • a return value, of a particular type. def multbytwo(x): return x * 2 name keyword argument(s)/parameter(s) return value
  • 27. Functions in Python (Cont.) – How do we call a function? We've been doing so informally since day one, but now we have a chance to call one that we've written. # ---- function multbytwo ---- # def multbytwo(x): return x * 2 result = multbytwo(3) # call the function print(f"{result}")
  • 28. Functions in Python (Cont.) – What makes a good function? The most important aspect of a good “building block” is that have a single, well-defined task to perform. – Other reasons: • When you find that a program is hard to manage • It appeared in the main program several times (be abstract). • The main program was getting too big, so it could be made (presumably) smaller and more manageable. When you call a function, you only have to know what it does, not how it does it.
  • 29. Functions in Python (Cont.) – We should say a little more about the mechanism by which an argument is passed down from a caller into a function. – Formally, Python is call by value, which means that a function receives copies of the values of its arguments. def swap(a, b): a, b = b, a x = 5 y = 10 print(f"Before: x = {x}, y = {y}") swap(x, y) print(f"After: x = {x}, y = {y}")
  • 30. Functions in Python (Cont.) – However, there is an exception to this rule. When the argument you pass to a function is not a single variable, but is rather an array (sequence), the function does not receive a copy of the array, and it therefore can modify the array in the caller. (reason is that it is too expensive to copy the array!) def addTwo(arr): for i in range(len(arr)): arr[i] += 2 list = [1, 2, 3, 4, 5] print(f"Before: {list}") addTwo(list) print(f"After: {list}")
  • 31. None Return Functions – None functions are created and used just like value-returning functions except they do not return a value after the function executes. – Instead of a data type, these functions use the keyword "None" implicitly. def printHello(times): for _ in range(times): print("Hello") return None # optional printHello(10) # call the function
  • 32. Variables Visibility and Lifetime – A variable declared within the block of a function is visible only within that function. – Variables declared within functions are called local variables. – On the other hand, a variable declared outside of any function is a global variable, and it is potentially visible anywhere within the program. – How long do variables last? • By default, local variables (those declared within a function) have automatic duration: they spring into existence when the function is called, and they (and their values) disappear when the function returns.
  • 33. Local Variables def myFunc(): localVar = 5 print(f"localVar = {localVar}") myFunc() # function call
  • 34. Global Variables globalVar = 10 # Global variable def myFunc(): print(f"globalVar = {globalVar}") globalVar = 25 myFunc() # function call
  • 35. Memory Layout – Text section • Program instructions – Program counter • Next instruction – Stack • Local variables • Return addresses • Method parameters – Data section • Global variables
  • 36. Positional Arguments def info(name, age): print(f"Hello {name}, your age is {age}.") info("Mohamed", 32) info(age=19, name="Ahmed") Default Arguments def info(name="Empty", age=0): print(f"Hello {name}, your age is {age}.") info()
  • 37. Variable length arguments def printinfo(arg1, *vartuple): print(arg1) for var in vartuple: print(var) printinfo(1, "Python", 24, 5, ['A', 'B', 'C'], 100)
  • 38. Variable length keyword arguments def addr(**kwargs): for k,v in kwargs.items(): print (f"{k}: {v}") addr(Name="Ahmed", Country="USA") addr(Name="Mohamed", Country="Egypt", phone="123456789", ID="400001")
  • 39. Docstrings def add(a, b): """Return the sum of two numbers.""" return a + b result = add(5, 3) print("Sum:", result)
  • 40. Docstrings (Cont.) def multiply(a, b): """ Multiply two numbers and return the result. Parameters: a (int or float): The first number. b (int or float): The second number. Returns: int or float: The result of multiplying a and b. """ return a * b result = multiply(5, 3) print("Product:", result)
  • 41. Functions annotations def myfunction(a: "physics", b: "Maths" = 20) -> int: c = a + b return c print(myfunction.__annotations__) • The function annotation feature of Python enables you to add additional explanatory metadata about the arguments declared in a function definition, and also the return data type. They are not considered by Python interpreter while executing the function. They are mainly for the Python IDEs for providing a detailed documentation to the programmer. def myfunction2(*args: "arbitrary args", **kwargs: "arbitrary keyword args") -> int: pass print(myfunction2.__annotations__)
  • 42. End of lecture 2 ThankYou!