Except ValueErrors - python-2.7

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

Related

How to prompt the user for input and only allow a numeric response (in Python 2.7)

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

Python input/strings

(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"

Python function will cycle through but error on the final iteration

On the following Python function I am using Python 2.7.6 and SQLAlchemy as the ORM. I am stumped as to why I keep getting the following error even though the function cycles through.
def vacantShelter():
#Used to stay in bounds of the all the entries in the DB
shelterCount = session.query(Shelter).count
shelter_id = 1
print "Here are the Shelter results:"
while(shelter_id<=shelterCount):
shelter = session.query(Shelter).filter(Shelter.id == shelter_id).first()
if(shelter.max_capacity >= getShelterOccupancy(shelter_id)):
print shelter.name + " has available space"
else:
print shelter.name + " is full! :("
shelter_id = shelter_id + 1
What is confusing me is that it is functioning correctly at first considering there are results, I do not understand why on the last iteration it fails or what to do about it.
`Here are the Shelter results:
Oakland Animal Services has available space
San Francisco SPCA Mission Adoption Center is full! :(
Wonder Dog Rescue has available space
Humane Society of Alameda is full! :(
Palo Alto Humane Society is full! :(
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "pup_test.py", line 82, in vacantShelter
if(shelter.max_capacity >= getShelterOccupancy(shelter_id)):
AttributeError: 'NoneType' object has no attribute 'max_capacity'`
The most likely reason for this error is the presence of holes in the Shelter.id values. For example, there the table could contain rows with the id value of [1, 2, 3, 4, 5, 7]. When you reach the last element, you will try to find a Shelter with id of 6, but it does not exist.
In principal, the way your code works now is by making a very bold assumption that all rows in the database have consecutive id values starting from 1. But this is generally not the case. Instead, you could directly iterate over the instances, and not load them one-by-one:
def vacantShelter():
shelters = session.query(Shelter).all()
for shelter in shelters:
if(shelter.max_capacity >= getShelterOccupancy(shelter.id)):
print shelter.name + " has available space"
else:
print shelter.name + " is full! :("
Also, it is much cleaner.

Why won't my program work in python?

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!"

TypeError: expected a character buffer object (trying to write to a text file)

I am trying to code a simple program that writes the output of a function to a text file, and I had it working, but today I tried to run it and it gives me this error at line 54: TypeError: expected a character buffer object.
Here is that line:
f.write(spotify.getCurrentTrack())
Also, here is the rest of the code:
from pytify import Spotify
spotify = Spotify()
import time
var2exit = 1
print "This program was created by Drew Halverson. Do not claim as your own work."
time.sleep(2)
print "This program could not have been created without the help of pytify."
time.sleep(2)
print "Also, this program is not affiliated with Spotify at all and is not an official app."
time.sleep(2)
print "For information on how to use this program and what its use is, check readme.txt"
yes = set(["yes", "y", "YES"])
no = set(["no", "n", "NO"])
r = open("readme.txt", "r")
print "Would you like to read the readme now (type yes or no)?"
choice = raw_input()
if choice in yes: print r.read()
print " "
time.sleep(2)
if choice in no: print "Hi! I will now be checking what song is playing on spotify."
time.sleep(2)
print "Make sure spotify is playing (Only the downloaded application will work. The program is not compatible with the web player version of Spotify."
time.sleep(2)
print " "
time.sleep(1)
print "Have you downloaded Spotify on this computer already? Type yes or no..."
choice2 = raw_input()
if choice2 in yes: print "Alright! Let's go!"
if choice2 in no: var2exit = 2
if var2exit == 2:
print "Go install Spotify first, then try again."
time.sleep(5)
print "Goodbye!"
time.sleep(2)
sys.exit()
var = 1
while var == 1 :
spotify.getCurrentTrack()
spotify.getCurrentArtist()
f = open("current_track.txt", "w")
g = open("current_artist.txt", "w")
f.write(spotify.getCurrentTrack())
g.write(spotify.getCurrentArtist())
print "The current Track is:"
print spotify.getCurrentTrack()
print "The current Artist is:"
print spotify.getCurrentArtist()
time.sleep(10)
print" "
print "Checking again..."
I know there are similar questions to this but none that I found exactly answered my problem. Thanks.