I started learning python few days ago and im looking to create a simple program that creates conclusion text that shows what have i bought and how much have i paid depended on my inputs. So far i have created the program and technically it works well. But im having a problem with specifying the parts in text that might depend on my input.
Code:
apples = input("How many apples did you buy?: ")
bananas = input("How many bananas did you buy?: ")
dollars = input("How much did you pay: ")
print("")
print("You bought " +apples+ " apples and " +bananas+ " bananas. You paid " +dollars +" dollars.")
print("")
print("")
input("Press ENTER to exit")
input()
So the problem begins when input ends with 1. For example 21, 31 and so on, except 11 as the conclusion text will say "You bought 41 apples and 21 bananas...". Is it even possible to make "apple/s", "banana/s", "dollar/s" as variables that depend on input variables?
Where do i start with creating variable that depends on input variable?
How do i define the criteria for "banana" or "bananas" by the ending of number? And also exclude 11 from criteria as that would be also "bananas" but ends with 1.
It seems like this could be an easy task but i still can't get my head around this as i only recently started learning python. I tried creating IF and Dictionary for variables but failed.
You would want to have an if statement that checks whether the specified input falls above or equal to 1. This is simple to do and requires an if statement.
A simple way of doing this would be:
if apples == '1':
strApples = str(apples, 'apple')
else:
strApples = str(apples, 'apples')
...and so forth for all the other fruits.
You would then print your conclusion with:
print("You bought", strApples, "and", strBananas + ". You paid " +dollars +" dollars.")
Not the best way of displaying this though.
I would go for a line by line conclusion:
print("You bought: ")
if apples == '1':
print("1 apple")
else:
print(apples, "apples")
if bananas == '1':
print("1 banana")
else:
print(bananas, "bananas")
print("You paid", dollars, "dollars")
EDIT:
I think I now understand that you want every number ending in '1', that is not '11' to be displayed as singular.
This can be done using the following:
apples = input("How many apples did you buy?: ")
bananas = input("How many bananas did you buy?: ")
dollars = input("How much did you pay: ")
print("You bought: ")
if int(apples[-1]) == 1 and int(apples) != 11:
print(apples, "apple")
else:
print(apples, "apples")
if int(bananas[-1]) == 1 and int(bananas) != 11:
print(bananas, "banana")
else:
print(bananas, "bananas")
print("You paid", dollars, "dollars")
Looks like you might be interested by functions.
For example:
def pluralize(x):
for i in ["a", "e", "i", "o", "u"]:
# Is vowel
if x.endswith(i):
return x+"s"
# Is consonant
return x
print(pluralize("Hello World"))
Note: you may want to improve this function to handle things like ending with y, ending with x or s and so on.
EDIT:
https://pastebin.com/m2xrUWx9
Related
I'm a freshman, and I want to make a bill that write out what I bought, quantity and how much total cash it cost.
customer = str(input("Customer's name: "))
print ("Welcome to our store")
print ("This is our products")
print ("orange 0.5$)
print ("Apple 1$)
print ("Grape 0.5$)
print ("Banana 0.5$)
chooseproducts= int(input("What do you want to buy: "))
For output example. Can you guys help me please.
BILL
Orange 5 2.5$
Apple 3 3$
Grape 2 1$
Total: 10 6.5$
First, your str(input(customer's name: )) code needs to be changed. input() calls need a string as the question, and also the apostrophe has Python think that it is the start of a string.
Also, when you are printing the costs, you need another closing quotation mark. When you are asking the user about what they want to buy, I suppose you want them to input the name of the fruit. Since you have the int() in the front, Python cannot turn a string like "orange" or "grape" into an integer. When people want to buy multiple things, however, they might only put one thing in.
I suppose that this isn't all your code, and you have the part where you calculate the cost. If I were to write this code, I would write it like the following:
customer = str(input("Customer's Name:"))
print ("Welcome to our store")
print ("This is our products")
print ("Orange 0.5$")
print ("Apple 1$")
print ("Grape 0.5$")
print ("Banana 0.5$")
prices = {"orange":0.5,"apple":1,"grape":0.5,"banana":0.5}# I added this so we can access the prices later on
#chooseproducts= int(input("What do you want to buy: "))
# The code below this is what I added to calculate the cost.
productnum = input("How many things do you want to buy: ") # This is for finding the number of different fruits the buyer wants
while not productnum.isdigit():
productnum = input("How many different products do you want to buy: ")
productnum = int(productnum)
totalprice = 0
totalfruit = 0
print(' BILL')
for i in range(productnum):
chosenproduct = input("What do you want to buy: ").lower()
while not chosenproduct in ['orange','apple','banana','grape']:
chosenproduct = input("What do you want to buy: ").lower()
fruitnum = input("How many of that do you want to buy: ")
while not fruitnum.isdigit():
fruitnum = input("How many of that do you want to buy: ")
fruitnum = int(fruitnum)
totalfruit += fruitnum
price = fruitnum * prices[chosenproduct]
totalprice += price
startspaces = ' ' * (11 - len(chosenproduct))
endspaces = ' ' * (5 - len(str(fruitnum)))
print(chosenproduct.capitalize() + startspaces + str(fruitnum) + endspaces + str(price) + '$')
print('Total: ' + str(totalfruit) + ' ' * (5 - len(str(totalprice))) + str(totalprice) + '$')
Please make sure you understand the code before copying it, thanks!
This question already has answers here:
How to test multiple variables for equality against a single value?
(31 answers)
Closed 1 year ago.
I am making a text adventure game, but it keeps running the 1st variation in the code, even though I specified both scenarios:
print("By Rishi Suresh 2021")
print('')
print('')
print("A S h o r t R i d e")
print('')
print('')
print(" P L A Y ( P )")
print('')
print('')
if input()=="p":
print('')
print('')
print("Your journey begins on a bleak day. It's cloudy, and the windows of your apartment amplify the pitter patter of the soft rain outside. Your clothes are strewn about. You hear the landline ringing. You also see a diary.")
print('')
print('')
if input("What do you do? Do you pick up the diary (A) or answer the landline (B)? ")=="b"or "B":
print("")
print("")
print("You pick up the landline, and hear a voice on the other end. It is scratchy, and tells you to come to the London Underground. You pick up your clothes, a empty whiskey bottle and some glasses, and dress. You head outside. ")
elif input() == "A" or "a":
print("The diary reads:")
print('')
print('')
print("Dear Diary,")
print("Tommorow's the day. We have all the trucks ready, all the Tommy's, all the big men. This stop and shop will be the sucess of the century.")
print("The landline rings again. You pick up the landline, and hear a voice on the other end. It is scratchy, and tells you to come to the London Underground. You pick up your clothes, a empty whiskey bottle and some glasses, and dress. You head outside.")
This clause:
if input("What do you do? Do you pick up the diary (A) or answer the landline (B)? ")=="b"or "B":
will always pass, because "B" (and "A" or any non-empty string, for that matter) is a truthy value:
if "B":
print("Hey!")
if "A":
print("I pass, too!")
if "A really, really, really long string that goes on...":
print("So do I!")
if "":
print("I'll never print.")
This means if <anything> or "B": will always pass (provided evaluation of <anything> doesn't throw an exception or change control flow), because the second part of the or is satisfied. The == operator is binding to input (i.e. input(...) == "b" or "B" is (input(...) == "b") or "B"); you can't express "the result is a member of some set" in this way (i.e. x == 1 or 2 is (x == 1) or 2, not x in (1, 2)).
Assign the result of your input calls to some variable result, and then test result in ("b", "B") or result.lower() == "b" (ditto for the second case).
by asking for another input in the elif you are asking for another user input discarding the user's previous input,plus or "a" would cause the statment to always be true since you are not checking if the input is equal to "a", this would be better:
print("")
print('')
print('')
print("")
print('')
print('')
print(" ")
print('')
print('')
if input()=="p":
print('')
print('')
print("")
print('')
print('')
option=input(" a or b")
if option =="b"or option =="B":
print("")
print("")
print("")
elif option == "A" or option == "a":
print("The diary reads:")
print('')
print('')
print("Dear Diary,")
print("")
print("")
Basically, I am trying to make this menu for a project and I need to make it loop. What I am having difficulty on is trying to take input into a list in a loop. I want the program to add up the totals of every order that is taken and put them into a list. I then want the program to add up this list and give me the final total cost of the order. How would I make it so that I can use a list in a loop without it deleting what was previously inputted in there. For example, if I order a chicken sandwhich the first time in the loop and then order only that again the second time and then quit the loop, instead of showing me a price of 10.50 I only get a total price of 5.25. Thanks for the help!
choice = (input("How many people are you ordering for? To quit the program simply type quit."))
while choice != 'quit':
if Beverage == "yes" and Fries == "yes":
Total_Cost = CostSandwich + CostBeverage + CostFries - 1 + KetchupNumber
elif Beverage == "no" and Fries == "no":
Total_Cost = CostSandwich + CostBeverage + CostFries + KetchupNumber
elif Beverage == "yes" and Fries == "no":
Total_Cost = CostSandwich + CostBeverage + CostFries + KetchupNumber
elif Beverage == "no" and Fries == "yes":
Total_Cost = CostSandwich + CostBeverage + CostFries + KetchupNumber
print("Your total cost is", Total_Cost)
print("You ordered a", SandwichType, "Sandwich,", BeverageType, "Beverage,", FriesType, "Fries,", "and", KetchupType, "Ketchup Packets." )
finalcost = [0]
finalcost.append(Total_Cost)
totaloffinalcost = sum(finalcost)
choice = (input("If you would like to quit then type quit or type anything to continue"))
print("The final cost is", totaloffinalcost)
Apart from the fact that a lot can be done to improve and make this much efficient, the answer to your query:
OP: For example, if I order a chicken sandwhich the first time in the loop and then order only that again the second time and then quit the loop, instead of showing me a price of 10.50 I only get a total price of 5.25.
That happens because on each iteration inside the while loop just before taking the sum, you're initialing a list:
finalcost = [0]
Take this outside the while loop:
finalcost = [0]
while choice != 'quit':
# rest of the code
did i write correct code
no1 = 1
no2 = 6
enter code here
dice = input("enter number: "):
no1 = int(input("enter number one: "))
no2 = int(input("enter number two: "))
print("you have enter "+str(no1))
print("you have enter "+str(no2))
if dice == "5":
print("you want to roll again")
elif dice == "6":
print("roll dice automatically")
check that you have not incorrectly formatted all of your question as code
There are many ways to write a dice rolling program. However, the simplest way would use a built-in library called random. Below I have fixed and cleaned the code:
import random # The libary used from generating random numbers
def dice_roll(): # function usedto reset the game
input("Press enter to roll the dice ")
print("The dice rolled: ", random.randint(0,6))
UserInputNew = input ("Would you like to roll again? ")
if UserInputNew == "5":
print("\n") # displays a blank line
dice_roll()
else:
print ("Thanks for playing!")
dice_roll() # loads the game
Above would do what you want. From your example above, you have loads of inputs which doesn't make sense from something like a dice roll. If you need help understanding certain bits of the code then I'll be more than happy to help.
help on this one
Alice, Bob and Carol have agreed to pool their Halloween candy and split it evenly among themselves. For the sake of their friendship, any candies left over will be smashed. For example, if they collectively bring home 91 candies, they'll take 30 each and smash 1.
Write an arithmetic expression below to calculate how many candies they must smash for a given haul.
I have been banging my head against the wall for a few hours now trying to figure this out so any help is greatly appreciated. What I'm trying to do is loop the program upon a Y input for a Y/N question, specifically when Y is inputed I want it to react the way it does as shown in the sample output.
Here is my code:
import random
def main():
name = eval(input("Hello user, please enter your name: "))
print("Hello", name ,"This program runs a coin toss simulation")
yn = input("Would you like to run the coin toss simulation?(Y/N):")
if yn == Y:
elif yn == N:
print("Ok have a nice day!")
heads = 0
tails = 0
count = tails + heads
count = int(input("Enter the amount of times you would like the coin to flip: "))
if count <= 0:
print("Silly rabbit, that won't work")
while tails + heads < count:
coin = random.randint(1, 2)
if coin ==1:
heads = heads + 1
elif coin == 2:
tails = tails + 1
print("you flipped", count , "time(s)")
print("you flipped heads", heads , "time(s)")
print("you flipped tails", tails , "time(s)")
main()
Here is the sample output that I'm looking for:
Hello user, please enter your name: Joe
Hello Joe this program runs a coin toss simulation
Would you like to run the coin toss simulation?(Y/N):Y
Enter the amount of times you would like the coin to flip:50
you flipped 50 times
you flipped heads 26 times
you flipped tails 24 times
Would you like to run another coin toss simulation?(Y/N):Y
Enter the amount of times you would like the coin to flip:100
you flipped 100 times
you flipped heads 55 times
you flipped tails 45 times
Would you like to run another coin toss simulation?(Y/N):N
Ok have a nice day!
I think you should say on line 6 if yn == 'Y' and not if yn == Y. You treat Y as a variable while it is actually a string from the input.
To run your coin toss simulation multiple times you can put it inside a while loop.
Your if yn == Y: test won't work because you haven't defined the variable Y, so when Python tries to execute that line you get a NameError. What you actually should be doing there is to test the value of yn against the string 'Y'.
I've made a couple of other minor adjustments to your code. I got rid of that potentially dangerous eval function call, you don't need it. I've also made a loop that asks for the desired flip count; we break out ofthe loop when count is a positive number.
import random
def main():
name = input("Hello user, please enter your name: ")
print("Hello", name , "This program runs a coin toss simulation")
yn = input("Would you like to run the coin toss simulation?(Y/N): ")
if yn != 'Y':
print("Ok have a nice day!")
return
while True:
heads = tails = 0
while True:
count = int(input("Enter the amount of times you would like the coin to flip: "))
if count <= 0:
print("Silly rabbit, that won't work")
else:
break
while tails + heads < count:
coin = random.randint(1, 2)
if coin ==1:
heads = heads + 1
else:
tails = tails + 1
print("you flipped", count , "time(s)")
print("you flipped heads", heads , "time(s)")
print("you flipped tails", tails , "time(s)")
yn = input("Would you like to run another coin toss simulation?(Y/N): ")
if yn != 'Y':
print("Ok have a nice day!")
return
main()
This code is for Python 3. On Python 2 you should use raw_input in place of input, and you should also put
from future import print_function
at the top of the script so you get the Python 3 print function instead of the old Python 2 print _statement.
There are several improvements that can be made to this code. In particular, it should handle a non-integer being supplied for the count. This version will just crash if it gets bad input. To learn how to fix that, please see Asking the user for input until they give a valid response.