Python入门笔记四

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/Helenzhn/article/details/79314839

一.用户输入和while循环

1.函数input()的工作原理。

函数input()让程序暂停运行,等待用户输入一些文本。获取用户输入后,Python将其储存在一个变量中,以方便你使用。

eg:

message = input("Tell me something, and I will repeat it back to you: ")
print(message)

函数input()接受一个参数:即要向用户显示的提示或说明,让用户知道该如何做。程序等待用户输入,并在用户按回车键后继续运行。

input()练手小demo

prompt = "If you tell us who you are, we can personalize the messages you see."
prompt += "\nWhat is your first name? "
name = input(prompt)
print("\nHello, " + name + "!")

使用函数input()时,Python将用户输入解读为字符串。当我们需要接收使用用户输入的数字时,可以使用int(),让Python将输入视为数值。

eg:

>>> age = input("How old are you? ")
How old are you? 21 
>>> age = int(age)
>>> age >= 18
True

demo(input()实际运用,判断一个人是否满足坐过山车的身高要求)

height = input("How tall are you,in inches?")
height = int(height)
if height>=36:
	print("\nYou're tall enough to ride!")
else:
	print("\nSorry")

求模运算符(%),用来处理数值信息,将两个数相除并返回余数。

>>> 4 % 3
1
>>> 5 % 3
2
>>> 6 % 3
0
>>> 7
求模运算符不会指出一个数是另一个数的多少倍,而只指出余数是多少。可以利用它来判断数值的奇偶性。因为偶数都能被2整除,则(number)%2结果为零的话,该数就一定为偶数了;否则就是奇数。


练手:

1.汽车租赁:编写一个程序,询问客户要租赁什么样的汽车,并打印一条消息:“Let me see if I can find you a Subaru”。

species=input("What species do you want?")
print("Let me see if I can find you a Subaru")

2.餐馆订位:编写一个程序,询问用户有多少人用餐。如果超过8人,就打印出一条消息,指出没有空桌;否则指出有空桌。

Num=input("Please tell me how much people need eat food !")
Num=int(Num)
if Num>8:
	print("Sorry, there is no vacancy for now.")
else:
	print("Come with me.")

3.10的倍数:让用户输入一个数字,并指出这个数字是否是10的整数倍。

Num=input("Please input a number !")
Num=int(Num)
if Num%10!=0:
	print("NO.")
else:
	print("YES.")

2.while循环简介。

for循环用于针对集合中的每个元素都一个代码块,而while循环不断地运行,直到指定的条件不满足为止。

num=1
while num<=5:
	print(num)
	num+=1

可以使用while循环让程序在用户愿意时不断地运行,让用户选择何时退出。

prompt="\nTell me something,and I will repeat it back to you:"
prompt+="\nEnter 'quit' to end the program"
message=""
while message !="quit":
	message=input(prompt)
	print(message)

要立即退出while循环,不在运行余下的代码,也不管条件测试的结果如何,可以使用break语句退出循环。

prompt="\nPlease enter the name of a city you have visited:"
prompt+="\n(Enter 'quit' when you are finished)"
while True:
	city = input(prompt)
	
	if city=='quit':
		break
	else:
		print("I'd love to go to "+city.title()+"!")
以while True打头的循环将不断运行,直到遇到break语句退出循环。
(注意:在任何python循环中都可以使用break语句。例如可以试用break语句来退出遍历列表或字典的for循环)


在循环中使用continue

要返回循环的开头,并根据条件测试结果决定是否继续执行循环,可以使用continue语句,他不像break语句那样不再执行余下的代码并退出整个循环。

c_number =0
while c_number<10:
	c_number+=1
	if c_number %2==0:
		continue
	print(c_number)
		


练手

1.编写一个循环,提示用户输入一系列的披萨配料,并在用户输入‘quit’时结束循环。能当用户输入一种配料后,都打印一条消息,说我们会在比萨中添加这种配料。

message="\nPlease add your need!"
message+=("\n(Enter 'quit' when you are finished)")
while True:
	n_food=input(message)
	
	if n_food=='quit':
		break
	else:
	    print("Ok,I will add it")
2.在一家电影院根据观众的年龄收取不同的票价:不到三岁的观众免费;3-12岁的观众为10美元;超过12岁的观众为15美元。请编写一个程序,在其中询问用户的年龄,并指出piaoj
message="\nPlease input your age!"

while True:
   age=input(message)
   age=int(age)
   if (age<=3):
	   print("You don't need pay money.")
   elif (age>3 and age<=12):
	   print("You need pay 12$.")
   elif (age>12):
	   print("You need pay 15$.")

3.使用while循环来处理列表和字典

假设有一个列表。其中包含新注册但还未验证的网站用户;验证这些用户后,如何将他们移动到另一个已验证用户表中?一种办法是使用一个while循环,在验证用户的同时将其从未验证用户列表中提取出来,再将其加入到另一个已验证用户列表中。

unconfirmed_users=['alice','brian','candace']
confirmed_users=[]

while unconfirmed_users:
	current_user=unconfirmed_users.pop()
	
	print("Verifying user:"+current_user.title())
	confirmed_users.append(current_user)
	
print("\nThe following users have been confiemed:")
for confirmed_user in confirmed_users:
	print(confirmed_user.title())
     

使用while循环删除列表中所有包含特定值的元素

pets=['dog','cat','dog','goldfish','cat','rabbit','cat']
print(pets)
while 'cat' in pets:
	pets.remove('cat')
	
print(pets)
     


使用用户输入来填充字典

responses={}
polling_active=True

while polling_active:
	name=input("\nWhat is you name?")
	response=input("Which mountain would you like to climb comeday?")
	responses[name]=response
	
	repeat=input("Would you like to let another person respond?(yes/no)")
	if repeat=='no':
		polling_active=False
	
print("\n--Poll Results--")
for name,response in responses.items():
	print(name+" would like to climb "+response)
     

练习

1.创建一个名为sandwich_orders的列表,在其中包含各种三明治的名字;在创建一个名为finished_sandwiches的空列表。遍历列表sanwich_orders,对其中的三明治,都打印一条消息,如I made your tuna sandwich,并将其移到列表finished_sandwiches。所有三明治都做好后,打印一条消息,将这些三明治列出来。


猜你喜欢

转载自blog.csdn.net/Helenzhn/article/details/79314839