如何输入循环以便在用户输入其年龄的文本时向用户询问号码

时间:2017-09-27 09:36:40

标签: python python-3.x loops

我正在尝试制作一个程序,询问用户他的姓名,年龄以及他希望看到答案的次数。程序将在他将转为100时输出,并将重复一定次数。

对我来说,难以让程序在输入文字时向用户提出一个数字。

这是我的计划:

def input_num(msg):
    while True:
        try :
            num=int(input(msg))

        except ValueError :
            print("That's not a number")
        else:
        return num
        print("This will never get run")
        break

name=input("What is your name? ")
age=int(input("How old are you? "))
copy=int(input("How many times? "))
year=2017-age+100
msg="Hello {}. You will turn 100 years old in {}\n".format(name, year)
for i in range(copy):
   print(msg)

2 个答案:

答案 0 :(得分:1)

当您提示用户注明年龄时:age=int(input("How old are you? "))您没有使用input_num()方法。

这应该对你有用 - 使用你写的方法。

def input_num(msg):
    while True:
        try:
            num = int(input(msg))
        except ValueError:
            print("That's not a number")
        else:
            return num

name = input("What is your name? ")
age = input_num("How old are you? ") # <----
copy = int(input("How many times? "))
year = 2017 - age + 100
msg = "Hello {}. You will turn 100 years old in {}\n".format(name, year)
for i in range(copy):
    print(msg)

答案 1 :(得分:-2)

这将检查用户输入是否为整数。

age = input("How old are you? ")
try:
    age_integer = int(age)
except ValueError:
    print "I am afraid {} is not a number".format(age)

将其放入while循环,您就可以了。

while not age:
    age = input("How old are you? ")
    try:
        age_integer = int(age)
    except ValueError:
        age = None
        print "I am afraid {} is not a number".format(age)

(我从这个SO Answer获取了代码)

另一个好的解决方案来自this blog post

def inputNumber(message):
  while True:
    try:
       userInput = int(input(message))       
    except ValueError:
       print("Not an integer! Try again.")
       continue
    else:
       return userInput 
       break