0% found this document useful (0 votes)
13 views9 pages

Py 2

The document provides an overview of Python loops, including while and for loops, along with their control statements such as break and continue. It also covers functions, lambda expressions, variable scope, and modules/packages in Python. Additionally, it includes exercises for practicing control statements and functions.

Uploaded by

Mariya Jacob
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)
13 views9 pages

Py 2

The document provides an overview of Python loops, including while and for loops, along with their control statements such as break and continue. It also covers functions, lambda expressions, variable scope, and modules/packages in Python. Additionally, it includes exercises for practicing control statements and functions.

Uploaded by

Mariya Jacob
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
You are on page 1/ 9

Python Loops

Python has two primitive loop commands:

 while loops
 for loops

while Loop
With the while loop we can execute a set of statements as long as a condition is true.
i=1
while i < 6:
print(i)
i += 1
1
2
3
4
5
i=10
while(i>1):
print(i)
i=i-1
10
9
8
7
6
5
4
3
2
l = ["apple", "banana", "cherry"]
i=0
while i < len(l):
print(l[i])
i=i+1
apple
banana
cherry

Break Statement

With the break statement we can stop the loop even if the while condition is true:
i=1
while i < 6:
print(i)
if i == 3:
break
i += 1
1
2
3

Continue Statement

With the continue statement we can stop the current iteration, and continue with the next
i=0
while i < 6:
i += 1
if i == 3:
continue
print(i)
1
2
4
5
6

For Loops
A for loop is used for iterating over a sequence
fruits = ["apple", "banana", "cherry"]
for x in fruits:
print(x)
apple
banana
cherry
for x in "banana": #looping string
print(x)
b
a
n
a
n
a

break Statement
fruits = ["apple", "banana", "cherry"]
for x in fruits:
print(x)
if x == "banana":
break
apple
banana
continue Statement
fruits = ["apple", "banana", "cherry"]
for x in fruits:
if x == "banana":
continue
print(x)
apple
cherry

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(6):
print(x)
0
1
2
3
4
5
for x in range(2, 6): #(starting value, ending value, increment value)
print(x)
2
3
4
5
for x in range(2, 30, 5): #(starting value, ending value, )
print(x)
2
7
12
17
22
27

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 i in range(10):
print(i)
else:
print("loop executed")
0
1
2
3
4
5
6
7
8
9
loop executed

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)
red apple
red banana
red cherry
big apple
big banana
big cherry
tasty apple
tasty banana
tasty cherry
for i in range(5):
for j in range(i):
print(j)
0
0
1
0
1
2
0
1
2
3

pass Statement

for loops cannot be empty, but if you for some reason have a for loop with no content, put in the
pass statement to avoid getting an error.
for i in range(5):
pass

Functions
A function is a block of code which only runs when it is called.

You can pass data, known as parameters, into a function.

A function can return data as a result.


#function definition

def myfunction():
return "hello world"

#function call

myfunction()
Out[23]:
'hello world'

passing arguments to function


def name(n):
print("My name is:",n)
name("python")
My name is: python
def func(car,model):
print("The car is:",car,", Model of car is:",model)
func("BMW","x5")
The car is: BMW , Model of car is: x5

passing multiple arguments


def func(*person):
#person[0] #to access values
for i in person:
print(i)
func("a","b","c")
a
b
c
def my_function(*kids):
print("The youngest child is " + kids[2])

my_function("Emil", "Tobias", "Linus")


The youngest child is Linus

Default Parameter Value

If we call the function without argument, it uses the default value:


def func(temp=37):
print("the body temperature is:",temp)

func()
the body temperature is: 37
def my_function(country = "Norway"):
print("I am from " + country)

my_function("Sweden")
my_function("India")
my_function()
my_function("Brazil")
I am from Sweden
I am from India
I am from Norway
I am from Brazil
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 func():
pass

Lambda
A lambda function is a small anonymous function.

A lambda function can take any number of arguments, but can only have one expression.
#Syntax

lambda arguments : expression


x = lambda a : a + 10
print(x(5))
15
x = lambda a, b : a * b
print(x(5, 6))
30
x = lambda a, b, c : a + b + c
print(x(5, 6, 2))
13

Scope of variable
A variable is only available from inside the region it is created. This is called scope.

Local Scope

A variable created inside a function belongs to the local scope of that function, and can only be
used inside that function.
def myfunc():
z = 300
print(z)

myfunc()
300
print(z) #local scop
---------------------------------------------------------------------------
NameError Traceback (most recent call last)
<ipython-input-42-c01ac3f50fdc> in <module>()
----> 1 print(z)

NameError: name 'z' is not defined

Global Scope

A variable created in the main body of the Python code is a global variable and belongs to the
global scope. The global keyword makes the variable global.
x = 300 #global scope

def myfunc():
print(x)

myfunc()

print(x)
300
300
def myfunc():
global x
x = 300

myfunc()

print(x)
300

Modules and Packages


A module is a file containing a set of functions.

Package is a collection of modules


import mod

mod.add(2,3)
Out[46]:
5
from pac import mod

mod.add(1,2)
Out[47]:
3
from pac.mod import add

add(1,4)
Out[48]:
5
#built-in Module
import platform
x = platform.system()
print(x)

Windows

pip
The pip command looks for the package in PyPI, resolves its dependencies, and installs
everything in your current Python environment to ensure that requests will work. The pip install
package_name command always looks for the latest version of the package and installs it.
pip install camelcase

The following command must be run outside of the IPython shell:

$ pip install camelcase

The Python package manager (pip) can only be used from outside of IPython.
Please reissue the `pip` command in a separate terminal or command prompt.

See the Python documentation for more information on how to install package
s:

https://docs.python.org/3/installing/
import camelcase

c = camelcase.CamelCase()

txt = "hello world"

print(c.hump(txt))

Hello World

EXERCISE

CONTROL_STATEMENTS

1. Write a python program to check if a given number is positive or negative


2. Write a python program to check if a given number is odd or even
3. Find greatest among two numbers
4. Find greatest among three numbers
5. Write a Python program to calculate the sum of three given numbers, if the values are
equal then return three times of their sum.
6. Write a Python program to sum of two given integers. However, if the sum is between 15
to 20 it will return 20.
7. Write a Python program that will return true if the two given integer values are equal or
their sum or difference is 5.
Functions

1. Write a Python function to find the Max of three numbers.


2. Write a Python function to sum all the numbers in a list. Sample List : (8, 2, 3, 0, 7)
Expected Output : 20
3. Write a Python function to multiply all the numbers in a list. Sample List : (8, 2, 3, -1, 7)
Expected Output : -336
4. Write a Python function that takes a list and returns a new list with unique elements of the
first list. Sample List : [1,2,3,3,3,3,4,5] Unique List : [1, 2, 3, 4, 5]
5. Write a Python program to print the even numbers from a given list. Sample List : [1, 2, 3,
4, 5, 6, 7, 8, 9] Expected Result : [2, 4, 6, 8]
6. Write a Python function that checks whether a passed string is palindrome or not.

lambda

1. Write a Python program to filter a list of integers using Lambda. Original list of integers:
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10] Even numbers from the said list: [2, 4, 6, 8, 10] Odd numbers
from the said list: [1, 3, 5, 7, 9]
2. Write a Python program to square and cube every number in a given list of integers using
Lambda. Original list of integers: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] Square every number of the
said list: [1, 4, 9, 16, 25, 36, 49, 64, 81, 100] Cube every number of the said list: [1, 8, 27,
64, 125, 216, 343, 512, 729, 1000]
3. Write a Python program to rearrange positive and negative numbers in a given array
using Lambda. Original arrays: [-1, 2, -3, 5, 7, 8, 9, -10] Rearrange positive and negative
numbers of the said array: [2, 5, 7, 8, 9, -10, -3, -1]
4. Write a Python program to count the even, odd numbers in a given array of integers
using Lambda. Original arrays: [1, 2, 3, 5, 7, 8, 9, 10] Number of even numbers in the
above array: 3 Number of odd numbers in the above array: 5
5. Write a Python program to add two given lists using map and lambda. Original list: [1, 2,
3] [4, 5, 6] Result: after adding two list [5, 7, 9]
6. Write a Python program to find numbers divisible by nineteen or thirteen from a list of
numbers using Lambda. Orginal list: [19, 65, 57, 39, 152, 639, 121, 44, 90, 190] Numbers
of the above list divisible by nineteen or thirteen: [19, 65, 57, 39, 152, 190]

You might also like