0

**EDIT:***This has been solved!*

Im programming a program that will tell you if you are old enough to vote. And, when it asks you for your age, I want it to say a certain thing if the user types letters instead of a number, something like "Please enter a number, not a letter. Restart." Here is the code I have right now:

name = raw_input("What is your name?: ")
print("")
print("Hello, "+name+".\n")
print("Today we will tell you if you are old enough to vote.")
age = input("How old are you?: ")
if age >= 18:
    print("You are old enough to vote, "+name+".")
elif age < 18:
    print("Sorry, but you are not old enough to vote, "+name+".")
  • I suggest you to use string formatting, i.e. replace all those `'Hello, ' + name + '.'` with `'Hello, %s.' % name`. Here's a good tutorial for string formatting: https://pyformat.info/ – Markus Meskanen May 28 '17 at 16:22

2 Answers2

0
name = raw_input("What is your name?: ")
print("")
print("Hello, "+name+".\n")
print("Today we will tell you if you are old enough to vote.")
while True:
    age = raw_input("How old are you?: ")
    try:
        age = int(age)
    except ValueError:
        print("Please enter a number, not a letter. Restart.")
    else:
        break
if age >= 18:  
    print("You are old enough to vote, "+name+".")
elif age < 18:    # else:
    print("Sorry, but you are not old enough to vote, "+name+".")

In the try-except-else, we try to convert age from string to integer. If an ValueError occurs, it means that the input string isn't a legal integer. If not, then we can simply jump out the while loop and do the following task.

Note1: better don't use input() in python2. Refer to this.

Note2: elif is useless. Simply use else.

YLJ
  • 2,940
  • 2
  • 18
  • 29
-1

You can try something like this :

name = raw_input("What is your name?: ")
print("")
print("Hello, "+name+".\n")
print("Today we will tell you if you are old enough to vote.")
while True:
    try:
        #get the input to be an integer.
        age = int(raw_input("How old are you?: "))
        #if it is you break out of the while
        break
    except ValueError:
        print("Please enter a number, not a letter. Restart.")
if age >= 18:
    print("You are old enough to vote, "+name+".")
elif age < 18:
    print("Sorry, but you are not old enough to vote, "+name+".")
RPT
  • 728
  • 1
  • 10
  • 29
  • I tried this, but I got an error: Traceback (most recent call last): File "vote.py", line 8, in age = int(input("How old are you?: ")) File "", line 1, in NameError: name 'Dhbe' is not defined – MrSprinkleToes May 28 '17 at 16:04
  • change `input` to `raw_input` – RPT May 28 '17 at 16:05