python - Python中的while循环问题,重复字符串
问题描述
a = input('Enter your username...')
while (a == 'SuperGiraffe007&'):
print('Welcome!')
else:
print("Try again...")
a = input('Enter your username...')
while (a == 'SuperGiraffe007&'):
print('Welcome!')
- 代码正常运行,但是当我输入正确的用户名时,字符串“欢迎!” 永远重复,使我的浏览器崩溃。如何阻止它重复并且只打印一次?
解决方案
看起来您误解了while
循环的作用。它检查你给它的条件,只要条件为真,它就会不断重复循环体。您描述的无限循环正是您对代码的要求。
我认为您想要的是当用户输入正确的用户名时停止的循环:
a = input('Enter your username...')
while a != 'SuperGiraffe007&': # stop looping when the name matches
print("Try again...")
a = input('Enter your username...') # ask for a new input on each loop
print('Welcome!')
推荐阅读
- r - 如何创建独立的 Rmath.h 库来访问 C 中的 R 函数?
- python - 使用 Item Pipelines 清理 Html 标签并在 Scrapy 中获取输出
- html - 为什么 HTML 和 body 元素的高度最初等于视口,但如果内容增加,那么它的高度也会增加?
- sql-server - 如何在 SQL Server 中处理 MMddyyyy 日期格式?
- slack - 无法向 Slack 机器人发送直接消息,功能已关闭
- ruby-on-rails - 如何根据 ruby 中的类型和名称键找到总和?(红宝石哈希数组)
- sql - SQL:给定一个字符串数组,过滤字符串列是否部分包含在该数组中
- reference - ReferenceField React-Admin 中的唯一值
- c# - 将用户重定向到未经授权的页面(临时解决方案)
- javascript - 无法使用 Ionic 5 监听发出的事件