Scientific Python 2025-02-11
Scientific Python 2025-02-11
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)
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
○ 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
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
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