I am making a price is right game. I am currently working on a game mode similar to the contestant row, where they guess the price of an item.
When it asks you to submit a bid, if you enter a word (instead of a bid), the program crashes and displays the following error:
"Traceback (most recent call last):
File "C:\Users\alexe\AppData\Local\Programs\Python\Python36\Thepriceisright.py", line 36, in
contestantrow()
File "C:\Users\alexe\AppData\Local\Programs\Python\Python36\Thepriceisright.py", line 24, in contestantrow
protagnum=int(input(propername +", what is your bid?"))
ValueError: invalid literal for int() with base 10: 'alexei'"
Here's my code:
import random
print(" The Price is Sorta Right - 000776331")
welcomeplayer = True
contestantrow = True
def welcome():
while True:
global welcomeplayer
global propername
welcomeplayer = input("Please enter your name using only letters")
validname = welcomeplayer.isalpha()
propername = welcomeplayer.capitalize()
if validname == True:
print( propername, " ! Come on down! You're the next contestant on the Price is (sorta) right")
print (" Dew Drop welcomes " ,propername ," to contestants row joining EIMNOT A. HUMAN,ARTHURFICIAL EINTEL , ROBORT")
return
else:
print("Please only write letters on your name tag")
welcomeplayer = False
def contestantrow():
while True:
print("Dew Drop shows the price that you are bidding on")
protagnum=int(input(propername +", what is your bid?"))
if protagnum > 0:
componebid = random.randint(1,1000)
print("EIMNOT A. HUMAN bids: ",componebid)
comptwobid = random.randint(1,1000)
print("ARTHURFICIAL EINTEL bids: ",comptwobid)
compthreebid =random.randint(1,1000)
print("ROBORT bids: ",compthreebid)
else:
print(" Dew Drop says [Im sorry bids should start at atleast one dollar]")
contestantrow = False
welcome()
contestantrow()
protagnum=int(input(propername +", what is your bid?"))
You're converting an int / string to int. "1" will work but "a" will raise a ValueError
while True:
try:
protagnum=int(input(propername +", what is your bid?"))
break
except ValueError:
print("Invalid bid, please try again")
Related
In Python, This can not loop many times and cannot find ID number in def.
Every time I try to run the program I get the error
"NameError: name 'askname' is not defined"
and in textfile Keep only the latest data
I expect the output of #def new_booking to be Keep data in files continuously but the actual output is kept data in files just one sentence
I expect the output of #def pre_booked to be Extract data from a file but the actual output is
"NameError: name 'askname' is not defined"
import random
# total=0
# people=0
total1 = 0
total2 = 0
# mini bar
def mini_bar():
mini_bar_total = 0
print("£50 for the Bar")
askbar = input("Would you like a mini bar? Y/N")
if askbar.upper() == "Y":
mini_bar_total = mini_bar_total + 50
return mini_bar_total
# breakfast
def breakfast(people, asknights):
breakfast_total = 0
print("£25 for breakfast")
askdinner = input("Would you like dinner? Y/N")
if askdinner.upper() == "Y":
breakfast_total = (people * 25) * asknights
print("total: £", breakfast_total)
return breakfast_total
# dinner
def dinner(people, asknights):
dinner_total = 0
print("£25 for Dinner")
askdinner = input("Would you like dinner? Y/N")
if askdinner.upper() == "Y":
dinner_total = (people * 25) * asknights
return dinner_total
# number customers
def num_customers():
customer_total = 0
print("£50 an Adult")
askadult = int(input("How many adults? "))
customer_total = askadult * 50
print("total: £", customer_total)
print("£25 a Child")
askchild = int(input("How many children? "))
customer_total = (askchild * 25) + customer_total
print("total: £", customer_total)
return customer_total, askadult, askchild
# number of nights (multiplier)
def num_nights(customer_total):
nights_total = 0
waiting = True
while waiting == True:
try:
asknights = int(input("How many nights are you staying for? "))
nights_total = customer_total * asknights
print("total: £", nights_total)
break
except ValueError:
print("invalid input!")
return nights_total, asknights
# New Booking *********
def new_booking():
askname = str(input("Please enter your name? "))
idnumber = random.randint(100, 999)
customer_total, numAdults, numChild = num_customers()
Num_people = numAdults + numChild
nights_total, asknights = num_nights(customer_total)
askbar = mini_bar()
askbreakfast = breakfast(Num_people, asknights)
askdinner = dinner(Num_people, asknights)
total = askdinner + askbreakfast + askbar + asknights
detailslist = (idnumber, askname, numAdults, numChild, asknights, askbar, askbreakfast, askdinner)
for i in detailslist:
f = open('newbooking.txt', 'w')
f.write(str(detailslist) + '\n')
print(i)
print("your total amount is: £", total)
print("your Name & ID number is: ", askname, idnumber)
# Pre booking ***** is not defind
def pre_booked():
name = input("enter your name or ID number: ")
if name == (askname) or (idnumber):
detailslist = [idnumber, askname, askadult, askchild, asknights, askbar, askbreakfast, askdinner]
for i in detailslist:
print(i)
print("total: £", total)
# main menu, start of program.
def main_menu():
print("##################### WELCOME TO BAY HOTEL ###########################")
print('''Please see what is available at the Hotel,\nAdult Prices per night: £50pp,\nChild price: £25pp,\nMiniBar price: £50 per room,\nBreakfast: £20pp,\nDinner: £25pp''')
while True:
prebook = input("Have you booked? Y/N")
if prebook.upper() == "N":
new_booking()
elif prebook.upper() == "Y":
pre_booked()
main_menu()
- I expect the output of #def new_booking to be Keep data in files continuously but the actual output is keep data in files just one sentence
- I expect the output of #def pre_booked to be Extract data from file but the actual output is "NameError: name 'askname' is not defined"
I think it's because your way to writing data in files.
Working with files has 3 step:
1) Opening file
2) Read [from] / Write [to] file
3) Closing file
third step is what you don't handled it.
You want to write a list in file and you are opening that file in each iteration. It's not a good idea (opening and closing files have their overhead) when you can do it once.
I changed some of your new_booking function and wrote it here:
# New Booking *********
def new_booking():
askname = str(input("Please enter your name? "))
idnumber = random.randint(100, 999)
customer_total, numAdults, numChild = num_customers()
Num_people = numAdults + numChild
nights_total, asknights = num_nights(customer_total)
askbar = mini_bar()
askbreakfast = breakfast(Num_people, asknights)
askdinner = dinner(Num_people, asknights)
total = askdinner + askbreakfast + askbar + asknights
detailslist = (idnumber, askname, numAdults, numChild, asknights, askbar, askbreakfast, askdinner)
# I handled opening and closing file with [python with statement]
# It close files automatically at the end
with open('newbooking.txt', 'w') as f:
for i in detailslist:
f.write(str(detailslist) + '\n')
print(i)
print("your total amount is: £", total)
print("your Name & ID number is: ", askname, idnumber)
The problem here is that you havent actually defined askname in your pre_booked() function so you cant compare against it. In new_booking() you are asking for the username with askname = str(input("Please enter your name? ")) however in the pre_booked() case you dont so you cant use it there without first getting the values from somewhere.
Seeing that you save the new_booking() to a file you probably want to load the data from your file like this:
accounts = []
with open(r"<FILEPATH", "r") as booking_file:
for line in booking_file:
accounts.append(line)
In your new_booking function it might be better to put all the related data in line by line or maybe even use dicts so you can later be sure which values belong together instead of writing all the values into their own line. So you might want to do this instead:
with open('newbooking.txt', 'w') as booking_file:
f.write(detailslist)
Then you can read line by line and possibly use ´eval()´ to get a list or dictionary right from your string or atleast you know the values in one line belong together later on.
You might also want to consider using "a" for append instead of w for write in your bookings file depending if you want to have multiple booking values in your file or just the one.
So I have an otherwise easy homework assignment that wants me to input my grades for subjects, etc. The amount of input varies with the number of subjects the user wants to enter. The input works fine, but when I print out the saved values only the ones most recently entered are saved. Here is my code for input:
def gpa_input(classList):
print("please enter how many classes you have")
while True:
try:
numOfClasses = int(input())
except ValueError:
print("please enter a valid number")
continue
else:
break
for i in range (numOfClasses):
classList.append(subject)
print("enter name of " + str(i+1) + "th subject:")
classList[i].name = input()
print("enter num of credits for " + str(i+1) + "th subject:")
while True:
try:
classList[i].credits = int(input())
except ValueError:
print("please enter a valid number")
continue
else:
break
print("enter grade for " + str(i+1) + "th subject:")
while True:
try:
classList[i].gradePercentage = int(input())
except ValueError:
print("please enter a valid number")
continue
else:
break
A subject is a class containing a string value and 2 int values, defined as following:
class subject:
def __init__(name, credits, gradePercentage):
self.name = name
self.credits = credits
self.gradePercentage = gradePercentage
And here is the code that prints out all of this:
def main():
gpa_input(classList)
for i in range (len(classList)):
print(classList[i].name)
print(classList[i].credits)
print(classList[i].gradePercentage)
What is the problem with my code? Am I iterating through something the wrong way, or is there something not getting properly assigned/saved?
You've got into the very common "trap".
The problem is in how you initialize your subject class.
Here you just append a class to the list:
classList.append(subject)
The situation here is the following:
Once you called subject without braces you will have a new object.
But when you call it on the second time - python will not initialize the new object for you and just return the object created on the first step.
So all you need is to properly initialize all subject objects.
Two ways:
1) Remove args from subject definition and make default values are none + add braces to the classList.append(subject)
2) Collect all values in your for loop into variables and at the end of the function initialize you subject class with proper args.
I need help to figure out how to fix errors in my Python code Assignment.
Basically I need create a program that should calculate the monthly average price for Google and tell us the best and worst six-month period for Google.
The average price is defined as ((v1*c1)+(v2*c2)+(v3*c3)+(v4*c4)...+(vn*cn)) / (v1+v2+v3+v4...+vn) where vi is the volume for day i and ci is the adjusted close price for day i.
For this assignment we'll look at Google from 2004 to 2012. The data-set we'll need is a table in CSV format and can be downloaded from https://www.dropbox.com/s/qr7cu2kui654kgz/googlePrices.csv.
So far I've created the Python code below but it's show some errors message and I couldn't figure out.
Thank you in advance.
Regards,
Roberto Leal
============================================================
Code:
__author__ = 'Roberto'
def get_values():
import operator
data_file = open("googlePrices.csv")
def get_data_list(file_name):
data_list = [] # always start with an open list
for line_str in data_file:
data_list.append(line_str.strip().split(',')) # removes all commas from the csv file
return data_list
def monthlyAverage(list_of_tuples=[]):
averageList = []
currentYear_int = 2012
month_int = 11
sum_float = float()
count = 0
for a_tuple in list_of_tuples:
dateStr = a_tuple[0]
Floatdata = a_tuple[1]
listdate = dateStr.split(',')
Year_int = int(listdate[0])
month_int = int(listdate[1])
date_year_str = "Date: " + str(month_int) + "-" + str(currentYear_int)
if month_int != currentYear_int:
float_average = sum_float / count
list_average = [date_year_str , float_average]
average_tuple = tuple(list_average)
averageList.append(average_tuple)
current_month_int = month_int
sum_float = 0.0
count = 0
sum_float += Floatdata
count += 1
return averageList
def best_6_month(averageList):
averageList.sort()
print("The 6 best months fo google are: ")
print()
print(averageList)
def worst_6_month(averageList):
averageList.reverse()
print("The 6 worst months for google are: ")
print()
print(averageList)
optionStr = ""
if optionStr != "0":
print("------------------------------")
print("\n Google Stock Prices. 2004 - 2012")
print("------------------------------")
print("Please choose an option")
print()
print("1. Calculate Average")
print("2. View best six months")
print("3. View worst six months")
print("0. Exit program")
print()
optionStr = input("Enter you choice now: ")
if (len(optionStr) != 1) or (optionStr not in "0123"):
print("You have entered an invalid number!")
print("Please try again")
elif optionStr == "1":
monthlyAverage()
elif optionStr == "2":
best_6_month()
elif optionStr == "3":
worst_6_month()
elif optionStr == "0":
print("\n Exiting program... Goodbye.")
else:
print("\n Bad option")
===============================================================
Error:
Traceback (most recent call last):
File "C:/Users/Kate/Desktop/College DIT/projecttest1/Project_3.py", line 97, in <module>
best_6_month()
TypeError: best_6_month() missing 1 required positional argument: 'averageList'
Process finished with exit code 1
Traceback (most recent call last):
File "C:/Users/Kate/Desktop/College DIT/projecttest1/Project_3.py", line 94, in <module>
monthlyAverage()
File "C:/Users/Kate/Desktop/College DIT/projecttest1/Project_3.py", line 48, in monthlyAverage
list_average = [date_year_str , float_average]`enter code here`
UnboundLocalError: local variable 'date_year_str' referenced before assignment
Process finished with exit code 1
import os
def createFile():
if os.path.exists("highscores.txt") == False:
myFile = open("highscores.txt","w")
myFile.close()
def inputInt():
number = input(str("please input your score "))
try:
return int(number)
except:
print ("this is not an acceptable input, please try again")
inputInt()
def addScore():
name = input("Please enter the name you wish to add")
score = inputInt()
messages = "thank you"
'''open the highscores line and read in all the lines to a list called scorelist.
then close the file'''
scoresFile = open("highscores.txt","r")
scoresList = scoresFile.readlines()
scoresFile.close()
#check each line in the scoresList list
for i in range(0,len(scoresList) ):
#check to see if the name is in the line
if name in scoresList[i]:
#if it is then strip the name from the text. this should leave theb score
tempscore = scoresList[i].replace(name,"")
#if the score is higher then add it to the list
if int(tempscore)<score:
message = "Score updated"
scoresList[i] = (name + str(score))
#write the scores back to the file
scoresFile = open("highscores.txt","w")
for line in scoresList:
scoresFile.write(line + "\n")
scoresFile.close()
#no need to continue so break
break
else:
#message as score too low
message= "score too low. not updated"
if message("Score updated"):
message = "New score added"
scoresFile = open("highscores.txt","a")
scoresFile.write(name + str(score) + "\n")
scoresFile.close()
print (message)
addScore()
Above is the code. The error shown is:
Traceback (most recent call last):
File "E:\Computer Science\python code\highScores\highscores1.py", line 66, in <module>
addScore()
File "E:\Computer Science\python code\highScores\highscores1.py", line 60, in addScore
File "E:\Computer Science\python code\highScores\highscores1.py", line 60, in addScore
if message("Score updated"):
UnboundLocalError: local variable 'message' referenced before assignment
(1) You are referring to message which is undefined when no names are found in scoresList[i]. Put a
message = ""
line before your for loop. I don't know your actual intent, so this will make the error go away but check if the logic is still correct.
(2) You are doing the comparison incorrectly. You should write
if message == "Score updated":
instead of
if message("Score updated"):
I am having a problem with my code here. The error that I am receiving is on the bottom.
I have to enter payroll in and calculate pay with overtime or without.
enter code here
####################### Functions ########################
def Input():
try:
name=raw_input("Enter your first and last name: ")
titlename=name.title()
except:
return Input
def Hours():
try:
wHours=raw_input("Enter the hours you worked this week: ")
except:
if wHours < 1 or wHours > 60:
print "Employees' can't work less than 1 hour or more than 60 hours."
return lstEmp
def Pay():
try:
pRate=raw_input("Enter your hourly wage: ")
except:
if pRate < 6 or pRate > 20:
print "Employees' wages can't be lower than $6.00 or greater than $20.00."
return pay
def calcHours(pr,h):
if h <= 40:
pr * h
else:
(h -40) *(pr *1.5) + pr * 40
return lstEmp
def end():
empDone=raw_input("Please type DONE when you are finished with employees' information: ")
empDone.upper() == "DONE"
#################### MAINLINE CODE
lstEmp=[]
Names=""
while True:
Names=Input()
WorkHours=Hours()
Wages=Pay()
gPay=calcHours(WorkHours, Wages)
Done=end()
if end():
break
Traceback (most recent call last):
File "J:\11-2-10.py", line 53, in
gPay=calcHours(WorkHours, Wages)
File "J:\11-2-10.py", line 29, in calcHours
pr * h
TypeError: unsupported operand type(s) for *: 'NoneType' and 'NoneType'
In Input, Hours and Pay, you assign to a variable of the same name as the functions; perhaps you mean to return these values instead?
gPay=calcHours(Hours, Pay)
You meant WorkHours, which is what you called the variable; Hours is still the function, that returned it. There are plenty of other places in the code where you've changed the variable names so they don't match any more.
Also +1 gnibbler's comment. That's really not what try does, and you should never use except without a particular Exception. The bit you might want to put in the try is a conversion to integer:
def getHours():
while True:
hours= raw_input("Enter the hours you worked this week: ")
try:
hours= int(hours)
except ValueError:
print "That's not a number, type it proper."
continue
if not 1<=hours<=60:
print "Employees must work between 1 and 60 hours."
continue
return hours