python学习6:用户输入和while循环

python学习6:用户输入和while循环

1 input()的工作原理

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

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

python会将用户输入解读为字符串,可以使用int(),可以让python将输入视为数值。

height = input('How tall are you,in inches?')
height = int(height)  # 在比较前,要将height(此时是字符串)转化成数值表示

if height >= 48:
    print('\nYou\'re tall enough to ride.')
else:
    print('\nYou\'ll be able to ride when you\'re a little older.')

结果:

How tall are you,in inches?28

You'll be able to ride when you're a little older.

注:将数值输入用于计算与比较前,务必将其转换为数值表示

1.2 求模运算符

求模运算符**%**,可将两个数相除并返回余数,如:4%3 1,可以依靠这一点判断一个数的奇偶性。

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

if number % 2 == 0:
    print(f'\n The number {number} is even.')
else:
    print(f'\nThe number {number} is odd.')

结果:

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

 The number 8 is even.

2 while循环

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

2.1 使用while循环

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

    print(current_number)

结果:

1
3
5
7
9

2.2 让用户选择何时退出

可定义一个退出值,如若用户输入的不是这个值,程序就将接着运行。

2.3 使用标志

定义一个变量,用于判断整个程序是否处于活动状态。可以让程序在标志为True时继续运行,并在任何事件导致标志的值为False时让程序停止运行。

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.first
first

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

2.4 使用break退出循环

  • 要立即退出while循环,不再运行循环中余下的代码,也不管条件测试的结果如何,可使用break语句。
  • break语句用于控制程序流程,可用来控制哪些代码将执行、哪些代码不执行,从而让程序按要求执行要执行的代码,可使用在任意循环中。

2.5 在循环中使用continue

要返回循环开头,并根据条件测试结果决定是否继续执行循环,可使用continue语句,可忽略余下代码,并返回循环开头。

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

    print(current_number)

结果:

1
3
5
7
9

2.6 避免无限循环

要避免无限循环,务必对每个while循环进行测试,确保其按预期结束,程序至少有一个地方能让循环条件为False,或者break

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

要在遍历列表的同时对其进行修改,可使用while循环。

3.1 在列表之间移动元素

使用一个while循环,在验证用户的同时将其从未验证用户列表中提取出来,再将其加入另一个已验证用户列表中。

unconfirmed_users = ['alice', 'brian', 'candace']
confirmed_users = []
while unconfirmed_users:
    current_user = unconfirmed_users.pop()  # pop()以每次一个的方式从列表末尾删除一个元素
    print(f"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

The following users have been confirmed:
Candace
Verifying user:Brian

The following users have been confirmed:
Candace
Brian
Verifying user:Alice

The following users have been confirmed:
Candace
Brian
Alice

3.2 删除为特定值的所有列表元素

要删除所有特定元素,可不断运行一个while循环,直到列表中不再包含特定值。

# 删除为特定值的所有列表元素
pets = ['dog', 'cat', 'dog', 'goldfish', 'cat', 'rabbit', 'cat']
print(pets)
# 通过while外加remove
while 'cat' in pets:
    pets.remove('cat')

print(pets)

结果:

['dog', 'cat', 'dog', 'goldfish', 'cat', 'rabbit', 'cat']
['dog', 'dog', 'goldfish', 'rabbit']

3.3 使用用户输入来填充字典

可使用while循环提示用户输入任意多的信息。

responses = {}
polling_active = True
while polling_active:
    name = input("\nWhat is your name?")
    response = input("Which mountain 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(f"{name} would like to climb {response}.")

结果:

What is your name?liuyang
Which mountain would you like to climb someday?dadongshan
Would you like to let another person respond?(yes/no)no

---Poll Results---
liuyang would like to climb dadongshan.

4 参考文献

python编程:从入门到实践

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值