Exercises
Exercise 1
print ("3" * "bc") ---> error
Exercise 2
str3 = 'world' str3[-1] == 'd' str3[:-1] = 'worl' str3[::-1] = 'dlorw'
Exercise 3
temp = 120
if temp > 85:
print("Hot")
elif temp > 100:
print("REALLY HOT!")
elif temp > 60:
print("Comfortable")
else:
print("Cold")
answer : Hot
Exercise 5
num = 10
for num in range(5):
print(num)
print(num)
##答案 0,1,2,3,4,4
##提示 num是全局变量
for variable in range(20):
if variable % 4 == 0:
print(variable)
if variable % 16 == 0:
print('Foo!')
##答案 0,Foo!,4, 8, 12, 16, Foo!
##提示 要考虑0
Exercise 6
school = 'Massachusetts Institute of Technology'
numVowels = 0
numCons = 0
for char in school:
if char == 'a' or char == 'e' or char == 'i' \
or char == 'o' or char == 'u':
numVowels += 1
elif char == 'o' or char == 'M':
print(char)
else:
numCons -= 1
print('numVowels is: ' + str(numVowels))
print('numCons is: ' + str(numCons))
## How many times does o print out? Disregard the o's in last two print statements.
o will not be printed!!
because if there exists an 'o' in the string, statement immediately after 'if' will be executed.
Remaining cases are not checked(i.e, elif condition is not checked or executed)
After the first condition involving char == 'o' is checked and found true,
the remaining conditions will not be tested for that particular character.
##What will the value of the variable numCons be?
-25(if you count the spaces you will get the answer -25)