03 PythonBasics Loops Function PDF

Download as pdf or txt
Download as pdf or txt
You are on page 1of 1

1.

Loops
In programming, looping means repeating the same set of computations in the same sequence for a number of times.

Think about a real-life situation. You are a field biologist who’s taking measurements of trees in the forest. You pick a tree, measure its diameter and height, write them down in your
notebook and make an estimate of its total volume. Next, you pick another tree, measure its diameter and height, write them down in your notebook and make an estimate of its total
volume. Then, you pick yet another tree, measure its diameter and height, write them down in your notebook and make an estimate of its total volume. You keep repeating the same
process until all trees in the sample are exhausted. In programming lingo, you are looping over each tree and doing the same set of tasks in the same sequence.

1. for loops iterate a finite number of times for each element in the iterable object

looping over Lists


looping over Dictionaries
looping over Strings
2. while loops keep going until a certain condition is met

For Loops
This loop is used for iterating over some kind of a sequence. That can be a list, tuple, dictionary, string, etc.

Looping over _Lists_

In [1]: integer_list = [101, 102, 103, 104, 105]

In [3]: for i in integer_list:


print(i)

101
102
103
104
105

In [5]: new_list = []

list1 = [2, 3, 4]
list2 = [4, 5, 6]

for i in list1:
for j in list2:
new_list.append(i*j)

In [6]: print(new_list)

[8, 10, 12, 12, 15, 18, 16, 20, 24]

Looping over _Dictionaries_

Dictionaries in Python are a collection of key-value pairs — meaning, every item in the dictionary has a key and an associated value. You can loop over these dictionary
elements and do a variety of operations.

In [7]: football_players_dict = {
"Son": "Tottenham",
"Kang-in": "Mallorca",
"Messi": "Barcelona",
"Mbappé": "Paris Saint-Germain",
"Kane": "Tottenham"
}

dict.keys() : All the keys in the dictionary

In [10]: for player in football_players_dict.keys():


print(player)

Son
Kang-in
Messi
Mbappé
Kane

dict.values() : All the values in the dictionary

In [11]: for team in football_players_dict.values():


print(team)

Tottenham
Mallorca
Barcelona
Paris Saint-Germain
Tottenham

Looping over _Strings_

In [12]: for t in 'Python':


print(t)

P
y
t
h
o
n

In [14]: sent = "I love Text Mining"

# splitting the sentence into words


sent_split = sent.split()
# extract each word with a loop
for t in sent_split:
print(t)

I
love
Text
Mining

While Loops
Like for loops, while loops repeatedly execute a block of code — as long as a condition is true. The loop only breaks out once the looping condition is false.

In [15]: i = 0
while i <=5:
print(i)
i = i+1 # option to break out of the loop

0
1
2
3
4
5

In [16]: name = ''

while name != "Ben":


name = input("What is your name?")
print("Hey," + name + "," + " Where is Ben?")

What is your name?Will


Hey,Will, Where is Ben?
What is your name?Sam
Hey,Sam, Where is Ben?
What is your name?Ben
Hey,Ben, Where is Ben?

2. Functions
Define a function without parameters
define a function with def
comes the name of the function
e.g.,
print_hello_world()
no parameters passed to a function

In [2]: def print_hello_world():


print("Hello world")

In [5]: print_hello_world()

Hello world

Define a function with parameters


Parameters, or arguments, are values that you can pass to a function that will determine how a function will get executed.
Positional Parameters: The most common type of passing parameters is by calling a function and passing the parameters in the same position as in the definition of
the function.

In [9]: def func1(parameter):


print("Hello,", parameter)

In [10]: func1("Text Mining")

Hello, Text Mining

The position is of importance when passing positional parameters. Note that we need to pass the two required parameters here. Otherwise, we will get a TypeError
indicating that we have passed an incorrect number of parameters

In [11]: def integer_division(num1, num2):


return num1/num2

In [12]: integer_division(10, 2)

5.0
Out[12]:

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy