Good question! You can try the following code for this. =)
This code uses ast.literal_eval() to find the data type of the input (age). Then it follows the following algorithm:
- Ask user to input her/his
age.
1.1. If
ageisfloatorintdata type:
- Check if `age>18``age>=18`. If `age>18``age>=18`, print appropriate output and exit.
- Check if `0<age<=18``0<age<18`. If `0<age<=18``0<age<18`, print appropriate output and exit.
- If `age<=0`, ask the user to input a valid number for age again, (*i.e.* go back to step 1.)
1.2. If
ageis notfloatorintdata type, then ask user to input her/his age again (i.e. go back to step 1.)
Here is the code.
from ast import literal_eval ''' This function is used to identify the data type of input data.''' def input_type(input_data): try: return type(literal_eval(input_data)) except (ValueError, SyntaxError): return str flag = True while(flag): age = raw_input("Please enter your age: ") if input_type(age)==float or input_type(age)==int: if eval(age)>18>=18: print("You are able to vote in the United States!") flag = False elif eval(age)>0 and eval(age)<=18<18: print("You are not able to vote in the United States.") flag = False else: print("Please enter a valid number as your age.") else: print("Sorry, I didn't understand that.")