7.1input()函数
1.简单例子
message=input('enter words:')
print(message)
结果:
2.使用int()获取数值输入
age=input('how old are u?')
age=int(age)
if age <=15:
print('you are a teenager')
input()获取的是一个字符串,不可以当作int型 进行数字运算。
3.求模运算符 %
将两个数相除 并返回余数
练习
1.餐馆订位 :编写一个程序,询问用户有多少人用餐。如果超过8人,就打印一条消息,指出没有空桌;否则指出有空桌
num=input('how many people will be dinning in the table? ')
num=int(num)
if num >8:
print("there's more table for u")
else:
print('enjoy your meal')
7.2while循环
1.简单例子 从1数到5
num=1
while num<=5:
print(num)
num+=1
2.使用break退出循环
mesg='enter the nameof a city:'
mesg+='\n(Enter quit when u finished)'
while True:
city=input(mesg)
if city=='quit':
break;
else:
print("I'd love to go to "+city.title()+' !')
运行结果:
3. cintinue语句
eg.打印1到10中的偶数
num=0
while num<=10:
num+=1
if num%2!=0:
continue
print(num)
练习
1.比萨配料 :编写一个循环,提示用户输入一系列的比萨配料,并在用户输入’quit’ 时结束循环。每当用户输入一种配料后,都打印一条消息,说我们会在比萨 中添加这种配料。
print('enter quit to end')
toppings=''
while toppings != 'quit':
toppings=input('choose toppings for your pizza: ')
print('add '+toppings+' to your pizza!')
print('end')
2.电影票 :有家电影院根据观众的年龄收取不同的票价:不到3岁的观众免费;3~12岁的观众为10美元;超过12岁的观众为15美元。请编写一个循环,在其中询问用 户的年龄,并指出其票价。、
year=1
while year:
year=input('how old are u? ')
year=int(year)
if year<=0:
break;
elif year<3:
print('free')
elif year<=12:
print('10 dollars')
elif year>12:
print('15 dollars')
else:
break