python学习六 用户输入和while循环

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

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

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

结果:

Tell me something,and I will repeat it back to you:哈哈哈哈哈哈
哈哈哈哈哈哈

注意:
sublime text不能运行提示用户输入的程序。你可以用它编写,但需要在终端运行。

但我觉得在终端运行有点麻烦,就上万能的互联网搜索了下解决方案,如下:
解决不能适用input()的问题: https://blog.csdn.net/yiqzq/article/details/87949704
在上述过程中,你还可能遇到提示there are no packages available for installation的问题 ,主要原因是网络访问的问题吧,可以参照:https://www.cnblogs.com/Hiooary/p/7542440.html

1.1编写清晰的程序
prompt = "If you tell us who you are ,we can know you."
prompt += "\nWhat is your first name? "
name = input(prompt)
print("\nHello " + name + "!")

结果:

If you tell us who you are ,we can know you.
What is your first name? dandan

Hello dandan!

1.2使用int()来获取数值输入

使用函数input()时,python将用户输入解读为字符串,不能与数值进行比较。

>>> age = input("How old are you? ")
How old are you? 20
>>> age
'20'
>>> age > 18
Traceback (most recent call last):
  File "<pyshell#2>", line 1, in <module>
    age > 18
TypeError: '>' not supported between instances of 'str' and 'int'

为解决这个问题,使用int()函数将输入视为数值。

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

举个例子

age = input("How old are you? ")
age = int(age)
if age >= 18:
	print("\nYou are old enough to run(竞选)!")
else:
	print("\nYou will be able to run when you are a little old!")

结果:

How old are you? 18

You are old enough to run(竞选)!
1.3求模运算符

求摸运算符将两个数相除并返回余数。

>>> 4 % 3
1
>>> 5 % 3
2

可以用来判断奇偶:

number = input("Enter a number,and I'll tell you if it's even or odd: ")
number = int(number)

if number % 2 == 0:
	print("\nThe number " + str(number) + " is even!")
else :
	print("\nThe number " + str(number) + " is odd!")

结果:

Enter a number,and I'll tell you if it's even or odd: 30

The number 30 is even!

2.while 循环简介

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

2.1使用while循环
current_number = 1
while current_number <= 5:
	print(current_number)
	current_number += 1

结果:

1
2
3
4
5
2.2让用户选择何时退出

可以使用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)

结果:

Tell me something, and I will repeat it back to you :
Enter 'quit' to end the program. Hello everyone!
Hello everyone!

Tell me something, and I will repeat it back to you :
Enter 'quit' to end the program. yeah
yeah

Tell me something, and I will repeat it back to you :
Enter 'quit' to end the program. quit
quit
2.3使用标志

在很多要求都满足才能继续运行的程序中,可定义一个变量,用于判断整个程序是否处于活动状态,这个变量被称为标志。

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

结果:

Tell me something, and I will repeat it back to you :
Enter 'quit' to end the program. I am a little girl!
I am a little girl!

Tell me something, and I will repeat it back to you :
Enter 'quit' to end the program. give me five!
give me five!

Tell me something, and I will repeat it back to you :
Enter 'quit' to end the program. quit
2.4使用 break 退出循环

break语句用于控制程序流程,可以使用它来控制哪些代码行将执行,哪些代码行不执行,从而让程序按你的要求执行你要的代码。

prompt = "\nPlease enter the name of a city you have visited:"
prompt += "\nEnter 'quit' to end the program. "

while True:
	city = input(prompt)
	if city == 'quit':
		break
	else :
		print("I have visited " + city.title() + "!")

结果:

Please enter the name of a city you have visited:
Enter 'quit' to end the program. hangzhou
I have visited Hangzhou!

Please enter the name of a city you have visited:
Enter 'quit' to end the program. suzhou
I have visited Suzhou!

Please enter the name of a city you have visited:
Enter 'quit' to end the program. quit

以while True 打头的循环将不断运行,直到遇到break语句。
注意: 在任何python循环中都可以使用break语句

2.5在循环中使用continue

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

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

结果:

1
3
5
7
9

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

要记录大量的用户和信息,需要再while循环中使用列表和字典。for循环是一种遍历列表的有效方式,但在for循环中不应修改列表,否则将导致python难以跟踪其中的元素。要在遍历列表的同时对其进行修改,可使用while循环。通过将while循环同列表和字典结合起来使用,可收集、存储并组织大量输入,供以后查看显示。

3.1在列表之间移动元素
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 confirmed:")
for confirmed_user in confirmed_users:
	print(confirmed_user.title())

结果:

Verifying user: Candace
Verifying user: Brian
Verifying user: Alice

The following users have been confirmed:
Candace
Brian
Alice
3.2删除包含特定值的所有列表元素

删除列表中的多条‘cat’元素

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

结果:

['dog', 'cat', 'dog', 'goldfish', 'cat', 'rabbit', 'cat']
['dog', 'dog', 'goldfish', 'rabbit']
3.3使用用户输入来填充字典
responses = {}
polling_active = True
while polling_active:
	name = input("\nWhat is your name? ")
	response = input("Which mountian would you like to climb someday? ")

	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 + ".")

结果:

What is your name? Littleegg
Which mountian would you like to climb someday? Mount  Qomolangma
Would you like to let another person respond? (yes/no) yes

What is your name? CangER
Which mountian would you like to climb someday? Mount  Qomolangma
Would you like to let another person respond? (yes/no) no

--- Poll Results ---
Littleegg would like to climb Mount  Qomolangma.
CangER would like to climb Mount  Qomolangma.
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值