Loops and Functions Session 8

Loops in Python

Sometimes we want to repeat a set of statements in our program. For instance: Print 1 to 1000

Loops make it easy for a programmer to tell the computer, which set of instructions to repeat, and how!

Types of loops in Python

Primarily there are two types of loops in Python

  1. While loop
  2. For loop

We will look into this one by one!

While loop

The syntax of a while loop looks like this:

''' while condition:
    #Body of the loop '''
  • The block keeps executing until the condition is true/false

In while loops, the condition is checked first. If it evaluates to true, the body of the loop is executed, otherwise not!

If the loop is entered, the process of condition check and execution is continued until the condition becomes false.

Quick Quiz: Write a program to print 1 to 50 using a while loop.

An Example:

i = 0
while i<5:
    print(“CodesforYou”)
    i = i+1

(Above program will print CodesForYou 5 times)

Note: if the condition never becomes false, the loop keeps getting executed.

Quick Quiz: Write a program to print the content of a list using while loops.

For loop

A for loop is used to iterate through a sequence like a list, tuple, or string (iterables)

The syntax of a for loop looks like this:

l = [1, 7, 8]
for item in l:
	print(item)

(Above program will print 1, 7, and 8)

Range function in Python

The range function in python is used to generate a sequence of numbers.

We can also specify the start, stop, and step-size as follows:

            range(start, stop, step_size)

  • step size is usually not used with range()

An example demonstrating range() function

for i in range(0, 7):		#range(7) can also be used
	print(i)		#prints 0 to 6
For loop with else

An optional else can be used with a for loop if the code is to be executed when the loop exhausts.

Example:

l = [1, 7, 8]
for item in l:
	print(item)
else:
	print(“Done”)	#This is printed when the loop exhausts!

Output:

1

7

8

Done
The break statement

‘break’ is used to come out of the loop when encountered. It instructs the program to – Exit the loop now.

Example:

for i in range(0, 80):
	print(i)	#This will print 0, 1, 2 and 3
	if i == 3:
		break
The continue statement

‘continue’ is used to stop the current iteration of the loop and continue with the next one. It instructs the program to “skip this iteration.”

Example:

for i in range(4):
	print(“printing”)
	if i == 2:	#if i is 2, the iteration is skipped
		continue
	print(i)

pass statement

pass is a null statement in python. It instructs to “Do nothing.”

Example:

l = [1, 7, 8]
for item in l:
	pass		#without pass, the program will throw an error

Functions and Recursions

A function is a group of statements performing a specific task.

When a program gets bigger in size and its complexity grows, it gets difficult for a programmer to keep track of which piece of code is doing what!

A function can be reused by the programmer in a given program any number of times.

Example and Syntax of a function

The syntax of a function looks as follows:

def func1():
	print(“Hello”)

This function can be called any number of times, anywhere in the program.

Function call

Whenever we want to call a function, we put the name of the function followed by parenthesis as follows:

func1()          #This is called function call

Function definition

The part containing the exact set of instructions that are executed during the function call.

Quick Quiz: Write a program to greet a user with “Good day” using functions.

Types of functions in Python

There are two types of functions in Python:

  1. Built-in functions #Already present in Python
  2. User-defined functions #Defined by the user

Examples of built-in function includes len(), print(), range(), etc.

The func1() function we defined is an example of a user-defined function.

Functions with arguments

A function can accept some values it can work with. We can put these values in the parenthesis. A function can also return values as shown below:

def greet(name):
	gr = “Hello” + name
	return gr
a = greet(“Ayesha”) #“Ayesha” is passed to greet in name

# a will now contain “Hello Ayesha”

Default Parameter Value

We can have a value as the default argument in a function.

If we specify name = “stranger” in the line containing def, this value is used when no argument is passed.

For Example:

def greet(name=’stranger’):
	#function body
greet()                       #Name will be ‘stranger’ in function body(default)

greet(“Iqra”)        #Name will be “Iqra” in function body(passed)
Recursion

Recursion is a function which calls itself.

It is used to directly use a mathematical formula as a function. For example:

factorial(n) = n * factorial(n-1)

This function can be defined as follows:

def factorial(n):
	if i == 0 or i == 1 : #Base condition which doesn’t call the function any further
		return i
	else:
		return n*factorial(n-1) #Function calling itself

This works as follows:




Practice Set (Using Loops)

  1. Write a program to print the multiplication table of a given number using for loop.
  2. Write a program to greet all the person names stored in a list l1 and which starts with H.
l1 = [“aMEEN”, “hUSSAIN”, “HASSAN”, “Ali”]
  1. Attempt problem 1 using a while loop.
  2. Write a program to find whether a given number is prime or not.
  3. Write a program to find the sum of first n natural numbers using a while loop.
  4. Write a program to calculate the factorial of a given number using for loop.
  5. Write a program to print the following star pattern.
    *

  ***  

***** for n=3
  1. Write a program to print the following star pattern:
*

**

*** for n = 3
  1. Write a program to print the following star pattern:
* * *
*   *             #For n=3
* * * 

10. Write a program to print the multiplication table of n using for loop in reversed order.

The programmer needs to be extremely careful while working with recursion to ensure that the function doesn’t infinitely keep calling itself. Recursion is sometimes the most direct way to code an algorithm.


Practice Set (Using Functions)

  1. Write a program using the function to find the greatest of three numbers.
  2. Write a python program using the function to convert Celsius to Fahrenheit.
  3. How do you prevent a python print() function to print a new line at the end?
  4. Write a recursive function to calculate the sum of first n natural numbers.
  5. Write a python function to print the first n lines of the following pattern.
***

**       #For n = 3

*
  1. Write a python function that converts inches to cms.
  2. Write a python function to remove a given word from a list and strip it at the same time.
  3. Write a python function to print the multiplication table of a given number.

Comments

Popular posts from this blog

Python Installation

How to Change your (dev/visual) console color