如何让我的代码在 python 中正确循环?
How do I make my code loop properly in python?
我的目标是确保当用户在用户名输入中输入数字时,它不应该接受它并让他们重试。
与 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)
我的目标是确保当用户在用户名输入中输入数字时,它不应该接受它并让他们重试。
与 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)