简体   繁体   English

python while循环用户输入

[英]python while loop user input

Write a program that keeps asking the user for numbers until they enter a non-number. 编写一个程序,不断询问用户输入数字,直到他们输入非数字。

This is what I have now, it seems I have created an infinite loop. 这就是我现在所拥有的,似乎我已经创建了一个无限循环。

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

You can use str.isdigit method ,Note that if you are in python 2 you need to use raw_input because isdigit() is a string method : 您可以使用str.isdigit方法,请注意,如果您在python 2中,则需要使用raw_input因为isdigit()是一个字符串方法:

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

in python 2 : 在python 2中:

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

You could ask for a number, and then check if the string entered is a digit using the built in isdigit() method. 您可以要求一个数字,然后使用内置的isdigit()方法检查输入的字符串是否为数字。 Currently your code does not ask for a digit to be entered, it just uses 0 automatically. 当前,您的代码不要求输入数字,它仅自动使用0。 It would not account for a user entering a non-number the very first time. 它不会解释用户第一次输入非数字的情况。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM