I'm learning how to program in Python and got stuck on this simple exercise. I saved the code below to a file, test.py and ran it from my OSX command line using "python test.py" and keep getting an error message that I can't understand. My guess that the error is some fairly obvious thing that was overlooked :P
The error message follows the code:
def hotel_cost(nights):
return 140 * nights
def plane_ride_cost(city):
if city == "Charlotte":
return 183
elif city == "Tampa":
return 220
elif city == "Pittsburgh":
return 222
elif city == "Los Angeles":
return 475
def rental_car_cost(days):
total = 40 * days
if days >= 7:
total = total - 50
elif days >= 3:
total = total - 20
return total
def trip_cost(city, days, spending_money):
return rental_car_cost(days) + hotel_cost(days) + plane_ride_cost(city) +
spending_money
thecity = raw_input("What city will you visit? ")
thedays = raw_input("How many days will you be traveling? ")
thespending_money = raw_input("How much spending money will you have? ")
trip_cost(thecity, thedays, thespending_money)
The console error message:
$ python test.py
What city will you visit? Los Angeles
How many days will you be traveling? 5
How much spending money will you have? 600
Traceback (most recent call last):
File "test.py", line 29, in <module>
trip_cost(thecity, thedays, thespending_money)
File "test.py", line 23, in trip_cost
return rental_car_cost(days) + hotel_cost(days) + plane_ride_cost(city) + spending_money
File "test.py", line 17, in rental_car_cost
total = total - 50
TypeError: unsupported operand type(s) for -: 'str' and 'int'
Change thedays = raw_input("How many days will you be traveling? ") into thedays = input("How many days will you be traveling? "), and replace all other raw_input with input whenever you need a numerical value.
Afrer thecity = raw_input("What city will you visit? ") "thecity" is a string. Make integer from string with int:
thecity = int(raw_input("What city will you visit? "))
Similarly for other inputs.
thedays = raw_input("How many days will you be traveling? ")
raw_input returns a string. So, when you enter 5, you get the string '5' rather than the integer 5. Python does not automatically convert these for you when you try to add them, since that can lead to bigger surprises in some cases. Instead, it wants you to do the conversion explicitly, so that your code is always unambiguous in the case of any input (eg, "parse the string 'abc' as a base 10 integer" is always an error; trying to do "abc" + 5 via implicit conversion might decide to turn 5 into the string '5' and do string concatenation to give "abc5").
The way to do this is with the builtin int, which takes a string and gives you back an integer parsed from it:
thedays = int(raw_input("How many days will you be traveling? "))
Related
I'm a beginner and this is my first receiving this message "IndexError: list index out of range," can someone please tell me how to fix it? and what exactly did I do wrong? Also if someone can run it and make sure it does what it's supposed to because I need another person other than me to run it(Professor's instruction)
This is the output it gave me -
Traceback (most recent call last):
File "", line 74, in
File "", line 24, in user
IndexError: list index out of range
Here's my code:
print ("Dish No. Dish Name Price ")
print (" -------- --------- ------")
print (" 1 Gang Gai $10.00")
print (" 2 Pad Thai $8.75")
print (" 3 Pad Cashew $9.50")
print (" 4 Pad Prik $10.25")
print (" 5 Peanut Curry $9.50")
print (" 6 Curry Noodles $11.25")
def user():
array = [10,8.75,9.50,10.25,9.50,11.25]
cart = []
while True:
x = int(input("Enter the item number you want (1-6):"))
check = checker(x)
if check == "wrong number":
print("Enter a valid number")
pass
cart.append(array[x-1])
xx=input("Would you like to order another item( Yes or No)?: ")
if xx.lower() == "no":
break
checkout(cart)
# if xx=='No'.lower():
# return array[x-1]
# else:
# return array[x-1]+user(array)
def seniorCitizen():
print("Are you 65 years or older(Yes or No)? ")
xsenior = input()
if xsenior.lower() == "yes":
senior = True
else:
senior = False
return senior
def checker(num):
if num > 6 or num < 1:
return "wrong number"
def checkout(cart):
senior = seniorCitizen()
titems = 0
for item in cart:
titems = titems + item
print(" Bill Information ")
print("-------------------------------")
print("Total of all items: $",titems)
if senior == True:
boomercount = titems * 0.1
boomercount = round(boomercount, 2)
print("Total senior discounts:-$", boomercount)
tax = round((titems-boomercount)*0.06, 2)
print("Taxes: $",tax)
print(" Bill: $", round(((titems-boomercount)+tax), 2))
else:
tax = round(titems*0.06, 2)
print("Taxes: $",tax)
print(" Bill: $", round((titems+tax), 2))
user()
while True:
x = int(input("Enter the item number you want (1-6):"))
check = checker(x)
if check == "wrong number":
print("Enter a valid number")
pass
cart.append(array[x-1])
The problem is the pass statement. It does not restart the loop -- it does nothing at all. So if the user enters a wrong number, it prints an error message but then it keeps going and tries to access array[x-1] which is out of range.
Use continue which will start the loop over, instead of pass.
I'm resolving a basic problem consisting of make a list of products, the user choose the product and the amount of the product and the total price is printed. I get a keyerror in the line 22.
def main():
print("Choose a product: ")
print("")
print("Products: ")
print("")
print("Samsung Galaxy S10+.............1")
print("Samsung Galaxy S10..............2")
print("OnePlus 7 Pro...................3")
print("OnePlus 7.......................4")
print("OnePlus 6t......................5")
print("Huawei P30 Pro..................6")
print("Huawei Mate 20 Pro..............7")
print("Google Pixel 3XL................8")
print("Gooogle Pixel 3A XL.............9")
print("Oppo Reno 10x Zooom............10")
print("")
relation = {1:1000, 2:900, 3:700, 4:600, 5:470, 6:850, 7:970, 8:950, 9:300, 10:550}
code = input("Enter the product code: ")
print("")
print("The price is $", relation[code])
quantify = input("Enter amount: ")
print("")
totalPrice = float(relation[code] * quantify)
print("The total price is: $", totalPrice)
The error displayed is
Traceback (most recent call last):
File "main.py", line 30, in <module>
main()
File "main.py", line 22, in main
print("The price is $", relation[code])
KeyError: '5'
In this case I choose the product code "5".
When you use input it returns a string, not an integer. You can see this because the error message shows '5', not 5. The keys to your dictionary are integers, though, so the key you are providing in the statement (code) is not found.
You could instead use
print("The price is $", relation[int(code)])
A better format, at least in Python 3.6 and later, would be
print(f"The price is ${relation[int(code)]}")
for line 26, the problem is similar. Just convert to integers (or float, if there's a decimal point)
totalPrice = float(relation[int(code)] * int(quantify))
or
totalPrice = relation[int(code)] * float(quantify)
input in python receives data as a string, you need to typecast it
it is something along:
print("The price is $", relation[int(code)])
I think you should also follow the Python idiom EAFP (Easier to ask for forgiveness than permission) here when asking for user input as he could write literally everything but integers you expect:
while True:
code = input("Enter the product code: ")
try:
price = relation[int(code)]
except (ValueError, KeyError):
print("Error: Incorrect code value, try again!")
else:
break
def main():
print("Choose a product: ")
print("")
print("Products: ")
print("")
print("Samsung Galaxy S10+.............1")
print("Samsung Galaxy S10..............2")
print("OnePlus 7 Pro...................3")
print("OnePlus 7.......................4")
print("OnePlus 6t......................5")
print("Huawei P30 Pro..................6")
print("Huawei Mate 20 Pro..............7")
print("Google Pixel 3XL................8")
print("Gooogle Pixel 3A XL.............9")
print("Oppo Reno 10x Zooom............10")
print("")
relation = {1:1000, 2:900, 3:700, 4:600, 5:470, 6:850, 7:970, 8:950, 9:300, 10:550}
code = input("Enter the product code: ")
print("")
print("The price is $", relation[code])
quantify = input("Enter amount: ")
print("")
totalPrice = float(relation[int(code)] * quantify)
print("The total price is: $", totalPrice)
you need to take the input as integer because the input() take the default as a string so you can type it like quantify = int(input("Enter amount: "))
or another method is to use int() in the place where the calculations are like
totalPrice = float(relation[int(code)] * int(quantify))
In my program I need to make simple math calc, but my variables are defind at str and i need to make it int for the calc and sum .
ex:
When age=40, in return I got 404040404040 (6 times the num 40)
is read the res like "str" and I need "int".
def check_age(age):
age = int(age)
return 30 * 6 if age >= 30 else 0
def just_married():
sum_married = 0
woman_age = int(input("Please enter the wife age [we know that is not ok ask woman about she's age] : ").strip())
sum_married = sum_married + check_age(woman_age)
husband = int(input("Please enter the husband age : ").strip())
sum_married = sum_married + check_age(husband)
return int(sum_married)
def children_age(number_of_children):
sum_children = number_of_children*50
return int(sum_children)
def work_hard():
print("for WIFE - Are you working part-time (0.5) or full-time (1)? : ")
wife_work = input()
print("for HUSBAND = Are you working part-time (0.5) or full-time (1)? : ")
husband_work = input()
sum_work = (wife_work+husband_work)*75
return int(sum_work)
def main():
sum_func = 0
print("The following is a program aimed at examining eligibility conditions "
"for participation in the tender Housing for the occupant.")
sum_func += just_married()
print("How many children over the age of 18 do you have? : ")
children = input()
sum_func += children_age(children)
sum_func += work_hard()
program_number = 599
if sum_func > program_number:
print("you got : " + str(sum_func) + " points ")
else:
print("sorry, but you need " + str(program_number-sum_func) + " point to join the program. try next time.")
main()
edit:
i edit the code, with the new change at func"check_age", and update the full code.
this is the input :
The following is a program aimed at examining eligibility conditions for participation in the tender Housing for the occupant.
Please enter the wife age [we know that is not ok ask woman about she's age] : 40
Please enter the husband age : 50
How many children over the age of 18 do you have? :
4
for WIFE - Are you working part-time (0.5) or full-time (1)? :
1
for HUSBAND = Are you working part-time (0.5) or full-time (1)? :
1
you got : 111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111155555555555555555555555555555555555555555555555915 points
Process finished with exit code 0
In your function check_age:
def check_age(age):
age = int(age)
return 30 * 6 if age >= 30 else 0
Also, consider changing these lines:
print("Please enter the wife age [we know that is not ok ask woman about she's age] : ")
woman_age = input(int)
To this:
woman_age = int(input("Please enter the wife age [we know that is not ok ask woman about she's age] : ").strip())
Explanation:
input takes a string, prints it and wait for user input.
str.strip removes trailing spaces
int convert a variable to an integer
Once you've sanitized your inputs, you can remove the explicit conversion to int in check_age:
def check_age(age):
return 30 * 6 if age >= 30 else 0
[EDIT] A few more suggestion:
create a function sanitize_input that takes a text, ask for input
ad returns an integer. Then use it anywhere to replace print...input
create logic blocks that make sense: For example, the main function contains all the texts that print out to the screen and store all inputs for later. Then, only process the variables in one function like check_eligibility or something where you do all the calculations. If you do that, you code will be more understandable and less error prone, for you and for the people who try to help you
The string -> number conversions have to be done before you attempt any calculations, it is too late at the time of return, as the strange things have happened already. Remember/learn that Python can add strings (which is common to many languages, "1"+"1" is "11" in various other languages too), and on top of that, it can also multiply them with integer numbers, "1"*5 is "11111".
If you assume correct input from the user, the simplest thing is to do the conversion in the input lines, which already happens in just_married, but not in the other places.
And of course remember that when you expect an input like 0.5, those should be converted to float.
def check_age(age):
#age = int(age) - removed this one, should happen at input
return 30 * 6 if age >= 30 else 0
def just_married():
sum_married = 0
woman_age = int(input("Please enter the wife age [we know that is not ok ask woman about she's age] : ").strip())
sum_married = sum_married + check_age(woman_age)
husband = int(input("Please enter the husband age : ").strip())
sum_married = sum_married + check_age(husband)
return sum_married # removed int(), it is already an integer
def children_age(number_of_children):
sum_children = number_of_children*50
return sum_children # removed int(), it was too late here
# and it should happen at input
def work_hard():
print("for WIFE - Are you working part-time (0.5) or full-time (1)? : ")
wife_work = float(input()) # added float()
print("for HUSBAND = Are you working part-time (0.5) or full-time (1)? : ")
husband_work = float(input()) # added float()
sum_work = (wife_work+husband_work)*75
return int(sum_work) # int() may stay, depending on what should happen
# with fractions - they are just thrown away now
def main():
sum_func = 0
print("The following is a program aimed at examining eligibility conditions "
"for participation in the tender Housing for the occupant.")
sum_func += just_married()
print("How many children over the age of 18 do you have? : ")
children = int(input()) # added int()
sum_func += children_age(children)
sum_func += work_hard()
program_number = 599
if sum_func > program_number:
print("you got : " + str(sum_func) + " points ")
else:
print("sorry, but you need " + str(program_number-sum_func) + " point to join the program. try next time.")
main()
As shown, I have written this code and have assigned values for CASH and TOTAL. What I can not understand is why I get.....
"Traceback (most recent call last):
File "C:\Python27\Checkout Counter2.py", line 29, in
change = cash - total
TypeError: unsupported operand type(s) for -: 'str' and 'str'"
I've tried multiple ways to make this work, and I dont see any difference between that and when it finds the total.
print "Welcome to the checkout counter! How many items are you purchasing today?"
#NOI is number of items
NOI = int(raw_input())
productlist = []
pricelist=[]
for counter in range(NOI):
print"Please enter the name of product", counter+1
productlist.append(raw_input())
print"And how much does", productlist[len(productlist)-1], "cost?"
pricelist.append(float(raw_input()))
if pricelist[len(pricelist)-1] < 0:
pricelist.pop()
productlist.pop()
len(productlist)-1
len(pricelist)-1
print "Your order was:"
subtotal=0.00
for counter in range(NOI):
print productlist[counter],
print "$%0.2f" % pricelist[counter]
subtotal += pricelist[counter]
total = "$%0.2f" % float(subtotal + (subtotal * .09))
print "Your subtotal comes to", "$" + str(subtotal) + ".", " With 9% sales tax, your total is " + str(total) + "."
print "Please enter cash amount:"
cash = raw_input()
while True:
change = cash - total
if cash < total:
print "You need to give more money to buy these items. Please try again."
else:
print "I owe you back", "$" + float(change)
"raw_input" will always return a string (even if you enter 3 or 3.5)
Therefore you have to:
cash = float(cash)
total = float(total)
Edit: Also, when you do:
total = "$%0.2f" % float(subtotal + (subtotal * .09))
total will also be a string, that is why you also have to convert it to float.
Hope it helps.
I am trying to get the expected value, but I seem to be having trouble. I turned the input values to integers and I think that is where the error is coming from. I know the int cannot convert an empty string to the integer, but when testing this I had a value.
Error:
TypeError: 'int' object is not subscriptable
What can I do to fix this problem?
def print_menu():
print('1. Add a Stock')
print('2. Recommend Sale')
print('3. Quit')
print()
expected_value = {}
menu_choice = 0
print_menu()
while menu_choice != 3:
menu_choice = int(input("Type in a number (1-3): "))
if menu_choice == 1:
print("Add Name, Prices, Risk, Shares")
name = input("Name: ")
price = input("Buyers Price: ")
Cprice = input("Current Price: ")
srisk = input("Risk: ")
sshares = input("Shares: ")
Expected_Sale_value = ((int(Cprice) - int(price)) - int(srisk) * int(Cprice)) * int(sshares)
expected_value[name] = Expected_Sale_value
elif menu_choice == 2:
print("Expected Sale values")
for x in expected_value.keys():
print("Stock: ", x, "\tExpected value:", Expected_Sale_value[x])
print()
elif menu_choice != 3:
print_menu()
I am new to python, and I know python has its tricks! Saying that I ask if there are any tips or you see something I can improve on please give me insight.
EXAMPLE(IDLE):
Add a Stock
Recommend Sale
Quit
Type in a number (1-3): 1
Add Name, Prices, Risk, Shares
Name: Google
Buyers Price: 21
Current Price: 20
Risk: 1
Shares: 2
Type in a number (1-3): 2
Expected Sale values
Traceback (most recent call last):
File "", line 25, in
print("Stock: ", x, "\tExpected value:", Expected_Sale_value[x])
TypeError: 'int' object is not subscriptable
You have an error where you're using the wrong variable name. Here are the relevant lines:
for x in expected_value.keys():
print("Stock: ", x, "\tExpected value:", Expected_Sale_value[x])
In the print statement you are indexing into the variable Expected_Sale_value rather than expected_value. Expected_Sale_value is an integer, rather than a dictionary, so you get an exception.
A slightly more "Pythonic" way of doing the loop would be:
for key, value in expected_value.items():
print("Stock: ", key, "\tExpected value:", value)
for x in expected_value.key():
should be
for x in expected_value.keys():
also use raw_input