Conditionals, Loops

Import statement

Typical import:

import something

or

from somemodule import somefunction

or

from somemodule import somefunction, anotherfunction

or

from somemodule import *

or

from somemodule import somefunction as different_name

Boolean values

False:

False    None    0    ""    ()    []    {}

True:

True    1   "Some string"   (1, 2)  [1, 2]  {1: 'One'}

if-elif-else

Most common decision construction is if-elif-else.

if condition1:
    body1
elif condition2:
    body2
elif condifion3:
    body3
.
.
.
elif condition(n-1)
    body(n-1)
else:
    body(n)

Examples:

num = int(input('Enter a number: '))
if num > 0:
    print('The number is positive')
elif num < 0:
    print('The number is negative')
else:
    print('The number is zero')

Example with pass:

if x < 5:
    pass
elif x > 5:
    pass
else:
    x = 5

Nested block example:

name = input('What is your name? ')
if name.endswith('Gumby'):
    if name.startswith('Mr.'):
        print('Hello, Mr. Gumby')
    elif name.startswith('Mrs.'):
        print('Hello, Mrs. Gumby')
    else:
        print('Hello, Gumby')
else:
    print('Hello, stranger')

Comparison Operators

Expression Description
x == y x equals y
x < y x is less than y
x > y x is greater than y
x >= y x is greater than or equal to y
x <= y x is less than or equal to y
x != y x is not equal to y
x is y x and y are the same object
x is not y x and y are different objects
x in y x is a member of the container (e.g., sequence) y
x not in y x is not a member of the container (e.g., sequence ) y

is: The identity operator

>>> x = y = [1, 2, 3]
>>> z = [1, 2, 3]
>>> x == y
True
>>> x == z
True
>>> x is y
True
>>> x is z
False

Loops

while loops

while condition:
    body
else: # optional
    code continuation

Example:

x = 1
while x <= 100:
    print(x)
    x += 1

for loops

for variable in sequence:
    body
else: # optional
    code continuation

Example:

numbers = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
for number in numbers:
    print(number)

range() function

Function range can be used in combination with len and for loop like this:

>>> x = [1, 2, 3, -7, 5, 10, -5, 4]
>>> for i in range(len(x)):
...  if x[i] < 0:
...    print("Negative number on index ", i)
...
Negative number on index  3
Negative number on index  6
>>> range(10)
range(0, 10)

The following program writes out the numbers from 1 to 100:

for number in range(1,101):
    print(number)

Iterating over dictionaries:

d = {'x': 1, 'y': 2, 'z': 3}
for key, value in d.items():
    print(key, 'corresponds to', value)

Breaking out of loop

break

To end (break out of) a loop, you use break.

>>> x = 1
>>>
>>> while True:
...   x += 1
...   if x == 10:
...     break
...   else:
...     print("Value is ", x)
...
Value is  2
Value is  3
Value is  4
Value is  5
Value is  6
Value is  7
Value is  8
Value is  9

continue

It causes the current iteration to end and to “jump” to the beginning of the next.

>>> x = 1
>>>
>>> while True:
...   x += 1
...   if x < 10:
...     continue
...   else:
...     print("x has the value ", x)
...     break
...
x has the value  10
{
  "data": {
    "sessionMaterial": {
      "id": "session-material:2019/tieto-ostrava-jaro:conditionals-loops:0",
      "title": "Conditionals, Loops",
      "html": "\n          \n    \n\n    <h2>Conditionals, Loops</h2>\n<h3>Import statement</h3>\n<p>Typical import:</p>\n<div class=\"highlight\"><pre><code>import something</code></pre></div><p>or</p>\n<div class=\"highlight\"><pre><code>from somemodule import somefunction</code></pre></div><p>or</p>\n<div class=\"highlight\"><pre><code>from somemodule import somefunction, anotherfunction</code></pre></div><p>or</p>\n<div class=\"highlight\"><pre><code>from somemodule import *</code></pre></div><p>or</p>\n<div class=\"highlight\"><pre><code>from somemodule import somefunction as different_name</code></pre></div><h3>Boolean values</h3>\n<p>False:</p>\n<div class=\"highlight\"><pre><code>False    None    0    &quot;&quot;    ()    []    {}</code></pre></div><p>True:</p>\n<div class=\"highlight\"><pre><code>True    1   &quot;Some string&quot;   (1, 2)  [1, 2]  {1: &apos;One&apos;}</code></pre></div><h3>if-elif-else</h3>\n<p>Most common decision construction is <em>if-elif-else</em>.</p>\n<div class=\"highlight\"><pre><code>if condition1:\n    body1\nelif condition2:\n    body2\nelif condifion3:\n    body3\n.\n.\n.\nelif condition(n-1)\n    body(n-1)\nelse:\n    body(n)</code></pre></div><p>Examples:</p>\n<div class=\"highlight\"><pre><code>num = int(input(&apos;Enter a number: &apos;))\nif num &gt; 0:\n    print(&apos;The number is positive&apos;)\nelif num &lt; 0:\n    print(&apos;The number is negative&apos;)\nelse:\n    print(&apos;The number is zero&apos;)</code></pre></div><p>Example with pass:</p>\n<div class=\"highlight\"><pre><code>if x &lt; 5:\n    pass\nelif x &gt; 5:\n    pass\nelse:\n    x = 5</code></pre></div><p>Nested block example:</p>\n<div class=\"highlight\"><pre><code>name = input(&apos;What is your name? &apos;)\nif name.endswith(&apos;Gumby&apos;):\n    if name.startswith(&apos;Mr.&apos;):\n        print(&apos;Hello, Mr. Gumby&apos;)\n    elif name.startswith(&apos;Mrs.&apos;):\n        print(&apos;Hello, Mrs. Gumby&apos;)\n    else:\n        print(&apos;Hello, Gumby&apos;)\nelse:\n    print(&apos;Hello, stranger&apos;)</code></pre></div><h3>Comparison Operators</h3>\n<table>\n<thead><tr>\n<th>Expression</th>\n<th>Description</th>\n</tr>\n</thead>\n<tbody>\n<tr>\n<td>x == y</td>\n<td>x equals y</td>\n</tr>\n<tr>\n<td>x &lt; y</td>\n<td>x is less than y</td>\n</tr>\n<tr>\n<td>x &gt; y</td>\n<td>x is greater than y</td>\n</tr>\n<tr>\n<td>x &gt;= y</td>\n<td>x is greater than or equal to y</td>\n</tr>\n<tr>\n<td>x &lt;= y</td>\n<td>x is less than or equal to y</td>\n</tr>\n<tr>\n<td>x !=  y</td>\n<td>x is not equal to y</td>\n</tr>\n<tr>\n<td>x is y</td>\n<td>x and y are the same object</td>\n</tr>\n<tr>\n<td>x is not y</td>\n<td>x and y are different objects</td>\n</tr>\n<tr>\n<td>x in y</td>\n<td>x is a member of the container (e.g., sequence) y</td>\n</tr>\n<tr>\n<td>x not in y</td>\n<td>x is not a member of the container (e.g., sequence ) y</td>\n</tr>\n</tbody>\n</table>\n<p><strong>is: The identity operator</strong></p>\n<div class=\"highlight\"><pre><code>&gt;&gt;&gt; x = y = [1, 2, 3]\n&gt;&gt;&gt; z = [1, 2, 3]\n&gt;&gt;&gt; x == y\nTrue\n&gt;&gt;&gt; x == z\nTrue\n&gt;&gt;&gt; x is y\nTrue\n&gt;&gt;&gt; x is z\nFalse</code></pre></div><h3>Loops</h3>\n<h4>while loops</h4>\n<div class=\"highlight\"><pre><code>while condition:\n    body\nelse: # optional\n    code continuation</code></pre></div><p>Example:</p>\n<div class=\"highlight\"><pre><code>x = 1\nwhile x &lt;= 100:\n    print(x)\n    x += 1</code></pre></div><h4>for loops</h4>\n<div class=\"highlight\"><pre><code>for variable in sequence:\n    body\nelse: # optional\n    code continuation</code></pre></div><p>Example:</p>\n<div class=\"highlight\"><pre><code>numbers = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]\nfor number in numbers:\n    print(number)</code></pre></div><h4>range() function</h4>\n<p>Function range can be used in combination with len and for loop like this:</p>\n<div class=\"highlight\"><pre><code>&gt;&gt;&gt; x = [1, 2, 3, -7, 5, 10, -5, 4]\n&gt;&gt;&gt; for i in range(len(x)):\n...  if x[i] &lt; 0:\n...    print(&quot;Negative number on index &quot;, i)\n...\nNegative number on index  3\nNegative number on index  6</code></pre></div><div class=\"highlight\"><pre><code>&gt;&gt;&gt; range(10)\nrange(0, 10)</code></pre></div><p>The following program writes out the numbers from 1 to 100:</p>\n<div class=\"highlight\"><pre><code>for number in range(1,101):\n    print(number)</code></pre></div><p>Iterating over dictionaries:</p>\n<div class=\"highlight\"><pre><code>d = {&apos;x&apos;: 1, &apos;y&apos;: 2, &apos;z&apos;: 3}\nfor key, value in d.items():\n    print(key, &apos;corresponds to&apos;, value)</code></pre></div><h4>Breaking out of loop</h4>\n<p><strong>break</strong></p>\n<p>To end (break out of) a loop, you use break.</p>\n<div class=\"highlight\"><pre><code>&gt;&gt;&gt; x = 1\n&gt;&gt;&gt;\n&gt;&gt;&gt; while True:\n...   x += 1\n...   if x == 10:\n...     break\n...   else:\n...     print(&quot;Value is &quot;, x)\n...\nValue is  2\nValue is  3\nValue is  4\nValue is  5\nValue is  6\nValue is  7\nValue is  8\nValue is  9</code></pre></div><p><strong>continue</strong></p>\n<p>It causes the current iteration to end and to &#x201C;jump&#x201D; to the beginning of the next.</p>\n<div class=\"highlight\"><pre><code>&gt;&gt;&gt; x = 1\n&gt;&gt;&gt;\n&gt;&gt;&gt; while True:\n...   x += 1\n...   if x &lt; 10:\n...     continue\n...   else:\n...     print(&quot;x has the value &quot;, x)\n...     break\n...\nx has the value  10</code></pre></div>\n\n\n        "
    }
  }
}