0

I am trying to do a program that asks the user his name, age, and the number of times he wants to see the answer. The program will output when he will turn 100 and will be repeated a certain number of times.

What is hard for me is to make the program asks a number to the user when he enters a text.

Here is my program:

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)
DavidG
  • 24,279
  • 14
  • 89
  • 82

2 Answers2

1

When you're prompting your user for the age: age=int(input("How old are you? ")) you're not using your input_num() method.

This should work for you - using the method you wrote.

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)
DavidG
  • 24,279
  • 14
  • 89
  • 82
Cicero
  • 2,872
  • 3
  • 21
  • 31
-2

This will check if the user input is an integer.

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

Put that into a while loop and you're good to go.

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)

(I took the code from this SO Answer)

Another good solution is from 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 
Jason
  • 514
  • 5
  • 21