0% found this document useful (0 votes)
2 views24 pages

Scientific Python 2025-02-11

This document covers various programming concepts in Python, including statements, compound statements, assignment statements, and control flow structures such as 'if' statements and loops. It emphasizes the importance of indentation, variable naming rules, and boolean operations. Additionally, it provides classwork and homework assignments to reinforce the learned concepts.

Uploaded by

Maiky Khorani
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
2 views24 pages

Scientific Python 2025-02-11

This document covers various programming concepts in Python, including statements, compound statements, assignment statements, and control flow structures such as 'if' statements and loops. It emphasizes the importance of indentation, variable naming rules, and boolean operations. Additionally, it provides classwork and homework assignments to reinforce the learned concepts.

Uploaded by

Maiky Khorani
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 24

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

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy