用户输入和while循环
7-1 汽车租赁
car = input("Let me see if I can find you a Subaru\n")
print(car)
程序运行后显示
Let me see if I can find you a Subaru
输入“interesting”,打印出
interesting
7-2 餐馆订位
num = input("请问有多少人用餐?\n")
num = int(num)
if num <= 8:
print("这里有空位")
else :
print("没有足够的空位")
运行程序分别输入5 和9 ,结果不同
请问有多少人用餐?
5
这里有空位
红色为用户输入,下同
请问有多少人用餐?
9
没有足够的空位
7-3 10 的整数倍
num = input("请输入一个数字\n")
num = int(num)
if num % 10 == 0:
print(str(num) + "是10的整数倍")
else :
print(str(num) + "不是10的整数倍")
运行代码分别输入50和102,结果如下
请输入一个数字
50
50是10的整数倍
请输入一个数字
102
102不是10的整数倍
7-5 电影票
while True:
x = input("请输入你的年龄\n")
x = int(x)
if x < 0:
print("输入无效")
elif x < 3:
print("你可以免费观看")
elif x <= 12:
print("你的票价为10美元")
elif x > 12:
print("你的票价为15美元")
运行程序输入数字:
请输入你的年龄
2
你可以免费观看
请输入你的年龄
5
你的票价为10美元
请输入你的年龄
11
你的票价为10美元
请输入你的年龄
13
你的票价为15美元
请输入你的年龄
函数:
8-1 消息
def display_message():
print("我在这章学习了python的函数")
display_message()
运行程序后打印出这句话:
我在这章学习了python的函数
8-9 魔术师:
def show_magicians(names):
for name in names:
print(name)
magician = ["Tom", "Jerry", "Mary"]
show_magicians(magician)
程序运行结果
Tom
Jerry
Mary
8-10 了不起的魔术师
def show_magicians(names):
for name in names:
print(name)
def make_great(names):
for i in range(0, len(names)):
names[i] = "the Great " + names[i]
magician = ["Tom", "Jerry", "Mary"]
show_magicians(magician)
make_great(magician)
show_magicians(magician)
运行程序后输出:
Tom
Jerry
Mary
the Great Tom
the Great Jerry
the Great Mary
8-11 不变的魔术师
def show_magicians(names):
for name in names:
print(name)
def make_great(names):
for i in range(0, len(names)):
names[i] = "the Great " + names[i]
return names
magician = ["Tom", "Jerry", "Mary"]
show_magicians(magician)
new_magician = make_great(magician[:])
print("Magicians in funtion make_great")
show_magicians(new_magician)
print("Magicians outside funtion make_great")
show_magicians(magician)
运行程序后
Tom
Jerry
Mary
Magicians in funtion make_great
the Great Tom
the Great Jerry
the Great Mary
Magicians outside funtion make_great
Tom
Jerry
Mary