Академический Документы
Профессиональный Документы
Культура Документы
The if Statement
if boolean-expression1:
suite1
elif boolean_expression2:
suite2
elif Boolean_expressionN:
suiteN
else:
else_suite
Example:
>>> i = 1
>>> while i < 6:
>>> print(i)
>>> if i == 3:
>>> break
>>> i += 1
Output:
1
2
3
The continue Statement
>>> i = 0
>>> while i < 6:
>>> i += 1
>>> if i == 3:
>>> continue
>>> print(i)
Output:
1
2
4
5
6
The for… in Statement:
for variable in iterable:
suite
>>> for country in [“Denmark”, “Finland”,
“Norway”, “Sweden”]:
>>> print(country)
Cont.
>>> countries = [“Denmark”, “Finland”, “Norway”,
“Sweden”]
>>> for country in countries:
>>> print(country)
Cont.
>>> for letter in
“ABCDEFGHIJKLMNOPQRSTUVWXYZ”:
>>> if letter in “AEIOU”:
>>> print(letter, “is a vowel”)
>>> else:
>>> print(letter, “is a consonant”)
Read an integer. If it is odd, then print its square
Output:
Ballroom
Lead pipe
Col. Mustard
>>> accusation = {‘room’ : ‘ballroom’, ‘weapon’ : ‘lead pipe’,
‘person’ : ‘Col. Mustard’)
Output:
(‘room’, ‘Ballroom’)
(‘weapon’, ‘Lead pipe’)
(‘person’, ‘Col. Mustard’)
Assigning the keys and the values of a tuple in a
single step
>>> for key, value in accusation.items()
>>> print(“key is ”, key, “ and its values are: ”, value)
Iterate multiple sequences in parallel with zip()
>>> days = [‘Monday’, ‘Tuesday’, ‘Wednesday’]
>>> fruits = [‘banana’, ‘orange’, ‘peach’]
>>> drinks = [‘coffee’, ‘tea’, ‘beer’]
>>> desserts = [‘tiramisu’, ‘ice cream’, ‘pie’, ‘pudding’]
>>> for day, fruit, drink, dessert in zip(days, fruits, drinks, desserts):
>>> print(day, “: drink ”, drink, “ eat ”, fruit, “ enjoy ”, dessert)
Output:
Monday: drink coffee eat banana enjoy tiramisu
Tuesday: drink tea eat orange enjoy ice cream
Wednesday: drink beer eat peach enjoy pie
*Pudding is not displayed
Generate number of sequences with range(start, stop, step)
By default the start is 0
by default the step is 1
>>> for x in range(0, 3):
>>> print(x)
Output:
0
1
2
3
Making a range from 2 down to 0:
>>> for x in range(2, -1, -1)
>>> print(x)
Output:
2
1
0
Cont.
>>> for x in list(range(2, -1, -1))
>>> print(x)
Output:
[2, 1, 0]