天天看点

python里while先print是为什么_初识python07--用户输入和while循环

7.1、函数input()

用int()将输入转换成整型

求模运算符:%,用于两数相除返回余数。eg. 100%10=0

练习:

# coding=GBK

#7-1

car=input('What car do you wanna rent?')

print('Let me see if I can find you a Subaru' )

#7-2

people=input('How many peole eat?')

people=int(people)

if people > 8:

print('There is no empty table.')

else:

print('Free table')

#7-3

number=input('Enter a number,and I will tell if it is a multiple of 10 ')

number=int(number)

if number%10 == 0:

print('It is a multiple of 10')

else:

print("It isn't")

7.2 while 循环

while循环不断运行。当指定条件不满足时,退出循环。

使用标志用于判断程序是否处于活动状态。True运行,False结束。

用break退出循环。

用continue结束此次循环,进入下次循环。

务必对每个While循环进行测试,以免进入无限循环。当进入无限循环时,按Ctrl+C退出或关闭窗口。

相关练习

#7-4

print('Please add your ingredient: ')

a=''

while a != 'quit':

a=input()

if a != 'quit':

print('We will add '+a)

else:

print('Please wait a minute')

#7-5 and 7-6

prompt='Please enter your age: '

prompt+='\ninput quit to exit.'

active=True

while active:

age=input(prompt)

if age=='quit':

break

else:

if int(age) < 3:

print('Free')

elif int(age) <= 12:

print('Please pay $10.')

else:

print('Please pay $15.')

7.3 用while处理列表和字典

在列表间移动元素:

练习:

#7-8、7-9

解一:

sandwich_orders=['A','pastrami','C','pastrami','E','pastrami']

print('Pastrami is sold out')

finished_sandwich=[]

b=0

while b < len(sandwich_orders):

a=sandwich_orders[b]

if a.lower() == 'pastrami':

b=b+1

continue

else:

finished_sandwich.append(a)

print('I made your '+a)

b=b+1

print(finished_sandwich)

删除列表内的特定值:

#7-9

sandwich_orders=['A','pastrami','C','pastrami','E','pastrami']

print('Pastrami is sold out')

finished_sandwich=[]

while 'pastrami' in sandwich_orders:

sandwich_orders.remove('pastrami')

finished_sandwich=sandwich_orders

print(finished_sandwich)

使用用户输入填充字典:

7-10

#coding=GBK

places={}

active=True

while active:

name=input('姓名:')

place=input('梦想的度假胜地:')

places[name]=place

repeat=input('还有人要回答吗?(yes/no)')

if repeat.lower() =='no':

active=False

print('调查结果')

for name,place in places.items():

print(name+'想去'+place+'.')