Basic Control Structures in Python

  • Loops allow us to repeatedly execute parts of a program (most of the time with a variable parameter)
  • Conditional program execution allow us to execute parts of a program depending on some condition

The while-loop

The basic sytax of the while-loop in Python is:

while condition:
    # execute commands until condition
    # evaluates to False

In [ ]:
# print the squares of the numbers 1 to 10
i = 1

while i <= 10:
    print(i**2)
    i = i + 1
    
print("The loop has finished")

Notes:

  • condition must be a boolean expression! The loop is executed while the condition evaluates to True.
  • Note the colon at the end of the condition!
  • Python has no special characters indicating the start and the end of the while-loop execution block. The block is merely indicated by identation! This is the case for all Python control structures! Blocks are always indicated by code-identation. All lines belonging to a block must be idented by the same amount of spaces. The usual ident is four spaces (never use tabs).

Exercises

  • What is the output of the print statements in the following code fragements? Answer the question before executing the codes!

    a = 1
    i = 1
    while i < 5:
        i = i + 1
        a = a + 1
    print(i, a)

    and

    a = 1
    i = 1
    while i < 5:
        i = i + 1
    a = a + 1
    print(i, a)

In [ ]:
# your solution here
  • The square root $y=\sqrt{x}$ of a positive number $x$ can be estimated iteratively with $y_0>0$ (an arbitrary positive number) and $y_{n+1}=\frac 12\left(y_n+\frac{x}{y_n}\right)$.

    Write a python program to estimate the square root with that recipe!

    Hint: Construct a while-loop with the condition $|y_{n+1}-y_n|>\epsilon$ with $\epsilon=10^{-6}$ and update $y_n$ and $y_{n+1}$ within the loop. Consider the final $y_{n+1}$ as estimate for $\sqrt{x}$.


In [ ]:
# your solution here

The if-statement

The basic syntax of the ìf-statement is:

if condition:
    # execute commands if condition is True
else:
    # execute commands if condition is False

The else-part of the construct is optional!

The same notes as for the while-loop apply!


In [ ]:
x = 6

if x < 10:
    print("x is smaller than 10!")
    
if x % 2 == 0:
    print("x is even!")
else:
    print("x is odd!")

Exercises:

  • $x$ and $y$ are integer numbers. Write a python program which determines whether $x<y$, $x>y$ or $x=y$ and prints out the result!

    Hint: Nested if-statements


In [ ]:
# your solution here
  • Write a program to test whether a given positive integer $x$ is a prime number!

    Hints:

    • You need a combination of a while-loop and an if-statement.
    • A very simple test for the prime-property is: A positive integer is prime if $x\bmod n \neq 0$ for all $2\leq n \leq \sqrt{x}$.

In [ ]:
# your solution here