我的目标是确保当用户在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. ')
答案 0 :(得分:4)
你永远不会停止循环。有两种方法可以做到这一点:要么改变循环条件(永远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!')
第二个循环具有相同的问题,具有相同的解决方案和其他更正。
答案 1 :(得分:0)
替代方式:在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)