I have a piece of python code that is supposed to end if a variable is equal to the string 'x', but it doesnt, I dont understand why. Can someone explain please
counter = 0
total_price = 0
biggest_price = 0
smallest_price = 10000000000
house_type = 0
while house_type != "x":
house_type = input("What is the house type? ")
if house_type != "x":
number_of_rooms = int(input("How many rooms does the house have? "))
age = int(input("How old is the house? "))
price = int(input("What is the houses price? "))
if price > biggest_price :
biggest_house_type = house_type
biggest_rooms = number_of_rooms
biggest_age = age
biggest_price = price
if price < smallest_price :
smallest_house_type = house_type
smallest_rooms = number_of_rooms
smallest_age = age
smallest_house_price = price
total_price = total_price + price
counter = counter + 1
print(biggest_house_type, biggest_rooms, biggest_age, biggest_price)
print(smallest_house_price, smallest_rooms, smallest_age, smallest_price)
print(total_price / counter)
Can someone explain why the program doesn't end when X is pressed, and instead just gives house_type the value of 'x'
There were a number of issues. I tried to make a minimal working example.
counter = 0
total_price = 0
biggest_price = 0
smallest_price = 10000000000
house_type = ''
while house_type != "x":
house_type = raw_input("What is the house type? ")
if house_type != "x":
number_of_rooms = int(raw_input("How many rooms does the house have? "))
age = int(raw_input("How old is the house? "))
price = int(raw_input("What is the houses price? "))
if price > biggest_price :
biggest_price = price
if price < smallest_price :
smallest_price = price
total_price = total_price + price
counter = counter + 1
print(biggest_price)
print(smallest_price)
print(total_price / counter)
Output:
What is the house type? 3
How many rooms does the house have? 5
How old is the house? 30
What is the houses price? 100000
100000
100000
100000
What is the house type? 4
How many rooms does the house have? 2
How old is the house? 10
What is the houses price? 200000
200000
100000
150000
What is the house type? x
NOTE:
If you are on Python 2.x use raw_input(). If you are on Python 3.x use input()
Related
I am currently working on improving my commission program by implementing arrays into my program. However, I cannot properly display my commission results anymore. If I revert some array changes, I can display my commission fine. Where did I do wrong? I would appreciate any feedback on my code posted below. I'm a beginner and have included code that I have learned up to this point.
MAX = 10
def main():
comp_name = [""] * MAX
sales_amount = [0.0] * MAX
total_sales_amount = 0.0
commission = 0.0
bonus = 0.0
more_sales = 'Y'
select_item = 0
welcome_message()
while more_sales == 'Y':
comp_name[select_item] = get_comp_name()
sales_amount[select_item] = get_sales_amount()
total_sales_amount = total_sales_amount + (sales_amount[select_item] + sales_amount[select_item])
more_sales = more_sales_input()
select_item = select_item + 1
commission += get_commission_calc(sales_amount[select_item])
print_receipt(comp_name, sales_amount, commission, select_item)
bonus = get_bonus(commission)
commission = commission + bonus
print_totals(bonus, commission)
def print_receipt(comp_name, sales_amount, total_commission, select_item):
sub_total = 0
count = 0
print("\nCompany Name Sales Your Commission")
print("------------ ----- ---------------")
while count < select_item:
print("{0:<15}".format(comp_name[count]), "\t\t$ ", format(sales_amount[count], ".2f"), "\t$ ", format(sales_amount[count], ".2f"))
sub_total = sub_total + (sales_amount[count])
count = count + 1
print("-----------------------------------------------")
print("Collect: $", format(total_commission, ".2f"))
def get_comp_name():
comp = ""
comp = input("\nEnter Company name: ")
return comp
def more_sales_input():
more = ""
more = input("Do you have more sales to add? (y/n): ")
more = more.upper()
while more != "Y" and more!= "N":
print("Invalid entry, either y or n.")
more = input("Do you have more sales to add? (y/n): ")
more = more.upper()
return more
def get_sales_amount():
sales = 0.0
while True:
try:
sales = float(input("Please enter sales $ "))
if sales < 0:
print("Invalid, must be a positive numeric!")
else:
return sales
except:
print("Invalid, must be a positive numeric!")
def get_commission_calc(sales):
commission = 0.0
if sales >= 20000:
commission = sales * .10
elif sales >= 10000:
commission = sales * .07
else:
commission = sales * .05
return commission
def get_bonus(commission):
if commission >= 1000:
return + 500
else:
return 0
def print_totals(bonus, total_commission):
if bonus > 0:
print("\nYou earned a $500 bonus added to your pay!")
else:
print("\nYou did not yet meet requirements for a bonus!")
print("\nYour commission is", '${:,.2f}'.format(total_commission))
main()
im learning python and for my homework i wanna make a food ordering program and get the receipt of the products purchased with the prices for the total. im struggling to get the billing process as i cannot get all the products chosen by the user displayed on the receipt
import datetime
x = datetime.datetime.now()
name = input("Enter your name: ")
address = input("Enter your address: ")
contact = input("Enter your phone number: ")
print("Hello " + name)
print("*"*31 + "Welcome, these are the items on on the menu."+"*" * 32 )
print("Menu:\n"
"1.Burger:150.\n"
"2.Fried Momo:120.\n"
"3.coffee:60.\n"
"4.Pizza:180.\n"
"5.Fried Rice:150.\n"
"6.French Fries:90.\n"
"7.Steamed Dumplings:150.\n"
"8.Chicken drumsticks:120.\n"
"9.Chicken Pakoras:120.\n"
"10.American Chop Suey:200.\n")
prices = {"1.Burger":150,
"2.Fried Momo":120,
"3.coffee":60,
"4.Pizza":180,
"5.Fried Rice":150,
"6.French Fries":90,
"7.Steamed dumplings":150,
"8.Chicken drumsticks":120,
"9.Chicken Pakoras":120,
"10.American Chop Suey":200
}
continue_order = 1
total_cost, total = 0, 0
cart = []
while continue_order != 0:
option = int(input("Which item would you like to purchase?: "))
cart.append(option)
if option >= 10:
print('we do not serve that here')
break
elif option == 1:
quantity = int(input("Enter the quantity: "))
total = quantity * 150
print("The price is: ₹" + str(total))
elif option == 2:
quantity = int(input("Enter the quantity: "))
total = quantity * 120
print("The price is: " + str(total))
elif option == 3:
quantity = int(input("Enter the quantity: "))
total = quantity * 60
print("The price is: " + str(total))
elif option == 4:
qquantity = int(input("Enter the quantity: "))
total = quantity * 180
print("The price is: " + str(total))
elif option == 5:
quantity = int(input("Enter the quantity: "))
total = quantity * 150
print("The price is: " + str(total))
elif option == 6:
quantity = int(input("Enter the quantity: "))
total = quantity * 90
print("The price is: " + str(total))
elif option == 7:
quantity = int(input("Enter the quantity: "))
total = quantity * 150
print("The price is: " + str(total))
elif option == 8:
quantity = int(input("Enter the quantity: "))
total = quantity * 120
print("The price is: " + str(total))
elif option == 9:
quantity = int(input("Enter the quantity: "))
total = quantity * 120
print("The price is: " + str(total))
elif option == 10:
quantity = int(input("Enter the quantity: "))
total = quantity * 200
print("The price is: " + str(total))
total_cost += total
continue_order = int(input("Would you like another item? enter Yes--> (1) or--> No (0):"))
print('='*30)
print('='*30)
print("Your receipt:\n")
print("Date: " + str(x))
print("Name: " + name.title())
print("Adress: " + address)
print("Contact number: " + contact)
for option in cart:
print ("Item: %s. Price: %s") % (option, prices[option])
print("Quantity: ",quantity)
print("Total Price: ", total_cost)
print('='*30)
print("Thank you for shopping here, have a great day ")
print('='*30)
but i get an error line 95, in
print ("Item: %s. Price: %s") % (option, prices[option])
KeyError: 1
any solution or better ways to improve the code would be really great
Try using F-Strings. They let you format text far more easily. Here's an example.
x = "hello!"
print(f"shr4pnel says {x}")
>>> shr4pnel says hello!
The problem in this case is that option == 1. 1 isn't a key in the dictionary so nothing is output. Hope this helps. This is because the dictionary does not have 1 as a key. To access the item the dictionary would have to be formatted like this.
prices = {1: "burger", 2: "hot dog"}
print(prices[1])
>>> burger
Is there a way to simplify the code here using function and loops?
I would like to simplify it but not sure how to.
age1 = int(input("Enter age:"))
if age1 < 12:
price1 = 10
else:
if age1 < 59:
price1 = 20
else:
price1 = 15
age2 = int(input("Enter age:"))
if age2 < 12:
price2 = 10
else:
if age2 < 59:
price2 = 20
else:
price2 = 15
age3 = int(input("Enter age:"))
if age3 < 12:
price3 = 10
else:
if age3 < 59:
price3 = 20
else:
price3 = 15
total = price1 + price2 + price3
print("The total price for the tickets is $" + str(total))
I would do this
people = int(input('Enter number of people: '))
min_age=12
max_age=59
def price(min_age, max_age):
age = int(input("Enter age:"))
if age < min_age:
price = 10
else:
if age < max_age:
price = 20
else:
price = 15
return price
prices = []
for j in range(people):
prices.append(price(min_age, max_age))
total_price = sum(prices)
print("The total price for the tickets is $" + str(total_price))
I would suggest creating a function that, given the age and returns the price. You can also create a function to get the age. It will then be easy to use in a loop or a comprehension to add up the prices:
def getAge(): return int(input("Enter age:"))
def getPrice(age): return 10 if age <12 else 20 if age < 59 else 15
total = sum(getPrice(getAge()) for _ in range(3))
print(f"The total price for the tickets is ${total}")
Enter age:65
Enter age:25
Enter age:9
The total price for the tickets is $45
This will separate computations from user interactions and it will be easy to add validations to the input (such as a permissible age range or to check if the value is numeric)
try using the while statement, in this context;
while true:
# Code goes here
while true: means that when the program is running, execute this code repeatedly until it stops.
price = input("How much: ")
country = input("which country are you from :")
tax = 0
total = int(price) + (int(price)*(tax/100))
if country =="Canada" :
province = input("Which province? :")
if province == "Alberta" :
tax = 5
print(total)
elif province == "Ontario" :
tax = 13
print(total)
else :
tax = 11
print(total)
else :
tax = 0
print(total)
This code does not update the tax and doesn't calculate total afterward accordingly. Can anyone suggest any solution?
The issue is you are calculating total before changing tax to be the correct value. You can fix this by moving the calculation so that it happens after tax has been set.
price = input("How much: ")
country = input("which country are you from :")
tax = 0
if country == "Canada":
province = input("Which province? :")
if province == "Alberta":
tax = 5
elif province == "Ontario":
tax = 13
else:
tax = 11
else:
tax = 0
total = int(price) + (int(price)*(tax/100))
print(total)
Well, the problem is, you pre-calculated the total before the if statement with tax = 0. That would always return the same value.
Try calculating the total everytime you update the tax.
Something like this:
tax = 5
total = int(price) + (int(price)*(tax/100))
print(total)
Have a look at this simple example. I think it can help you "rethink" your data-sctructure. Good luck!
taxes = {
'Canada': {
'Alberta': 5,
'Ontario': 13,
'default': 11
}
}
def taxfunc(price, tax):
return price + price*tax/100
price = int(input("How much: "))
country = input("which country are you from :").title()
if country in taxes:
province = input("Which province? :").title()
tax = taxfunc(price, taxes[country].get(province, taxes[country]['default']))
print('Your tax is: {}'.format(tax))
else:
print('no data')
Try this: After getting the tax, then calculate the total. Problem of your code is you calculate the total before assigning values to tax. Always your total is for tax = 0 only. But moving the total calculation to the bottom will fix the issue.
price = input("How much: ")
country = input("which country are you from :")
tax = 0
if country =="Canada" :
province = input("Which province? :")
if province == "Alberta" :
tax = 5
elif province == "Ontario" :
tax = 13
else :
tax = 11
else :
tax = 0
total = int(price) + (int(price)*(tax/100))
print(total)
I am a beginner in python and It always says I have a bad input on lines 2,4, and 10 and when I put a < in front of the second line it approves it and when I put > for the 4th line it approves it and I tried it for the 10th line but it didn't work
start = int(input("type 1 to begin or 2 to buy items: "))
if start = 1 :
print("welcome to this game")
if start = 2 :
ranged = 0
melee = 1
fighting = 0
money = 100
shop = int(input("1 for sword or two for arrows: "))
if shop = 1 :
money = money-100
fighting = fighting+1
melee = melee+1
start = int(input("type 1 to begin or 2 to buy items: "))
if shop = 2 :
money = money-100
fighting = fighting+0.5
ranged = ranged+1
start = int(input("type 1 to begin or 2 to buy items: "))
else:
print("invalid selection")`
Umm so I kind of changed it a little but it still has errors on line 12 where it says it cannot recognize x but I have already defined it earlier
start = int(input('type 1 to begin or 2 to buy items: '))
if start == 1 :
print("welcome to this game")
print("you will face off with a evil monster named york for the first adventure")
print("I am york and I will eat you")
if start == 2 :
x = float(input('type 1 or 2 to buy items: '))
ranged = 0
melee = 1
fighting = 0
money = 100
if x == 1:
money = money-100
print(money)
fighting = fighting+1
melee = melee+1
start = int(input('type 1 to begin or 2 to buy items: '))
if start == 1 :
print("welcome to this game")
else:
print("visit the shop another time")
if x == 2 :
money = money-100
fighting = fighting+0.5
ranged = ranged+1
start = int(input("type 1 to begin or 2 to buy items: "))
The "=" sign in Python is for assigning a value to a variable.
Example:
>>> x = 3
>>> x+1
4
For comparison use "==".
Example:
>>> if x == 3:
... print "That is true"
...
That is true
>>> if x == 2:
... print "that is true"
...
>>>