(Python 2.7.10) So i am a beginner in python, just started learning about a week ago. I need some help with writing the code commented on lines 3 and 5.If the user enters a word instead of a numerical value then I need the program to tell them error and to restart. I commented the program to make it easier to understand. The program works just fine otherwise. Thank you.
## Ask user for age
age = input("Please enter your age.(numerical value)")
## If input is not a numerical value then tell the user "Error. Enter a numerical value"
## Restart program to let the user try again.
## If age is less than 18 then tell them they are too young
if age < 18:
print (" Access denied. Sorry, you are not old enough.")
## If the user is 18 then grant them access
elif age == 18:
print ("Acess granted. You are just old enough to use this program!")
## If user is any age above 18 then grant them access
else:
print ("Access granted.")
his is a way to make sure you get something that can be interpreted as integer from the user:
while True:
try:
# in python 3:
# age = int(input('Please enter your age.(numerical value)'))
# in python 2.7
age = int(raw_input('Please enter your age.(numerical value)'))
break
except ValueError:
print('that was not an integer; try again...')
the idea is to try to cast the string entered by the user to an integer and ask again as long as that fails. if it checks out, break from the (infinite) loop.
Change your age input part to this:
#keep asking for age until you get a numerical value
while True:
try:
age=int(raw_input("Please enter your age.(numerical value)"))
break
except ValueError:
print "Error. Enter a numerical value"
Related
I'm working in Python 2.7. I want to prompt the user for input, and to analyze the input as a number. If the user inputs something other than a number, I want the program, instead of crashing, to prompt the user again. For example, I'm thinking (in psuedocode):
g=input("Enter a number: ")
while g is not a number:
g=input("That isn't a number. Try again:")
print g**2
Any thoughts?
Try this:
def is_integer(n):
try:
int(n)
return True
except ValueError:
return False
g=raw_input("Enter a number: ")
while not is_integer(g):
g=raw_input("That isn't a number. Try again:")
g = int(g)
print g**2
def get_number():
try:
a = raw_input('Please enter number: ')
return float(a)
except ValueError:
print('Please enter a valid number')
return get_number()
print(get_number())
Please enter number: asfa
Please enter a valid number
Please enter number: asdfasdf
Please enter a valid number
Please enter number: 123.213
123.213
My if statement is not working:
choice = float(input("Enter 1 to enter sec. Enter 2 to enter mins")):
#My problem:
if 'choice' == 1
a = float(input("Enter secs"))
etc...
BTW, I was making a timer, but I need to know... It told me invalid syntax...
Fixed code (with my comments):
choice = int(raw_input("Enter 1 to enter sec. Enter 2 to enter mins")) # no need to use float here, also in python2 please use raw_input
if choice == 1: # you tried to compare `choice` string with 1 (always False), compare choice variable value with 1 instead. Also note, that you missed : after if
a = float(input("Enter secs"))
I figured it out!
choice + int(input("Bla bla bla")):
I forgot the ':'
I'm a beginner at programming with python and confused on how exceptions work. I'm creating a menu list and dictionary for a restaurant and for the cost of item if user types in invalid number or a string I need it to except the value Error and ask the user again but still getting a value error code
while True:
try:
itemCost = float(raw_input("Please enter the cost of this item (ex: 22.45): "))
if itemCost < 0: print "Invalid Number, please try again"
except ValueError:
print "Invalid Number, please try again"
except NameError:
print "Invalid Number, please try again"
except SyntaxError:
print "Invalid Number, please try again"
Update:
This is what im entering but still getting a Value Error code because i used a string instead of a float but want it to give the user a error message.
Please enter the menu item name (quit to exit): Chicken
Please enter the cost of this item (ex: 22.45): rrr
Traceback (most recent call last):
File "/Users/Stan/Documents/Intro to Programming/Program Project #2.py", line 14, in <module>
itemCost = float(raw_input("Please enter the cost of this item (ex: 22.45): "))
ValueError: could not convert string to float: rrr
Process finished with exit code 1
Hi I recently had this program running fine but after fiddling round with it now it doesn't work because when i run it in the shell when the program asks "do you want to enter a user" and I type "yes" it doesn't ask for the user to input he/shes name, DOB in form 00/00/0000, run time, postcode. It just prints "do you want to see your records?" If anyone could help quick it would be much appreciated p.s im really new so I dont 100% understand some things at the moment.
def openfile1(name,dob,time,postcode):
file=open('runnerdata.txt', 'a')
file.write(name+":")
file.write(dob+":")
file.write(time+":")
file.write(postcode+ ":\n")
file.close()
while True:
enter=input("Do you want to enter a user? ")
if enter=="no":
file=open('runnerdata.txt', 'r')
list=(file.readlines())
enter2=input("Do you want to see your records? ")
if enter2=="no":
break
elif enter2=="yes":
name2=input("Enter name to see your records ")
for line in list:
if line.split(":")[0]==name2:
print(line)
elif enter=="yes":
name=input("Enter name ")
dob=input("Enter your DOB in form 00/00/0000 ")
time=input("Enter your run time ")
postcode=input("Enter your postcode ")
openfile1(name,dob,time,postcode)
def openfile1(name,dob,time,postcode):
file=open('runnerdata.txt', 'a')
file.write(name+":")
file.write(dob+":")
file.write(time+":")
file.write(postcode+ ":\n")
file.close()
while True:
enter=input("Do you want to enter a user? ")
if enter=="no":
file=open('runnerdata.txt', 'r')
list=(file.readlines())
enter2=input("Do you want to see your records? ")
if enter2=="no":
break
elif enter2=="yes":
name2=input("Enter name to see your records ")
for line in list:
if line.split(":")[0]==name2:
print(line)
elif enter=="yes":
name=input("Enter name ")
dob=input("Enter your DOB in form 00/00/0000 ")
time=input("Enter your run time ")
postcode=input("Enter your postcode ")
openfile1(name,dob,time,postcode)
Try this
Hi I am 11 yrs old and I am teaching myself how to code. I set myself a task to make a times table quiz that asks 10 questions and inputs random numbers. However, my code is not working and I do not know why. I am using python 2.7.5. This is my code:
print("Here is a quiz to test your knowledge")
print("")
print("Question 1")
import random
print random.randint(1,10)
print ("times")
import random
print random.randint(1,10)
answer = raw_input ("Make your choice: ")
if answer == ran1*ran2:
print "That is correct"
correct=correct +1
else:
print "That is incorrect!"
I can not spot why it is not working but I have not put a for loop in yet so it only asks 1 question. When I run it else is highlighted in red but I do not know why.
Python works without brackets. It is replaced by "spaces or tabs". And we import ONCE, the beginning.
This should work
import random
print("Here is a quiz to test your knowledge")
print("")
print("Question 1")
print random.randint(1,10)
print ("times")
print random.randint(1,10)
answer = raw_input ("Make your choice: ")
if answer == ran1*ran2:
print "That is correct"
correct=correct +1
else:
print "That is incorrect!"