python while 循环用户输入

python while loop user input

编写一个程序,不断询问用户输入数字,直到他们输入非数字。

这就是我现在的样子,好像我创建了一个无限循环。

i = 0
count = 0
while i != (int):
    i = input("Enter a number: ")

你可以使用str.isdigit方法,注意如果你在python2你需要使用raw_input因为isdigit()是一个字符串方法:

i='0'
count = 0
while i.isdigit():
    i = input("Enter a number: ") 

在 python 2 中:

i='0'
count = 0
while i.isdigit():
    i = raw_input("Enter a number: ")

您可以要求输入一个数字,然后使用内置的 isdigit() 方法检查输入的字符串是否为数字。目前您的代码不要求输入数字,它只是自动使用 0。它不会考虑用户第一次输入非数字。

i = raw_input("Enter a number: ")
while i.isdigit():
    i = raw_input("Enter a number: ")