# Python Tutorial

## Control structures and loops:

### Control structures

If…elif…else is a decision making expression. We use decision making statements when we want to execute a part of our program only if a certain condition is fulfilled. The if statement syntax is shown below.

```if condition: statements elif condition: statements . . . else: statements```

Here, the program evaluates the first `condition_A` and if it is fulfilled will execute the statements. If not, it evaluates the next `condition_B`. If no conditions are fulfilled the program continues at the the `else` block and executes the statements.

Note: In `if...elif...else` as a decision making expression, `elif` and `else` are not compulsory. It means, you can use `if` without other expressions or with just one `else` or several `elif` and just one `else`.

Example: Run the code below and check the result to understand content of decision making sentence.

``````# This code check the number. If the number is positive it prints a message

num = 5
if num > 0:
print("The number is positive.")
``````
``````The number is positive.
``````
``````# This code check the code. If the number is positive ot not, it prints a message.

num = -2

if num > 0:
print("The number is positive.")
else:
print("The number is not positive.")
``````
``````The number is not positive.
``````
``````# The user input a number. If the number is positive or negetive or zero, the code print a message

# take a number from user

# make decision that the number is positive, negative ot zero
if num > 0:
elif num < 0:
else:
print("Your number is equal to zero.")
``````
``````Please input your number:1
``````

Exercise: Create code to take a number from user and check the number is even or odd, then print a message depending on the result.

``````# Your code goes here

# take a integer number from user
num =

# make decision that the number is Even or Odd

``````

### Nested if statements

In programming we usually need nested blocks. Nesting means that we use a block inside another block. As an example we can have a `if...elif...else` statement inside another `if...elif...else` statement.

Example: The code in the next cell is equivalent to the previous example, but implemented in another way.

``````num = float(input("Please input your number:"))

if num >= 0:
if num == 0:
print("Your number is equal to zero.")
else:
else:
``````
``````Please input your number:1
``````

### For loop

In Python, the for loop is used to iterate over a sequence (string, list, tuple,…) or other iterable objects. You can see the `syntax` of for loop below.

```for variable in sequence: body sentences```

Here, the variable iteratively takes all values of the sequence and executes the block for each value. The loop continues until the variable has taken the value of the last item in the sequence. The body sentences are seperated by indentation from other part of the code.

Examples: Let’s run the following examples to see the for loop in action.

``````# Program to find the sum value of numbers from 0 to 9
numbers = [0,1,2,3,4,5,6,7,8,9]

# variable to store sum value
sum = 0

# iterate over the numbers
for i in numbers:
sum = sum + i

# Output: sum value
print("The sum value is:", sum)
``````
``````The sum value is: 45
``````
``````# Program to print list of words

# List of words
word_list = ["Gottfried", "Wilhelm", "Leibniz"]

# iterate over the list
for w in word_list:
print(w)
``````
``````Gottfried
Wilhelm
Leibniz
``````

Exercise: We have a list of numbers below. Try to create a code to print only positive numbers by using `for loop` and inside it an `if` making decision statement.

``````# The code must print only positive numbers

# The list of numbers
num_list = [5,0,-8,-4,56,1265,-0.33,77,-99,0.08]

``````

### The range() function

In python, we can use `range()` function to generate a sequence of numbers. The `range(10)` function generate numbers from `0` to `9`(10 numbers).

If you want to define the start, stop and step size, you can use `range()` function in this form: `range(start,stop,step size)`

Note: We can use the `range()` function in `for` loop to iterate through a sequence of numbers.

Note: `Step size` defaults to 1, if you do not define step size.

Example: Let’s use the `range()` function to compute the sum value of numbers from `0` to `9`:

``````# Program to find the sum value of numbers from 0 to 9

# variable to store sum value
sum = 0

# iterate over the numbers
for i in range(10):
sum = sum + i

# Output: sum value
print("The sum value is:", sum)
``````
``````The sum value is: 45
``````

The `range()` function does not pre-compute all the values. If you want to force the function to output all values, you can use the conversion to `list()`.

Example: These codes show the function of `range()`. Lets to run and check them.

``````print(range(10))
``````
``````range(0, 10)
``````
``````print(list(range(10)))
``````
``````[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
``````
``````print(list(range(0,10,2)))
``````
``````[0, 2, 4, 6, 8]
``````

Exercise: We have two list of fruits name and colours. Try to print any fruit with it’s colour by using `for loop` and `range()` function. The result must be in this form:

```Apple is red Banana is yellow Pear is green```

``````# The code must output fruit name with it's colour
fruits = ["Apple", "Banana", "Pear"]
colours = ["red", "yellow", "green"]

``````

### for loop with else

Like the `if` statement, a `for` loop can have an `else` part. The `else` part is executed, if the item in the sequence in `for` loop exits.

Example: Let’s see how the `else` part is working.

``````# Program to print list of words

word_list = ["Gottfried", "Wilhelm", "Leibniz"]

for w in word_list:
print(w)
else:
print("No items left.")
``````
``````Gottfried
Wilhelm
Leibniz
No items left.
``````

Exercise: Modify the code below. The code must find the biggest number in a list of numbers.

``````# Program to find the biggest number in a list of numbers

# Input list of numbers by user
# split numbers by using space between input numbers
List_num = [int(x) for x in input().split()]

# find the biggest number and store it in:

biggest_num =

# check part
import numpy as np
assert biggest_num == np.max(List_num,0), "The number that you find is not the biggest number in the List_num"
``````

### While loop

In Python, the while loop is used to iteratively execute code as long as a condition is true. You can see the `syntax` of while loop below.

```while condition: body statements(code block)```

Here, the `condition` is checked first, if the `condition` is true the `body statements` will execute. Again the `condition` will be checked. If it is still true the `body statements` will execute again. This iteration continues as long as the condition is true. When the condition is not true, the program comes out of the loop and does not run the body statement any more.

Note: In Python, the body statements in while loop are determined by indentation.

Example: Let’s compute the sum value of numbers from `0` to `9` using a `while` loop.

``````# Program to find the sum value of numbers from 0 to 9

# variable to store sum value
Sum = 0

# variable to count numbers from 0 to 9
counter = 0

# iterate over the numbers
while counter < 10:
Sum = Sum + counter
counter = counter + 1 # update counter

# Output: sum value
print("The Sum value is:", Sum)
``````
``````The Sum value is: 45
``````

Note: In Python programming, any `non-zero` value is defined as `True` and any `None` and `0` are defined as `False`. You can see how it works in next example.

Example: In this example, the condition of the `while loop` is true till the value of the variable `x` is not `zero`. After changing the value of `x` to `zero` the condition would not be true, then the program comes out of the `while loop`. You can change the input value of `x` to `zero` manually and check the result.

``````x = 1

while x:
y = 2 * x
print('y: ', y)
x -= 1
``````
``````y:  2
``````

### While loop with else

Like `for` loop, a `while` loop can have an else part. The `else` part is executed, if the item in the `condition` in `while` loop exits.

When the condition in `while` loop is not `True`, the `else` part statements will execute.

Example: Lets see the `while` loop example with `else`.

``````# Program to find the sum value of numbers from 0 to 9

# variable to store sum value
Sum = 0

# variable to count numbers from 0 to 9
counter = 0

# iterate over the numbers
while counter < 10:
Sum = Sum + counter
counter = counter + 1 # update counter
else:
print("The counter increased bigger or equal to 10")

# Output: sum value
print("The Sum value for the counter less than 10 is:", Sum)
``````
``````The counter increased bigger or equal to 10
The Sum value for the counter less than 10 is: 45
``````

Exercise: Modify the code below. The code must print the `Fibonacci` series.

Note: A Fibonacci series is the integer sequence of `0,1,1,2,3,5,8,13,...` where element `n` is the sum of the previous two elements.

``````# Program to display the Fibonacci series up to the number that is lees than input number

# take input number from the user
input_num =

# you need to define first 2 terms
n1 = 0
n2 = 1

``````

### break and continue

In Python, the `break` and `continue` statements can change the flow in a loop. The `break` statement breaks out of the code block (body statements) in loops. And the `continue` statement continues with the next iteration of the loop. You can see the syntax and working of `break` and `continue` statements. If the `condition` is `True`, the program execute the `break` statement and goes out of the iteration and execute the codes block outside the loop. If the `condition` is `True`, the program execute the `continue` statement and goes back to the sequence of loop, then execute the codes block from the beginning again.

Example: Lets to run the programs below to see how `break` and `continue` statements work.

``````# use of break statement inside a loop

for i in "ICAML":
if i == "M":
break
print(i)
print("Finished")
``````
``````I
C
A
Finished
``````
``````# use of continue statement inside a loop

for i in "Hannover":
if i == "n":
continue
print(i)
print("Finished")
``````
``````H
a
o
v
e
r
Finished
``````

Exercise: Modify the program below. The program must find `even` numbers from a list of numbers and less than `10`. Your result should be like this: ``````# program to find even numbers less than 10 from a list
# list of numbers
List_num = [1,4,3,8,10,28,9,44,77]

# create a loop to iterate numbers from List

``````

### Pass statement

In Python, `pass` statement explicitly means to do nothing. We can say the `pass` statement is like a comment. The difference between them is, the interpreter ignores a comment during execution but it does not ignore `pass` in execution. It is usually used, when we define a statement that starts a block without implementing the block itself. We must use the `pass` keyword here, to fulfill the indentation rules.

Note: Nothing happens, when a `pass` statement is executed.

Example: You can see the application of `pass` statement below. You can run the code below and see that nothing will happen.

``````# pass statement application
# used in a loop to hold the place

numbers = [5,658,0.67,-45,45.98]
for num in numbers:
pass

``````

Looping Techniques: The most common mistake that happens in python programming `looping` is `The infinite loop`. In python looping, we have three techniques to avoid of this mistake.

• Loop with condition at the top: We have to limit iteration by defining condition at the top of loop. For instance:

```num = 10 sum = 0 i = 1 while i < num: sum = sum + i i = i+1```

• Loop with condition in the middle: In this kind, we can have a loop with unlimited iteration. But we can define limitation by using `conditional break` in between of the body code block of the loop. For instance:

```i = 0 sum = 0 while i >= 0: sum = sum + i i = i + 1 if i > 100: break print("Sum numbers from 0 to 100 is:", sum)```

• Loop with condition at the bottom: In this kind, we can have a loop with unlimited iteration. But we can define limitation by using `conditional break` at the bottom of the loop. For instance:

```while True: num = input("input a number") remian = num % 2 print("The remain of dividing your number by 2 is:") if remain == 0: break```