允许int介于0到100之间,请询问agian

时间:2016-12-16 10:31:29

标签: python

嗨尝试做一个程序,要求用户输入一个数字,并且只允许0到100之间的int 如果没有,我想问同样的问题。编辑我尝试做一个程序,要求用户提供一个数字,然后用户必须键入0 - 100之间的nuber,如果不是问我问agin。如果用户键入一个sting,它将生成另一条消息,然后要求用户输入0-100之间的数字。如果nuber是正确的,我想打破循环。 EDIT2问题解决了! Thanx为每个人提供快速帮助。我是一个菜鸟......

print('Whats your name?')
name = input()
print('Hello ' + name + ' enter a number between 0 - 100')

number = input()
while True:
    try:
        if  0 <= int(number) <= 100:
            print('Good')
            break
        else:
            print('You must enter a nuber between 0 - 100')
            continue
    except ValueError:
            print('You must enter a nuber between 0 - 100')

4 个答案:

答案 0 :(得分:3)

您需要使用while num < 0 or num > 100

print("What's your name?")
name = input()

print('Hello ' + name + ' enter a number between 0 - 100')

try:
    num = int(input())
except ValueError:
    print('You must enter a number between 0 - 100')

while num < 0 or num > 100:
    try:
        num = int(input())
    except ValueError:
        print('You must enter a number between 0 - 100')

print('Good')

输出示例:

What's your name?
'John Doe'
Hello John Doe enter a number between 0 - 100
200
120
300
50
Good

答案 1 :(得分:2)

你需要在while循环中取input()。这是一个冗长的代码:

def take_int_as_input(default=-1):
    try:  
        return int(input())
    except:
        return default

print('enter a number between 0 - 100')
num = take_int_as_input()
while 0 > num or num > 100:
    print('You must enter a nuber between 0 - 100')
    num = take_int_as_input()
else:
    print "Good"

将上述代码粘贴到名为code.py的文件中。以下是输出:

$ python code.py 
enter a number between 0 - 100
d
You must enter a nuber between 0 - 100
gf
You must enter a nuber between 0 - 100
rfe
You must enter a nuber between 0 - 100
876543
You must enter a nuber between 0 - 100
22
Good

简洁且不那么详细的版本:

print('enter a number between 0 - 100')
while not (0 <= take_int_as_input() <= 100):
    print('You must enter a nuber between 0 - 100')
else:
    print "Good"

答案 2 :(得分:1)

试试这段代码

print('Whats your name?')
name = input()

while True:
    number = input()
    try:
        if 0 <= int(number) <= 100:
            print('Good')
            break
    except ValueError:
        print('You must enter a number between 0 - 100')

input()应该在循环中

答案 3 :(得分:0)

您可以使用由重复定义的函数:

def ask():
    num = int(input("Enter your number between 0 and 100"))
    if num < 0 or num > 100:
        ask()
    else:
        print('Good')
        pass