Practicing Loops and Conditions
Contents
Practicing Loops and Conditions#
1. Write a while
loop such that you print out the first 10 natural numbers:#
1
2
3
4
5
6
7
8
9
10
# variable declarations?
# while
2. Write a while
loop that prints the following even numbers:#
2
4
6
8
10
12
14
16
18
20
# variables?
# while ...
3. Write a while
loop that processes all the lower-case letters and prints out a letter if it is a vowel#
Preliminaries to writing the loop#
A handy operator in Python is in
which returns a boolean
answering whether some item is present in an iterable such as a string. For example:
some_characters = 'abcdefg'
# use 'in' to see if an 'e' is present
print('x' in some_characters) # will return and print 'False'
print('e' in some_characters) # will return and print 'True'
False
True
Use in
to write the loop.
Additional hints:
use an
if
statement in the loopThe
if
statement should check if a character isin
the stringvowels
.If it is, use a print statement to output it.
letters = 'abcdefghijklmnopqrstuvwxyz'
vowels = 'aeiou'
count = 0
while count < len(letters):
# do something here
count += 1
4. Write a while
loop that generates a random integer from 1 to 9 and only breaks out if the integer is equal to 5#
from random import randint
while True:
pass
5. Write a procedure that takes in an integer and prints backward from that integer down to 0 and then prints “Blastoff!”#
def countdown(i):
while i >= 0:
pass