0% found this document useful (0 votes)
3 views11 pages

Python For Loops and Functions Guide

The document provides an overview of basic Python programming concepts, focusing on iteration using for and while loops, as well as the definition and use of functions. It explains how to traverse lists, utilize the range function, and implement nested loops, along with examples of using break and continue statements. Additionally, it covers defining functions, including recursive and iterative examples, and demonstrates how to encapsulate code for better modularity and reusability.

Uploaded by

rafayahmed820
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
3 views11 pages

Python For Loops and Functions Guide

The document provides an overview of basic Python programming concepts, focusing on iteration using for and while loops, as well as the definition and use of functions. It explains how to traverse lists, utilize the range function, and implement nested loops, along with examples of using break and continue statements. Additionally, it covers defining functions, including recursive and iterative examples, and demonstrates how to encapsulate code for better modularity and reusability.

Uploaded by

rafayahmed820
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

Python Basics 2

February 20, 2024

1 Iterating
A for loop in Python is primarily designed to exhaust a list, that is, to enumerate the elements of
a list. The effect is similar to the repetition effect just described if one uses a list containing the
first n integers. A for loop only needs one element of the list at a time. It is therefore desirable to
use a for loop with objects that are able to create those elements on demand, one at a time. This
is what iterators achieve in Python.

1.1 The for statement


The for statement The primary aim of the for statement is to traverse a list: “‘python for s in [‘a’,
‘b’, ‘c’]: print(s), # a b c
In this example, the loop variable s is successively assigned to one element of the list. Notice that
the loop variable is available after the loop has terminated. This may sometimes be useful; refer,
for instance, the example in section Controlling the flow inside the loop.
One of the most frequent uses of a for loop is to repeat a given task a defined number of times One
of the most frequent uses oftimes, using the function range. “‘python for iteration in range(n): #
repeat the following code n times …

[1]: # To loop through a set of code a specified number of times, we can use the␣
↪range() function,

# The range() function returns a sequence of numbers, starting from 0 by␣


↪default, and increments by 1 (by default),

# and ends at a specified number.

for x in range(10):
print(x)

0
1
2
3
4
5
6
7

1
8
9

[2]: for x in range(2, 6):


print(x)

2
3
4
5

[3]: for x in range(2, 30, 3):


print(x)

2
5
8
11
14
17
20
23
26
29

[4]: # Nested for Loop

adj = ["red", "big", "tasty"]


fruits = ["apple", "banana", "cherry"]

for x in adj:
for y in fruits:
print(x, y)

red apple
red banana
red cherry
big apple
big banana
big cherry
tasty apple
tasty banana
tasty cherry

[5]: # With the while loop we can execute a set of statements as long as a condition␣
↪is true.

i = 1
while i < 6:

2
print(i)
i += 1

1
2
3
4
5

[6]: # With the break statement we can stop the loop even if the while condition is␣
↪true:

# Exit the loop when i is 3:

i = 1
while i < 6:
print(i)
if i == 3:
break
i += 1

1
2
3

[7]: # With the continue statement we can stop the current iteration, and continue␣
↪with the next:

#Continue to the next iteration if i is 4:

i = 0
while i < 6:
i += 1
if i == 4:
continue
print(i)

1
2
3
5
6

1.2 Functions in Python


In Python, a function is a reusable block of code that performs a specific task. Functions are used
to encapsulate and organize code, making it easier to manage and understand. They help improve
code modularity and reusability.

3
1.2.1 Defining a Function
You can define a function in Python using the def keyword, followed by the function name, a pair
of parentheses, and a colon. Here’s a simple example:
“‘python def greet(name): ””“This function greets the person passed as a parameter.”””
print(f“Hello, {name}!”)

[8]: #In Python a function is defined using the def keyword:


def my_function():
print("Salam from a function")

[9]: my_function()

Salam from a function

[10]: # Function to calculate factorial using recursion

def factorial_recursive(n):
if n == 0:
return 1
else:
return n * factorial_recursive(n - 1)

[11]: factorial_recursive(5) ## Calculates 5!

[11]: 120

[12]: # Calculating Factorial iteratively


def factorial_iterative(n):
result = 1
for i in range(1, n + 1):
result *= i
return result

[13]: factorial_iterative(5)

[13]: 120

[14]: # Sundaram Sieve


#This program calculates an entry in the Sundaram table for the given value of n

def sundaram_table_entry(n):
# Step 1: Generate a list of positive integers from 1 to n
integers = list(range(1, n + 1))

# Step 2: Eliminate numbers of the form i + j + 2ij


for i in range(1, n + 1):
for j in range(i, (n - i) // (2 * i) + 1):

4
eliminate = i + j + 2 * i * j
if eliminate in integers:
[Link](eliminate)

# Step 3: Double the remaining numbers and add 1 to get the prime numbers
primes = [(2 * x + 1) for x in integers]

return primes

# Example usage:
n = 2000 # You can change the value of n as needed
entry = sundaram_table_entry(n)
print(entry)

[3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71, 73,
79, 83, 89, 97, 101, 103, 107, 109, 113, 127, 131, 137, 139, 149, 151, 157, 163,
167, 173, 179, 181, 191, 193, 197, 199, 211, 223, 227, 229, 233, 239, 241, 251,
257, 263, 269, 271, 277, 281, 283, 293, 307, 311, 313, 317, 331, 337, 347, 349,
353, 359, 367, 373, 379, 383, 389, 397, 401, 409, 419, 421, 431, 433, 439, 443,
449, 457, 461, 463, 467, 479, 487, 491, 499, 503, 509, 521, 523, 541, 547, 557,
563, 569, 571, 577, 587, 593, 599, 601, 607, 613, 617, 619, 631, 641, 643, 647,
653, 659, 661, 673, 677, 683, 691, 701, 709, 719, 727, 733, 739, 743, 751, 757,
761, 769, 773, 787, 797, 809, 811, 821, 823, 827, 829, 839, 853, 857, 859, 863,
877, 881, 883, 887, 907, 911, 919, 929, 937, 941, 947, 953, 967, 971, 977, 983,
991, 997, 1009, 1013, 1019, 1021, 1031, 1033, 1039, 1049, 1051, 1061, 1063,
1069, 1087, 1091, 1093, 1097, 1103, 1109, 1117, 1123, 1129, 1151, 1153, 1163,
1171, 1181, 1187, 1193, 1201, 1213, 1217, 1223, 1229, 1231, 1237, 1249, 1259,
1277, 1279, 1283, 1289, 1291, 1297, 1301, 1303, 1307, 1319, 1321, 1327, 1361,
1367, 1373, 1381, 1399, 1409, 1423, 1427, 1429, 1433, 1439, 1447, 1451, 1453,
1459, 1471, 1481, 1483, 1487, 1489, 1493, 1499, 1511, 1523, 1531, 1543, 1549,
1553, 1559, 1567, 1571, 1579, 1583, 1597, 1601, 1607, 1609, 1613, 1619, 1621,
1627, 1637, 1657, 1663, 1667, 1669, 1693, 1697, 1699, 1709, 1721, 1723, 1733,
1741, 1747, 1753, 1759, 1777, 1783, 1787, 1789, 1801, 1811, 1823, 1831, 1847,
1861, 1867, 1871, 1873, 1877, 1879, 1889, 1901, 1907, 1913, 1931, 1933, 1949,
1951, 1973, 1979, 1987, 1993, 1997, 1999, 2003, 2011, 2017, 2027, 2029, 2039,
2053, 2063, 2069, 2081, 2083, 2087, 2089, 2099, 2111, 2113, 2129, 2131, 2137,
2141, 2143, 2153, 2161, 2179, 2203, 2207, 2213, 2221, 2237, 2239, 2243, 2251,
2267, 2269, 2273, 2281, 2287, 2293, 2297, 2309, 2311, 2333, 2339, 2341, 2347,
2351, 2357, 2371, 2377, 2381, 2383, 2389, 2393, 2399, 2411, 2417, 2423, 2437,
2441, 2447, 2459, 2467, 2473, 2477, 2503, 2521, 2531, 2539, 2543, 2549, 2551,
2557, 2579, 2591, 2593, 2609, 2617, 2621, 2633, 2647, 2657, 2659, 2663, 2671,
2677, 2683, 2687, 2689, 2693, 2699, 2707, 2711, 2713, 2719, 2729, 2731, 2741,
2749, 2753, 2767, 2777, 2789, 2791, 2797, 2801, 2803, 2819, 2833, 2837, 2843,
2851, 2857, 2861, 2879, 2887, 2897, 2903, 2909, 2917, 2927, 2939, 2953, 2957,
2963, 2969, 2971, 2999, 3001, 3011, 3019, 3023, 3037, 3041, 3049, 3061, 3067,
3079, 3083, 3089, 3109, 3119, 3121, 3137, 3163, 3167, 3169, 3181, 3187, 3191,
3203, 3209, 3217, 3221, 3229, 3251, 3253, 3257, 3259, 3271, 3299, 3301, 3307,
3313, 3319, 3323, 3329, 3331, 3343, 3347, 3359, 3361, 3371, 3373, 3389, 3391,

5
3407, 3413, 3433, 3449, 3457, 3461, 3463, 3467, 3469, 3491, 3499, 3511, 3517,
3527, 3529, 3533, 3539, 3541, 3547, 3557, 3559, 3571, 3581, 3583, 3593, 3607,
3613, 3617, 3623, 3631, 3637, 3643, 3659, 3671, 3673, 3677, 3691, 3697, 3701,
3709, 3719, 3727, 3733, 3739, 3761, 3767, 3769, 3779, 3793, 3797, 3803, 3821,
3823, 3833, 3847, 3851, 3853, 3863, 3877, 3881, 3889, 3907, 3911, 3917, 3919,
3923, 3929, 3931, 3943, 3947, 3967, 3989, 4001]

[15]: import numpy as np # here the variable np is defined


def sqrt(x):
return [Link](x) # we use np inside the function

[16]: sqrt(2)*sqrt(2)

[16]: 2.0000000000000004

“‘python a = 3 def multiply(x): return a * x # bad style: access to the variable a defined outside
The following function takes a complex number 𝑧 and returns its polar coordinate representation
as magnitude 𝑟 and angle according to Euler’s formula:

𝑧 = 𝑟𝑖𝜙

And the Python counterpart would be this:

[17]: def complex_to_polar(z):


r = [Link]([Link] ** 2 + [Link] ** 2)
phi = np.arctan2([Link], [Link]) # importing arctan2 and sqrt from numpy

return (r,phi) # here the return object is formed

[18]: complex_to_polar(1+2j)

[18]: (2.23606797749979, 1.1071487177940904)

[19]: z = 3 + 5j
a = complex_to_polar(z)
r = a[0]
phi = a[1]

[20]: r

[20]: 5.830951894845301

[21]: phi

[21]: 1.0303768265243125

For example, the following program defines a function to return both roots of the quadratic equation
𝑎𝑥2 + 𝑏𝑥 + 𝑐 = 0(assuming it has two real roots)

6
[22]: import math
def roots(a, b, c):
d = b**2 - 4*a*c
r1 = (-b + [Link](d)) / 2 / a
r2 = (-b - [Link](d)) / 2 / a
return r1, r2

[23]: print(roots(1.,-1.,-6.))

(3.0, -2.0)
Excercise 1
Modify the above function so that it only works when d is real
Chebyshev polynomials are defined by a three-term recursion:
𝑇𝑛 (𝑥) = 2𝑥𝑇𝑛−1 (𝑥) − 𝑇𝑛−2 (𝑥)
Such a recursion needs to be initialized, that is, 𝑇0 (𝑥) = 1, 𝑇1 (𝑥) = 𝑥.
In Python, this three term recursion can be realized by the following function definition:

[24]: def chebyshev(n, x):


if n == 0:
return 1
elif n == 1:
return x
else:
return 2. * x * chebyshev(n - 1, x)- chebyshev(n - 2 ,x)

The function is then called like this:

[25]: chebyshev(5, 0.52)

[25]: 0.39616645119999994

This example also illustrates the risk of dramatically wasting computation time. The number of
function evaluations increases exponentially with the recursion level and most of these evaluations
are just duplicates of previous computations. While it might be tempting to use recursive programs
for demonstrating the strong relation between code and mathematical definition, a production code
will avoid this programming technique.

1.3 Function documentation


A function docstring is a string literal that occurs as the first statement of the function definition.
It should be written as a triple-quoted string on a single line if the function is simple, or on multiple
lines with an initial one-line summary for more detailed descriptions of complex functions

[26]: def heun(f,x0,y0,h,n):


""" Heun method for the solution of first order differential equations
f = function dy/dx
x0 = Initial value of x
y0 = Initial value of y

7
xn = Final value of x
h = Step size
"""
import numpy as np
for i in range(n+1):
k1 = f(x0,y0)
k2 = f(x0+h,y0+k1*h)
slope = (k1 + k2)/2
yn = y0 + slope*h
print('x = %.6f\t y = %.6f\t slope = %.6f'% (x0,y0,slope))
print('--------------------------------------------------------------')
y0 = yn
x0 = x0 + h

The docstring becomes the special _ _ doc _ _ attribute of the function.

[27]: heun.__doc__

[27]: ' Heun method for the solution of first order differential equations\n f =
function dy/dx\n x0 = Initial value of x\n y0 = Initial value of y\n xn
= Final value of x\n h = Step size\n '

1.4 Anonymous functions – the lambda keyword


The syntax is as follows: lambda parameter_list: expression

[28]: parabola = lambda x: x ** 2 + 5

[29]: parabola(3)

[29]: 14

The definition of the lambda function can only consist of a single expression and
in particular, cannot contain loops. lambda functions are, just like other functions,
objects and can be assigned to variables
The main reason to use a construction is for very simple functions, when a full function definition
would be too cumbersome.
Example:
𝑑𝑦
Integrate the differential equation = 4𝑒0.8𝑥 − 0.5𝑦 where 𝑦(0) = 2 and a step size of h=0.5.
𝑑𝑥
Solve from 𝑥 = 0 to 𝑥 = 8.

[30]: import numpy as np


dydx = lambda x,y: 4*[Link](0.8*x) - 0.5*y

[31]: heun(f = dydx,x0 = 0, y0 = 2, h = 0.5,n = 5)

x = 0.000000 y = 2.000000 slope = 3.608649


--------------------------------------------------------------

8
x = 0.500000 y = 3.804325 slope = 5.024427
--------------------------------------------------------------
x = 1.000000 y = 6.316538 slope = 7.215060
--------------------------------------------------------------
x = 1.500000 y = 9.924068 slope = 10.544460
--------------------------------------------------------------
x = 2.000000 y = 15.196298 slope = 15.559280
--------------------------------------------------------------
x = 2.500000 y = 22.975938 slope = 23.077964
--------------------------------------------------------------
Example:
Bisection method is used for finding an estimate of the root of non-linear equations. The Python
program for the bisection method is given below

[32]: def bisection(f,xl,xu,n = 10):


"""This is Python implementation of Bisection method based on the algorithm
given in Numerical Methods for Engineers (7th Edition) by Chapra and Canale␣
↪Calling the function:

bisection(f,xl,xu,n)
f = function
xl = Lower guess
xu = Upper guess
n = No. of iterations. Default is fixed at 10 iterations
"""
## Step 1 starts here
if (f(xl)*f(xu) > 0):
return print("Wrong guesses of xl and xu were input.")
## Step 2 starts here
i = 1
xr = 0
while i <= n:
xrold = xr
xr = round(0.5*(xl+xu),6)
if xr != 0:
ea = round((abs(xr - xrold)/abs(xr))*100,2)
print("After Iteration",i, "\n","xr =",xr, "ea =",ea,"\n")
## Step 3 starts here
if (f(xr)*f(xl) < 0):
xu = xr
elif (f(xr)*f(xl) >0):
xl = xr
else:
print("xr is the root = ",xr)
break
i += 1
return f(xr)

9
[33]: f = lambda x: 5*x**3 - 5*x**2 + 6*x - 2

[34]: bisection(f,0,1,10)

After Iteration 1
xr = 0.5 ea = 100.0

After Iteration 2
xr = 0.25 ea = 100.0

After Iteration 3
xr = 0.375 ea = 33.33

After Iteration 4
xr = 0.4375 ea = 14.29

After Iteration 5
xr = 0.40625 ea = 7.69

After Iteration 6
xr = 0.421875 ea = 3.7

After Iteration 7
xr = 0.414062 ea = 1.89

After Iteration 8
xr = 0.417968 ea = 0.93

After Iteration 9
xr = 0.419922 ea = 0.47

After Iteration 10
xr = 0.418945 ea = 0.23

[34]: 0.003750911061293216

Example:
The greatest common divisor of two integers can be computed with Euclid’s algorithm described
by the following recursion:
𝑔𝑐𝑑(𝑎, 𝑏) = 𝑎 𝑖𝑓 𝑏 = 0
𝑎𝑛𝑑 𝑔𝑐𝑑(𝑎, 𝑏) = 𝑔𝑐𝑑(𝑏, 𝑎𝑚𝑜𝑑𝑏) otherwise.
where:
• 𝑎 and 𝑏 are the two numbers for which you want to find the GCD.
• 𝑔𝑐𝑑(𝑎, 𝑏) represents the GCD of 𝑎 and 𝑏.
• 𝑚𝑜𝑑 represents the modulus operation, which gives the remainder when 𝑎 is divided by 𝑏.

10
[35]: def gcd(a, b):
if b == 0:
return a
else:
return gcd(b, a % b)

[36]: gcd(5,12)

[36]: 1

Exercise 2 :
Rewrite the program in a non-recursive way to compute Chebyshev polynomials.

1.5 The global and nonlocal Keywords


If you want to change variables that are defined outside the local scope, you must first declare
within the function body that this is your intention with the keywords global (for variables in
global scope) and nonlocal (for variables in enclosing scope, for example, where one function is
defined within another).

[37]: def func():


global x
x += 1

[38]: x=4
func()
x

[38]: 5

11

You might also like