Documente Academic
Documente Profesional
Documente Cultură
Imperative Programming
Python Programs
Interactive Input/Output
One-Way and Two-Way if Statements
for Loops
User-Defined Functions
Assignments Revisited and Parameter Passing
Python program
line1='HelloPythondeveloper...'
A Python program is a
sequence of Python
statements
line2='WelcometotheworldofPython!'
print(line1)
print(line2)
line1='HelloPythondeveloper...'
line2='WelcometotheworldofPython!'
print(line1)
print(line2)
hello.py
$pythonhello.py
HelloPythondeveloper
WelcometotheworldofPython!
first=input('Enteryourfirstname:')
last=input('Enteryourlastname:')
line1='Hello+first+''+last+''
print(line1)
print('WelcometotheworldofPython!')
input.py
Enteryourname:Michael
Enteryourname:
>>>name
>>>
'Michael'
>>>=========RESTART=============
>>>
Enteryourfirstname:Michael
Enteryourfirstname:
Enteryourlastname:Jordan
Enteryourlastname:
HelloMichaelJordan...
WelcometotheworldofPython!
>>>age=input('Enteryourage:')
Enteryourage:18
>>>age
'18'
>>>int(age)
18
>>>eval('18')
18
>>>eval('age')
'18'
>>>eval('[2,3+5]')
[2,8]
>>>eval('x')
Traceback(mostrecentcalllast):
File"<pyshell#14>",line1,in
<module>
eval('x')
File"<string>",line1,in
<module>
NameError:name'x'isnotdefined
>>>
Exercise
Write a program that:
1.
2.
3.
>>>
Enteryourname:Marie
Enteryourage:17
Marie,youwillbe18nextyear!
name=input('Enteryourname:')
age=int(input('Enteryourage:'))
line=name+',youwillbe'+str(age+1)+'nextyear!'
print(line)
Exercise
Write a program that:
1.
2.
3.
One-way if statement
if<condition>:
<indentedcodeblock>
<nonindentedstatement>
The value of
tempis
iftemp>86:
print('Itishot!')
print('Besuretodrinkliquids.')
print('Goodbye.')
50.
90.
True
temp>86:
print('Itishot!')
False
print('Besuretodrinkliquids.')
Print('Goddbye.')
Exercises
Write corresponding if statements:
a) If
ageis greater
benefits
b) If string
'largebonuses'appears
'YoucangetSocialSecurity
in string
reportthen
'Vacation
time!
c) If
hitsis
shieldis
0 then print
>>>report='nobonusesthisyear'
>>>age=45
>>>hits=12
>>>if'largebonuses'inreport:
>>>ifage>62:
>>>shield=0
print('Vacationtime!')
print('YoucangetSocialSecuritybenefits')
>>>ifhits>10andshield==0:
print("You'redead...")
>>>report='largebonusesthisyear'
>>>age=65
>>>if'largebonuses'inreport:
>>>ifage>62:
You'redead...
print('Vacationtime!')
print('YoucangetSocialSecuritybenefits')
>>>hits,shield=12,2
>>>ifhits>10andshield==0:
print("You'redead...")
Vacationtime!
YoucangetSocialSecuritybenefits
>>>
>>>
"You'redead..."
Indentation is critical
iftemp>86:
print('Itishot!')
print('Drinkliquids.')
print('Goodbye.')
iftemp>86:
print('Itishot!')
print('Drinkliquids.')
print('Goodbye.')
True
temp>86:
True
temp>86:
print('Itishot!')
False
print('Itishot!')
False
print('Drinkliquids.')
print('Goddbye.')
print('Drinkliquids.')
print('Goddbye.')
Two-way if statement
if<condition>:
<indentedcodeblock1>
else:
<indentedcodeblock2>
<nonindentedstatement>
The value of
tempis
iftemp>86:
print('Itishot!')
print('Besuretodrinkliquids.')
else:
print('Itisnothot.')
print('Bringajacket.')
print('Goodbye.')
50.
90.
False
True
temp>86:
print('Itisnothot!')
print('Itishot!')
print('Bringajacket.')
print('Besuretodrinkliquids.')
print('Bringajacket.')
Exercise
Write a program that:
1) Requests
2) Requests
3) Prints
a message saying
whether the user is eligible to
vote or not
name=input('Enteryourname:')
age=eval(input('Enteryourage:'))
ifage<18:
print(name+",youcan'tvote.")
else:
print(name+",youcanvote.")
>>>
Enteryourname:Marie
Enteryourage:17
Marie,youcan'tvote.
>>>
============RESTART================
>>>
Enteryourname:Marie
Enteryourage:18
Marie,youcanvote.
>>>
forloop
Executes a block of code for every item of a sequence
If sequence is a string, items are its characters (single-character
strings)
>>>name='Apple'
>>>forcharinname:
print(char)
name=
char=
char=
char=
char=
char=
'Apple'
A
p
p
l
e
'A'
'p'
'p'
'l'
'e'
forloop
Executes a code block for every item of
a sequence
Sequence can be a string, a list,
Block of code must be indented
word=
word=
word=
word=
'stop'
for<variable>in<sequence>:
<indentedcodeblock>
<nonindentedcodeblock>
forwordin['stop','desktop','post','top']:
if'top'inword:
print(word)
print('Done.')
'desktop'
'post'
'top'
>>>
stop
desktop
top
Done.
Exercise
Write for loops that will print the following sequences:
a) 0,
1,
b) 1, 2,
c) 0, 2,
d) 1, 3,
e) 20,
2,
3,
4,
5,
3,
4,
6,
7,
4, 5, 6, 7, 8 , 9, 10
5, 6, 7, 8, 9
8
9
>>>abs(9)
9
>>>max(2,4)
4
>>>lst=[2,3,4,5]
>>>len(lst)
4
>>>sum(lst)
14
>>>print()
>>>
>>>deff(x):
res=2*x+10
returnx**2+10
>>>f(1)
>>>
11
>>>f(3)
19
>>>f(0)
10
deff(x):
res=x**2+10
print(res)
>>>f(2)
14
>>>2*f(2)
28
>>>f(2)
14
>>>2*f(2)
14
Traceback(mostrecentcalllast):
File"<pyshell#56>",line1,in
<module>
2*f(2)
TypeError:unsupportedoperand
type(s)for*:'int'and
'NoneType'
a
b
Exercise
Write function hello() that:
takes a name (i.e., a string) as input
prints a personalized welcome message
Note that the function does not return anything
>>>hello('Julie')
Welcome,Julie,totheworldofPython.
>>>
defhello(name):
line='Welcome,'+name+',totheworldofPython.
line='Welcome,'+name+',totheworldofPython.'
print(line)
Exercise
Write function rng() that:
takes a list of numbers as input
returns the range of the numbers in the list
The range is the difference between the largest and smallest
number in the list
>>>rng([4,0,1,2])
6
>>>
defrng(lst):
res=max(lst)min(lst)
returnres
Docstring
deff(x):
'returnsx**2+10'
res=x**2+10#computeresult
returnres#andreturnit
>>>help(f)
Helponfunctionfin
module__main__:
f(x)
>>>deff(x):
'returnsx**2+10'
res=x**2+10
returnres
>>>help(f)
Helponfunctionfin
module__main__:
f(x)
returnsx**2+10
>>>
Assignment statement: a
second look
a b c d
3
3.3
'three'
[1,2,3]
<variable>=<expression>
1. <expression>is
2.
>>>a
>>>a
Traceback(mostrecentcall
Traceback(mostrecentcall
last):
last):
File"<pyshell#66>",line
File"<pyshell#66>",line
1,in<module>
1,in<module>
a
a
NameError:name'a'isnot
NameError:name'a'isnot
defined
defined
>>>
>>>a=3
>>>a=3
>>>b=2+1.3
>>>b=2+1.3
>>>c='three'
>>>c='three'
>>>d=[1,2]+[3]
3
3.3
'three'
[1,2,3]
[1,7,3]
>>>a
3
>>>a=6
>>>a
6
>>>d
[1,2,3]
>>>d[1]=7
>>>d
[1,7,3]
3
3.3
'three'
[1,7,3]
[1,7,9]
ac and
and bd refer
refer to
to the
the same
same integer
list object
object
>>>a
6
>>>b
3.3
3.3
>>>b=a
>>>b
6
>>>a=9
>>>b
6
>>>c=d
>>>c
[1,7,3]
>>>d[2]=9
>>>c
[1,7,9]
The
listrefers
that ctorefers
changes;
to the
list
object,
a
now
a newtoobject
(9); d
b refers
still refers
to same
the old
object
(6)so
Becausetoo
integers are immutable, a change to a does not affect the
it changes
value
of b lists are mutable, a change to d affects c
Because
Swapping values
a b
Have:
tmp
>>>a
3
>>>b
6
>>>a,b=b,a
>>>tmp=b
>>>b=a
>>>b=a
>>>a=tmp
Want:
a b
Immutable parameter
passing
a
shell
3
defg(x):
x=5
5
>>>
>>>a=3
>>>
>>>g(a)
>>>
Variable
inside
g() refers
to the modify
object athe
refers
to of a in the
Function xg()
did not,
and cannot,
value
interactive shell.
As if we executed x = a
This is because a refers to an immutable object.
shell
[1,2,3]
[5,2,3]
defh(l):
l[0]=5
>>>
>>>lst=[1,2,3]
>>>
>>>h(lst)
>>>
Exercise
Write function swapFS() that:
takes a list as input
swaps the first and second element of the list, but only if
the list has at least two elements
The function does not return anything
>>>mylst=['one','two','three']
>>>swapFS(mylst)
>>>mylst
['two','one','three']
>>>mylst=['one']
>>>swapFS(mylst)
>>>mylst
['one']
>>>
defswapFS(lst):
iflen(lst)>1:
lst[0],lst[1]=lst[1],lst[0]