4-PythonIntroCourse Midterm Material
4-PythonIntroCourse Midterm Material
Statements
اﻟﻣﺗﻐﯾرات
Constants
• Fixed values such as numbers, letters, and strings are called
“constants” - because their value does not change
• Case Sensitive
• Good: spam eggs spam23 _speed
x = 3.9 * x * ( 1 - x )
A variable is a memory location x 0.6
used to store a value (0.6).
0.6 0.6
x = 3.9 * x * ( 1 - x )
0.4
x = 3.9 * x * ( 1 - x )
** Power
• Exponentiation (raise to a power) looks % Remainder
different from in math.
Numeric Expressions
>>> x = 2 >>> j = 23
>>> x = x + 2 >>> k = j % 5
+ Addition
>>> print x >>> print k
4 3 - Subtraction
12 3 / Division
>>> print y 64
4R3 ** Power
5280 %
Remainder
>>> z = y / 1000 5 23 (Modulus)
>>> print z 20
5 3
Order of Evaluation
• When we string operators together - Python must know which one
to do first
int a;
• In Python variables, literals, and float b;
constants have a “data type” a=5
b = 0.43
• In Python variables are
“dynamically” typed. In some In Python:
other languages you have to
explicitly declare the type before a=5
you use the variable a = “Hello”
a = [ 5, 2, 1]
More on “Types”
• In Python variables, literals, and
constants have a “type” >>> d = 1 + 4
>>> print d
• Python knows the difference 5
between an integer number and a
string >>> e = 'hello ' +
'there'
>>> print e
• For example “+” means “addition” hello there
if something is a number and
“concatenate” if something is a concatenate = put together
string
Type Matters >>> e = 'hello ' + 'there'
>>> e = e + 1
• Python knows what “type” Traceback (most recent call last):
everything is File "<stdin>", line 1, in <module>
TypeError: cannot concatenate 'str'
and 'int' objects
• Some operations are prohibited >>> type(e)
<type 'str'>
• You cannot “add 1” to a string >>> type('hello')
<type 'str'>
>>> type(1)
• We can ask Python what type <type 'int'>
something is by using the type() >>>
function.
Several Types of Numbers
>>> x = 1
• Numbers have two main types >>> type (x)
<type 'int'>
• Integers are whole numbers: -14, -2, 0, 1, >>> temp =
100, 401233 98.6
>>> type(temp)
<type 'float'>
• Floating Point Numbers have decimal >>> type(1)
parts: -2.5 , 0.0, 98.6, 14.0 <type 'int'>
>>> type(1.0)
• There are other number types - they are <type 'float'>
variations on float and integer >>>
>>> print float(99) / 100
Type Conversions 0.99
>>> i = 42
>>> type(i)
<type 'int'>
• When you put an integer and >>> f = float(i)
floating point in an expression >>> print f
the integer is implicitly 42.0
converted to a float >>> type(f)
<type 'float'>
• You can control this with the >>> print 1 + 2 * float(3) / 4 -
5
built in functions int() and float()
-2.5
>>>
String >>> sval = '123'
>>> type(sval)
hours = 35.0
What is this rate = 12.50
code doing? pay = hours * rate
print pay
Exercise
Program:
print 'Smaller'
x=5
Yes if x < 10:
X > 20 ?
print
'Smaller‘
print 'Bigger'
if x > 20:
print 'Bigger'
print 'Finis' print 'Finis'
Comparison Operators
• Boolean expressions = an
expression that evaluates to
true or false < Less than
<= Less than or Equal
• Boolean expressions use == Equal to
comparison operators >= Greater than or Equal
evaluate to - True or False
> Greater than
!= Not equal
• Comparison operators look
at variables but do not Remember: “=” is used for assignment.
change the variables
x=5
Comparison
if x == 5 :
print 'Equals 5‘ Operators
if x > 4 :
print 'Greater than 4’
if x >= 5 :
print 'Greater than or Equal 5‘
if x < 6 :
print 'Less than 6'
Yes
X == 5 ?
The IF Statement
Indentation Rules
• Increase indent after an if statement or for statement (after : )
• Maintain indent to indicate the scope of the block (which lines are
affected by the if/for)
if x > 2 :
print 'Smaller' print 'Bigger'
print 'Bigger'
else :
print
'Smaller' print 'All Done'
x = 42
yes
if x > 1 : x < 100
print 'Hello'
astr = 'Bob'
try:
print 'Hello' istr = int(astr)
istr =
int(astr) print 'There'
print 'There'
except: istr = -1
istr = -1
print 'Done', istr Safety net
print 'Done', istr
Sample try / except
rawstr = raw_input('Enter a number:')
try:
ival = int(rawstr)
except: Enter a number:42
ival = -1 Nice work
Enter Hours: 45
Enter Rate: 10
Pay: 475.0
475 = 40 * 10 + 5 * 15
Exercise
• Indentation
• One Way Decisions
• Two way Decisions if : and else :
Functions اﻟﻌﻣﻠﯾﺎت
Stored (and reused) Steps
def
hello(): Program:
print 'Hello' Output:
print 'Fun' def hello():
print 'Hello' Hello
hello() print 'Fun' Fun
hello() Zip
print “Zip” print 'Zip‘ Hello
hello() Fun
hello()
We call these reusable pieces of code “functions”.
Python Functions
• There are two kinds of functions in Python
• Built-in functions that are provided as part of Python - raw_input(),
type(), float(), max(), min(), int(), str(), …
big = max('Hello
world')
Function name
def print_lyrics():
print "I'm a lumberjack, and I'm okay."
print 'I sleep all night and I work all day.' Hello
Yo
print 'Yo' 7
x=x+2
print x
Definitions and Uses
def print_lyrics():
print "I'm a lumberjack, and I'm okay."
print 'I sleep all night and I work all day.'
print 'Yo'
print_lyrics() Hello
x=x+2 Yo
print x I'm a lumberjack, and I'm okay.
I sleep all night and I work all day.
7
Arguments
• An argument is a value we pass into the function as its input when we
call the function
def greet():
return "Hello " Hello Glenn
Hello Sally
print greet(), "Glenn"
print greet(), "Sally"
def greet(lang):
Return Value if lang == 'es':
return 'Hola '
elif lang == 'fr':
return 'Bonjour '
• A “fruitful” function is one else:
that produces a result (or a return 'Hello '
return value)
print greet('en'),'Glenn'
• The return statement ends Hello Glenn
the function execution and print greet('es'),'Sally'
“sends back” the result of Hola Sally
the function print greet('fr'),'Michael'
Bonjour Michael
Arguments, Parameters, and Results
>>> big = max( 'Hello world‘ )
Parameter
>>> print big
>>> w
def max(inp):
blah
blah ‘w’
for x in y:
Argument blah
blah Result
return ‘w’
Multiple Parameters / Arguments
• We can define more than def addtwo(a, b):
one parameter in the added = a + b
function definition return added
• Make a library of common stuff that you do over and over - perhaps
share this with your friends...
The range() function
• range() is a built-in function x = range(5)
that allows you to create a print x
sequence of numbers in a [0, 1, 2, 3, 4]
range
x = range(3, 7)
print x
• Very useful in “for” loops [3, 4, 5, 6]
which are discussed later in
the Iteration chapter x = range(10, 1, -2)
print x
• Takes as an input 1, 2, or 3 [10, 8, 6, 4, 2]
arguments. See examples.
Modules and the import statement
• A program can load a module import math
file by using the import radius = 2.0
statement area = math.pi * (radius ** 2)
12.5663706144
• Use the name of the module math.log(5)
1.6094379124341003
• Functions and variables
names in the module must be import sys
qualified with the module sys.exit()
name. e.g. math.pi
Summary
• Functions
• Built-In Functions:
• int(), float(), str(), type(), min(), max(), dir(), range(), raw_input(),…
• Defining functions: the def keyword
• Arguments, Parameters, Results, and Return values
Loops and Iteration
n=5 Repeated Steps
No Yes
n>0? Program: Output:
print n n=5 5
while n > 0 : 4
print n 3
n = n -1
n=n–1 2
print 'Blastoff!' 1
print n Blastoff!
print 'Blastoff' 0
Loops (repeated steps) have iteration variables that
change each time through a loop. Often these
iteration variables go through a sequence of numbers.
n=5
An Infinite Loop
No Yes
n>0?
while True:
> hello there
line = raw_input('> ')
hello there
if line == 'done' :
> finished
break
finished
print line
> done
print 'Done!'
Done!
while True: No Yes
True ?
line = raw_input('> ')
if line == 'done' :
....
break
print line
print 'Done!' break
...
print 'Done'
http://en.wikipedia.org/wiki/Transporter_(Star_Trek)
Using continue in a loop
• The continue statement ends the current iteration and jumps to the
top of the loop and starts the next iteration
while True:
> hello there
line = raw_input('> ')
hello there
if line[0] == '#' :
> # don't print
continue
this
if line == 'done' :
> print this!
break
print this!
print line
> done
print 'Done!'
Done!
No
True ? Yes
while True:
line = raw_input('> ') ....
if line[0] == '#' :
continue
if line == 'done' : continue
break
print line
...
print 'Done!'
print 'Done'
Indefinite Loops
• While loops are called "indefinite loops" because they keep going until
a logical condition becomes False
• The loops we have seen so far are pretty easy to examine to see if
they will terminate or if they will be "infinite loops"
• We can write a loop to run the loop once for each of the items in a
set using the Python for construct
• These loops are called "definite loops" because they execute an exact
number of times
print 'Before'
for value in [9, 41, 12, 3, 74, 15] :
if value > 20: Before
print 'Large number',value Large number 41
print 'After' Large number 74
After
If we just want to search and know if a value was found - we use a variable that starts
at False and is set to True as soon as we find what we are looking for.
Finding the smallest value
smallest = None
print 'Before' Before
for value in [9, 41, 12, 3, 74, 15] : 99
If smallest is None : 9 41
smallest = value 9 12
elif value < smallest : 33
smallest = value 3 74
print smallest, value 3 15
print 'After', smallest After 3
We still have a variable that is the smallest so far. The first time through the
loop smallest is None so we take the first value to be the smallest.
The "is" and "is not" Operators
• Python has an "is" operator that
smallest = None can be used in logical
print 'Before' expressions
for value in [3, 41, 12, 9, 74, 15] :
if smallest is None :
smallest = value • Implies 'is the same as'
elif value < smallest :
smallest = value • Similar to, but stronger than ==
print smallest, value
print 'After', smallest
• 'is not' also is a logical operator
Summary
• While loops (indefinite)
• Summing in loops
• Infinite loops
• Averaging in loops
• Using break
• Searching in loops
• Using continue
• Detecting in loops
• For loops (definite)
• Largest or smallest
• Iteration variables