Lesson 3.
Statements
M. Maikey Zaki
Statements
These units of code can perform actions, repeat tasks,
make choices, build larger program structures, and so on..
Statements
Statements
Compund statements
● .. are statements that have other statements nested
inside them
● Syntax
Header line:
Nested statement block
● The colon (:) is required (easy to forget…)
● Identation is a must
● If the nested block is unimplemented, then put a
“pass” statement there
Compund statements
● Common rules (C vs. Python)
○ Parentheses are optional
■ if (x < y) vs. if x < y
○ End-of-line is end of statement
■ x = 1; vs. x = 1
○ End of indentation is end of block
■ if (x > y) { vs. if x > y:
x = 1; x = 1
y = 2; y = 2
} print(‘hi’)
Indentation syntax
● May seem unusual at first …
● Python almost forces programmers to produce
uniform, regular, and readable code
● You must line up your code vertically, in columns,
according to its logical structure
● Consider C vs. Python code
if (x)
if x:
if (y)
if y:
statement1;
statement1
else
else:
statement2;
statement2
Assignment statements
● Assignments create object references
● Names are created when first assigned
● Names must be assigned before being referenced
● Some operations perform assignments implicitly
Module imports, function and class definitions, for loop variables, and function
arguments are all implicit assignments.
● Basic forms of assignments
Augmented assignments
● Borrowed from the C language, these formats are
mostly just shorthand
● Example
X=X+Y # traditional form
X += Y # augmented form
● Types
● Disadvantage?
Variable name rules
● Syntax: (underscore or letter) + (any number of
letters, digits, or underscores)
● Case matters: SPAM is not the same as spam
● Reserved words are off-limits
Expression statements
● You can use an expression as a statement, too, but…
● because the result of the expression won’t be saved,
it usually makes sense to do so only if the expression
does something useful as a side effect.
● Expressions are commonly used as statements in
two situations:
○ For calls to functions and methods
○ For printing values at the interactive prompt
The ‘if’ statement
● Selects actions to perform.
● The if statement may contain other statements,
including other if’s.
● In fact, Python lets you combine statements in a
program sequentially
● General format
if test1: # if test
statements1 # Associated block
elif test2: # Optional elifs
statements2
The ‘if’ statement
● An example
>>> choice = 'ham'
>>> if choice == 'spam':
... print(1.25)
... elif choice == 'ham':
... print(1.99)
... elif choice == 'eggs':
... print(0.99)
... elif choice == 'bacon':
... print(1.10)
... else:
... print('Bad choice')
...
1.99
Indentation Rules
● Indentation is the empty space to the left of your code
● All statements indented the same distance to the right
belong to the same block of code
● The block ends when the end of the file or a lesser-
indented line is
encountered
● Avoid mixing tabs and
space (your code will
ONLY work if you mix
tabs and spaces
consistently)
Booleans
● All objects have an inherent Boolean true or false
value.
● Any nonzero number or nonempty object is true.
● Zero numbers, empty objects, and the special object
None are considered false.
● Comparisons and equality tests are applied
recursively to data structures.
● Comparisons and equality tests return True or False
(custom versions of 1 and 0 ).
● Boolean and and or operators return a true or false
operand object.
● Boolean operators stop evaluating (“short circuit”) as
soon as a result is known.
Boolean tests
● Logical connection
○ X and Y
■ Is true if both X and Y are true
○ X or Y
■ Is true if either X or Y is true
○ not X
■ Is true if X is false (the expression returns
True or False )
Ternary expression
● No special syntax, just use if...else:
● Python normal form:
if X:
A = Y
else:
A = Z
● Python ternary form:
A = Y if X else Z
● Ternary in C:
A = Y ? X : Z
while loops
● General form
while test: # Loop test
statements # Loop body
else: # Optional else
statements # Run if didn't exit
loop with
break
● An example
>>> import time, datetime
>>> while True:
... print(datetime.datetime.now())
... print('Ctrl-C to stop me!')
... time.sleep(1.0)
break, continue, pass, else
● Syntax
while test:
statements
if test: break # Exit loop now, skip else if present
if test: continue # Go to top of loop now, to test1
else: # Run if we didn't hit a 'break'
statements
● Pass is the no-operation placeholder
while True: pass # Type Ctrl-C to stop me!
for loops
● The for loop is a generic iterator: it can step through the items in
any ordered sequence or other iterable object (like containers)
● Works on strings, lists, tuples, and other built-in iterables, as
well as on user-defined objects
● Syntax
for target in object: # Assign object items to target
statements # Repeated loop body: use target
if test: break # Exit loop now, skip else
if test: continue # Go to top of loop now
else: # Optional else part
statements # If we didn't hit a 'break'
for loop examples
● Step across a list
>>> for x in ["spam", "eggs", "ham"]:
... print(x, end=' ')
...
spam eggs ham
● Iterate over a dictionary
>>> D = {'a': 1, 'b': 2, 'c': 3}
>>> list(D.items())
[('a', 1), ('c', 3), ('b', 2)]
>>> for (key, value) in D.items():
... print(key, '=>', value)
...
a => 1
c => 3
b => 2
Classwork
● Go to the site:
https://drive.google.com/drive/folders/1GGA0RTb79rCl
mvxU2p5qSZpLYdXzQQeG?usp=sharing
● Create here a folder with your Name + Bologna ID’s,
like:
B1232….
● Create here or upload your solution for the excercies
(file naming for excercise 1: e1.py)
● The first solution for each excercise will be rewarded by
1 point
Classwork
1. Write program which will test all numbers between A
and B, and test if they are divisible by C and D. A, B, C
and D are given as command line arguments.
2. Write program, which computes the factorial for a
number given as command line argument.
3. Generate a dictionary, in which the key’s are numbers
starting from 1 to N (given interactively), and the values
are the square of the key-numbers.
4. Ask for a series of numbers separated by commas, and
generate a list of the numbers (not strings containing
numbers)
Homework
1. Try out the commands, statements learned today
2. Finish the exercises you could not resolve during the
lesson