[英]How do I make my code loop properly in python?
我的目标是确保当用户在userName输入中键入数字时,它不应该接受它并使他们再试一次。
与userNumber相同。 当用户输入字母时,应该用另一行提示他们再输入一次。
问题在于,当他们输入正确的输入时,程序将继续循环并无限期地列出数字。
我是编码的新手,我试图弄清楚自己在做错什么。 先感谢您!
userName = input('Hello there, civilian! What is your name? ')
while True:
if userName.isalpha() == True:
print('It is nice to meet you, ' + userName + "! ")
else:
print('Choose a valid name!')
userNumber = input('Please pick any number between 3-100. ')
while True:
if userNumber.isnumeric() == True:
for i in range(0,int(userNumber) + 1,2):
print(i)
else:
print('Choose a number please! ')
userNumber = input('Please pick any number between 3-100. ')
您永远不会停止循环。 有两种方法可以执行此操作:更改循环条件(永远为while true
循环),或从内部break
。
在这种情况下,使用break
更容易:
while True:
# The input() call should be inside the loop:
userName = input('Hello there, civilian! What is your name? ')
if userName.isalpha(): # you don't need `== True`
print('It is nice to meet you, ' + userName + "! ")
break # this stops the loop
else:
print('Choose a valid name!')
第二个循环具有相同的问题,具有相同的解决方案和其他更正。
另一种方法:在while
循环中使用条件。
userName = ''
userNumber = ''
while not userName.isalpha():
if userName: print('Choose a valid name!')
userName = input('Hello there, civilian! What is your name? ')
print('It is nice to meet you, ' + userName + "! ")
while not userNumber.isnumeric():
if userNumber: print('Choose a number please! ')
userNumber = input('Please pick any number between 3-100. ')
for i in range(0,int(userNumber) + 1,2):
print(i)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.