Introduction to Python Prog. - Lecture 2

1mohamedgamal54 86 views 42 slides Sep 09, 2024
Slide 1
Slide 1 of 42
Slide 1
1
Slide 2
2
Slide 3
3
Slide 4
4
Slide 5
5
Slide 6
6
Slide 7
7
Slide 8
8
Slide 9
9
Slide 10
10
Slide 11
11
Slide 12
12
Slide 13
13
Slide 14
14
Slide 15
15
Slide 16
16
Slide 17
17
Slide 18
18
Slide 19
19
Slide 20
20
Slide 21
21
Slide 22
22
Slide 23
23
Slide 24
24
Slide 25
25
Slide 26
26
Slide 27
27
Slide 28
28
Slide 29
29
Slide 30
30
Slide 31
31
Slide 32
32
Slide 33
33
Slide 34
34
Slide 35
35
Slide 36
36
Slide 37
37
Slide 38
38
Slide 39
39
Slide 40
40
Slide 41
41
Slide 42
42

About This Presentation

Introduction to Python Programming Language for absolute beginners level.


Slide Content

Introduction to Python
Programming
By Mohamed Gamal
© Mohamed Gamal 2024

The topics of today’s lecture:
Agenda

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 theprintstatement 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:
# codetobeexecuted
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
fori inrange(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]

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
Thank You!