I'm kinda stuck on something. Well, alot of things but one step at a time right. I'm not sure how to get the program to add the choices that the user input together. The assignment asks me to make a vending machine that gets a users input, return the total to them when they input 0 to quit, then it will ask them to enter the money to pay, if it is a valid amount, it will dispense change, if not, it will ask for more money. Right now though, I'm stuck on it returning the user choices and adding the total together. I will paste my code below. thanks
def main():
userchoice = ()
while userchoice != 0:
# First, the vending machine will display a message on its "screen"
print("Welcome to the Vending Machine!")
# Now, the vending machine will display the available items
Options()
# Now, the first input will ask the user to enter their choice
userchoice = float(input("Please enter the number corresponding to your preferred item or 0 to quit: "))
# Now, the program will print the choice and re-run it until the user selects 0
choices = []
choices.append(userchoice)
if userchoice == 1:
print("You selected one can of Dr.Pepper for $1.50")
elif userchoice == 2:
print("You selected one can of Mtn.Dew for $1.50")
elif userchoice == 3:
print("You selected one bottle of Water for $1.00")
elif userchoice == 4:
print("You selected one bag of Doritos for $1.75")
elif userchoice == 5:
print("You selected one Snickers bar for $1.50")
elif userchoice == 6:
print("You selected one pack of Gum for $0.50")
elif userchoice == 0:
print(choices)
else:
print("Invalid Choice, Please Try Again")
def Options():
print("\t1. Dr.Pepper - $1.50\n"
"\t2. Mtn.Dew - $1.50\n"
"\t3. Water - $1.00\n"
"\t4. Doritos - $1.75\n"
"\t5. Snickers - $1.50\n"
"\t6. Gum - $0.50")
def Sum(userchoice):
return userchoice + userchoice
main()
I have discovered one problem which is that when you declare choices you declare it inside the loop, meaning it becomes [] each time the user picks something.
Try this:
def main():
choices = []
userchoice = ()
while userchoice != 0:
# First, the vending machine will display a message on its "screen"
print("Welcome to the Vending Machine!")
# Now, the vending machine will display the available items
Options()
# Now, the first input will ask the user to enter their choice
userchoice = int(input("Please enter the number corresponding to your preferred item or 0 to quit: "))
# Now, the program will print the choice and re-run it until the user selects 0
choices.append(userchoice)
if userchoice == 1:
print("You selected one can of Dr.Pepper for $1.50")
elif userchoice == 2:
print("You selected one can of Mtn.Dew for $1.50")
elif userchoice == 3:
print("You selected one bottle of Water for $1.00")
elif userchoice == 4:
print("You selected one bag of Doritos for $1.75")
elif userchoice == 5:
print("You selected one Snickers bar for $1.50")
elif userchoice == 6:
print("You selected one pack of Gum for $0.50")
elif userchoice == 0:
print(choices)
else:
print("Invalid Choice, Please Try Again")
def Options():
print("\t1. Dr.Pepper - $1.50\n"
"\t2. Mtn.Dew - $1.50\n"
"\t3. Water - $1.00\n"
"\t4. Doritos - $1.75\n"
"\t5. Snickers - $1.50\n"
"\t6. Gum - $0.50")
def Sum(userchoice):
return userchoice + userchoice
main()
This means that the choices variable now has something useful in it.
Here is a more refined approach, it always helps to see different design concepts:
options = {
'1': {'title':'Dr.Pepper','price':1.50},
'2': {'title':'Mtn.Dew','price':1.50},
'3': {'title':'Water','price':1.00},
'4': {'title':'Doritos','price':1.75},
'5': {'title':'Snickers','price':1.50},
'6': {'title':'Gum','price':0.50}
}
def get_number(question):
value = input(question)
while 1:
try:
value = int(value)
break
except:
value = input(f'(must be a number) {question}')
return value
def main():
choices = []
amount = 0
while 1:
# First, the vending machine will display a message on its "screen"
print("Welcome to the Vending Machine!")
# Now, the vending machine will display the available items
for k, v in options.items():
print(f"\t{k}. {v['title']} - ${v['price']:.2f}")
# Now, the first input will ask the user to enter their choice
userchoice = get_number('Please enter the number corresponding to your preferred item or 0 to quit:')
if userchoice == 0:
break
# Now, the program will print the choice and re-run it until the user selects 0
choice = options.get(str(userchoice), None)
if choice:
choices.append(choice['title'])
amount += choice['price']
print(f"You selected one {choice['title']} for ${choice['price']:.2f}")
else:
print('Invalid Choice, Please Try Again')
print('Your Cart Contains:')
for each in sorted(choices):
print(each)
print(f'Total Amount: {amount}')
return choices, amount
choices, amount = main()
Related
I am trying to create a IPL/Fanstasy cricket simulators in which you create your team and play. You auction the players. In the auction function, I have added a turn feature, which means if the turn variable is even, then its your turn, if its odd, then its other bidders turn.
def auction(money, turn, choice):
if turn % 2 == 0:
while True:
print("It is your turn to choose a player.")
while True:
selected_player = str(
input("Enter the name of the player you wish to choose(leave empty to skip):"))
if selected_player in players:
break
elif selected_player == "":
print("Turn Skipped")
else:
print("That player is not in your players")
selected_player_bid = int(input("Enter the amount of money for which you wish to buy the player(leave "
"empty to skip):"))
if selected_player_bid > money:
print("You dont have enough money to buy the player.")
else:
your_players.append(selected_player)
print("Player bought")
break
break
else:
selected_player = random.choice(players)
selected_player_bid = random.randint(1, 100000)
print(
f"{random.choice(bidders)} chooses {selected_player} for {selected_player_bid}.")
print(
"You can either type [p]ass let them take the player or type [c]hallenge to challenge them.")
while True:
choice = input("Challenge or pass: ")
if choice.lower() == "challenge":
break
elif choice.lower() == "pass":
break
elif choice.lower() == "p":
break
elif choice.lower() == "c":
break
else:
print("Not a valid command, please type again.")
while choice.lower() == "challenge" or choice.lower() == 'c':
bid = int(input("Enter your bid: "))
if bid > money:
print("You do not have enough money.")
elif bid < selected_player_bid:
print("That is lower than the starting bid.")
else:
print(f"{selected_player} bought for {bid}")
money = money - bid
print("You have enough money.")
your_players.append(selected_player)
break
if choice.lower() == "p" or choice.lower() == "pass":
pass
players.remove(selected_player)
The usage of the function(This is where I was trying to fix the code).
while True:
if random_choice:
turn = turn + 1
random_choice = bool(random.choice(binary_numbers))
auction(your_money, turn, choice)
else:
random_choice = bool(random.choice(binary_numbers))
auction(your_money, turn, choice)
pass
if len(players) == 0:
break
else:
continue
GitHub repo
You can comment the fix or create a pull request.
Thanking you in advance.
I expected the code to randomly choose the bidder, either the player or the bots, but when I was fixing it, it was not doing so.
I'm writing code for a rock, paper, scissors game but the if statement in the function identify_winner is not running. The only thing that prints out is the else statement and it prints out for all outcomes, not just when it's a tie. I'm pretty sure it has something to do with the variables but I don't know what it is.
import random
ROCK = 1
PAPER = 2
SCISSORS = 3
def main():
user_choose(None)
comp_choose(None)
identify_winner()
def user_choose(weapon):
weapon = int(input('Choose Your Weapon' + '\n (Rock = 1, Paper = 2' +\
' Scissors = 3): '))
if weapon == 1:
print('You have chosen Rock')
elif weapon == 2:
print('You have chosen Paper')
elif weapon == 3:
print('You have chosen Scissors')
def comp_choose(choice):
if random.randint(1,3) == 1:
choice = 'Rock'
elif random.randint(1,3) == 2:
choice = 'Paper'
else:
choice = 'Scissors'
print('Your enemy has chosen',choice)
def identify_winner():
user = 0
comp = 0
while user == comp:
user_choose(user)
comp_choose(comp)
if (user == 1 and comp == 3) or (user ==2 and comp == 1) or (user == 3 and comp
== 2):
print('Congratulations! You have defeated the foe!')
elif (comp ==1 and user == 3) or (comp == 2 and user == 1) or (comp == 3 and
user == 2):
print('Alas, you have been defeated! Better luck next time!')
else:
print('Oh no, a tie! choose again!')
main()
First and foremost it is not a good practice to call main function directly as it was a script. If you plan to create not script program you should scope main function inside.
if __name__ == "__main__":
main()
Secondly, you don't need to call user_choose and comp_choose inside identify winner, you can just return those values in your main program and give them as arguments to your identify winner function. Also you should not generate two times a random number in your comp_choose() because in the second elif you could generate the previous number so comp choice most likely be Scissors. I give you one possible solution to your problem:
import random
ROCK = 1
PAPER = 2
SCISSORS = 3
def main():
identify_winner(user_choose(), comp_choose())
def user_choose():
weapon = int(input('Choose Your Weapon' + '\n (Rock = 1, Paper = 2' +\
' Scissors = 3): '))
if weapon == 1:
print('You have chosen Rock')
elif weapon == 2:
print('You have chosen Paper')
elif weapon == 3:
print('You have chosen Scissors')
return weapon
def comp_choose():
comp_weapon = random.randint(1,3)
if comp_weapon == 1:
choice = 'Rock'
elif comp_weapon == 2:
choice = 'Paper'
else:
choice = 'Scissors'
print('Your enemy has chosen',choice)
return comp_weapon
def identify_winner(user, comp):
if (user == 1 and comp == 3) or (user ==2 and comp == 1) or (user == 3 and comp
== 2):
print('Congratulations! You have defeated the foe!')
elif (comp ==1 and user == 3) or (comp == 2 and user == 1) or (comp == 3 and
user == 2):
print('Alas, you have been defeated! Better luck next time!')
else:
print('Oh no, a tie! choose again!')
if __name__ == "__main__":
main()
I made some little changes in your code. Commented the parts for explanation:
import random
# you never use those, so they are not needed here:
# ROCK = 1
# PAPER = 2
# SCISSORS = 3
def user_choose(): # no input argument needed since you define weapon in the next line anyway
weapon = int(input('Choose Your Weapon' + '\n (Rock = 1, Paper = 2' +\
' Scissors = 3): '))
# this part is asking for a number as long as user don't choose a valid number between 1 and 3.
# You could do even more here, check for number or letter, check if number is 0 or negative
while weapon>3:
weapon = int(input('No valid number. Please choose again: ' + '\n (Rock = 1, Paper = 2' +\
' Scissors = 3): '))
if weapon == 1:
print('You have chosen Rock')
elif weapon == 2:
print('You have chosen Paper')
elif weapon == 3:
print('You have chosen Scissors')
return weapon # you need to return the variable weapon, otherwise it is only in the local scope and your main function doesn't have access to it
def comp_choose(): # same as in the other function, no input argument needed
choice = random.randint(1,3) # in your code random.randint(1,3) executes twice and can have two different results. You want it once and then check on it
if choice == 1:
chose = 'Rock' # in the main() func you compare the numbers, but in your code user has numbers between 1 and 3 and comp has values with rock, paper, scissors.
elif choice == 2:
chose = 'Paper'
else:
choice = 3
chose = 'Scissors'
print('Your enemy has chosen',chose)
return choice # same as in the other function with 'weapon'
def main(): # identy_winner() isn't needed. two functions for user and comp with the main to select winner is enough
run = True
while run: # doing it like this you can make the user choose if he wants to continue or not (later at the 'continue_playing' part)
user = user_choose() # get access to the return value of the function
comp = comp_choose() # get access to the return value of the function
if (user == 1 and comp == 3) or (user ==2 and comp == 1) or (user == 3 and comp
== 2):
print('Congratulations! You have defeated the foe!')
elif (comp ==1 and user == 3) or (comp == 2 and user == 1) or (comp == 3 and
user == 2):
print('Alas, you have been defeated! Better luck next time!')
else:
print('Oh no, a tie! choose again!')
continue_playing = input('You want to play again? [y/n]: ')
if continue_playing == 'n':
run = False
main()
The code will crash if the user chooses a letter instead of numbers, and working poorly if he chooses numbers 0 or less. You may want to check for that.... I leave that up to you.
How do I make a loop in an if-statement within an if-statement? I'm busy with How to learn Python 3 the hard way, and so far I know I can do the following:
while True:
print("choose 1st branch")
choice = input()
if choice == '1':
print('1, now choose second branch')
while True:
choice = input("")
if choice == "2":
print("2")
while True:
choice = input("")
if choice == "3":
print('3')#
else: #needs to ask for input for choice 3 again
print("try again")
else:print("try again")#needs to ask for input for choice 2 again
ive edited a simpler code example of what im trying to accomplish
Instead of creating a loop everywhere you want to check if the user input is a valid choice, you can extract that "checking if user input is within a valid choices" into a function. Said function will be something like
def get_user_choice(prompt, choices=None):
while True:
choice = input(prompt)
if choices is None:
# Return the entered choice without checking if it is
# valid or not.
return choice
if choice in choices:
return choice
print("unknown choice, try again")
With this new function, we check the validity of the choices first, then after we received the correct input, we then process with the logic for each of the choices.
occu = "ranger"
prompt = "-->"
def get_user_choice(prompt, choices=None):
while True:
choice = input(prompt)
if choices is None:
# Return the entered choice without checking if it is
# valid or not.
return choice
if choice in choices:
return choice
print("unknown choice, try again")
def room1():
print("you walk into an bare room")
door = False
gemstone = False
hole = False
monster = False
rat = False
trap = False
occu = "ranger"
while True:
print("you see a door infront of you")
print("do you go left, right or forward?")
choice = get_user_choice(prompt, ("left", "right", "forward"))
if choice == "left" and hole == False:
print("\nDo you \ndodge \nor \nattack?")
choice = get_user_choice(prompt, ("dodge", "attack"))
if choice == "dodge" and occu == "ranger":
trap = True
rat = True
print("\nhole \nroom")
choice = get_user_choice(prompt, ("hole", "room"))
if choice == "hole" and rat == True:
print("you walk up to the hole, you see a faint glitter")
print("do you reach your hand in?")
print("\nyes \nno")
choice = get_user_choice(prompt, ("yes", "no"))
if choice == "yes":
print("you reach into the whole and pull out a gemstone")
print("you put the gemstone in your inventory")
print("and go back to the room\n")
hole = True
gemstone = True
choice = True
elif choice == "no":
print(" you go back to the centre of the room")
Notice that other input also get modified to use this function to check if the choice user selected is valid or not.
The problem is that you are reusing the variable choice, and assigning it to be a boolean value and later on be the input. Try using another variable as well for either the boolean or the input, i.e. proceed.
proceed = False # CREATE VARIABLE PROCEED
while proceed == False: # LOOP WHILE PROCEED IS FALSE
print("do you reach your hand in?")
print("\nyes \nno")
choice = input(prompt)
if choice == "yes":
print("you reach into the whole and pull out a gemstone")
print("you put the gemstone in your inventory")
print("and go back to the room\n")
hole = True
gemstone = True
proceed = True # CHANGE PROCEED, NOT CHOICE
elif choice == "no":
print("You go back to the center of the room")
# Perhaps assign proceed to be True here as well?
else:
print("unknown choice, try again")
occu = 'ranger'
prompt = "-->"
def room1():
print("you walk into an bare room"
door = False
gemstone = False
hole = False
monster = False
rat = False
trap = False
occu = 'ranger'
while True:
print("you see a door infront of you")
print("do you go left, right or foward?")
if input(prompt) == 'left' and hole == False:
print('\nDo you \ndodge \nor \nattack?')
if input(prompt) == 'dodge' and occu == 'ranger':
trap = True
rat = True
print("\nhole \nroom")
if input(prompt) == 'hole' and rat == True:
print("you walk up to the hole, you see a faint glitter")
while True:
print("do you reach your hand in?")
print("\nyes \nno")
choice = input(prompt)
if choice not in ['yes', 'no']:
print("unknown choice, try again")
continue # <-- Starts loop over.
elif choice == "yes":
print("you reach into the whole and pull out a gemstone")
print("you put the gemstone in your inventory")
print("and go back to the room\n")
hole = True
gemstone = True
else:
print(" you go back to the centre of the room")
break # <-- Breaks out of loop.
I am currently producing a menu-driven program. Here is a code snippet:
def main():
intro()
loop = True
while loop:
print("\n<<<<<<<<<<<<<<<<<<<<<<<<< ||| >>>>>>>>>>>>>>>>>>>>>>>>")
print("\nChoose your option below:")
print("1 - Patient Registration")
print("2 - Total Patients")
print("3 - Total Sales")
print("Q/q - Quit")
choice = str(input("Your choice?"))
print("\n<<<<<<<<<<<<<<<<<<<<<<<<< ||| >>>>>>>>>>>>>>>>>>>>>>>>")
menu(choice)
def intro():
print("Welcome to CTI System.")
print("This system is used to track and manage Covid-19 testing")
def menu(choice):
if choice == '1':
patientRegistration()
elif choice == '2':
testType(pcr,antigen)
elif choice == '3':
totalSales()
elif choice == 'Q' or choice == 'q':
print("\nThank you for using this program.\n")
exit()
else:
print("\nInvalid choice! Please select from the list of choices.\n")
loop = False
When choosing the first choice, it will prompt the user to gather information. Afterwards, once the user is done with the first choice, the user will be prompted to continue, if 'N' then it will go back to the main menu.
This is where where problem starts. I want to choose the 2nd choice in the menu which is the total number of patients. How can I pass the parameters from the first condition to the second?
Your help is greatly appreciated.
Thank you!
so I've been struggling with the first part of an assignment. For some reason the while loop in the entrance() function has been causing problems. As far as I know, this is the only statement that has been throwing me off. Can help me fix this?
#Satinderpal Saroa A3 30027872
#Entrance Function
def entrance():
lockedDoor = True
print("""
ROOM: ENTRANCE
_____________________________________________________________
You are at the entrance. The door you entered through is gone
and the door to what might be the exit is in front of you.
There are two entryways to the left and the right, what will
you choose to do?
_____________________________________________________________
Your choices are:
1. Try to open the door
2. Go through the left entryway
3. Go through the right entryway
""")
enterChoice = int(input("Your choice: "))
while lockedDoor == True:
if (lever == "backwards" and dial == "red"):
lockedDoor == False
print("You go through the door and enter... another part of the house?!")
if(enterChoice not in [1,2,3]):
print("INVALID INPUT: Please enter 1,2, or 3.")
enterChoice = int(input("Your choice: "))
if (enterChoice == 1):
print("You try to open the door, it doesn't move an inch!")
enterChoice = int(input("Your choice: "))
elif(enterChoice == 2):
print("You make your way down to the kitchen.")
lever = kitchen()
elif(enterChoice == 3):
print("You make your way down to the pantry")
dial = pantry()
return()
#Kitchen Function
def kitchen():
lever = "nothing"
print("""
ROOM: KITCHEN
_____________________________________________________________
You reach the kitchen. Everything is spotless, a disturbing
revelation as you know that the house hasn't been touched
in decades. Near the sink, there is a lever that can be pulled
backwards or forwards. What will you do?
_____________________________________________________________
Your choices are:
1. Pull the lever backwards
2. Push the lever forwards
3. Do nothing and go back to the entrance
""")
kitchenChoice = int(input("Your choice: "))
if (kitchenChoice not in [1,2,3]):
print("INVALID INPUT: Please choose between 1,2, and 3")
kitchenChoice = int(input("Your choice: "))
elif (kitchenChoice == 1):
lever == "backwards"
print("The lever is pulled backwards")
lever = entrance()
elif (kitchenChoice == 2):
lever == "forwards"
print("The lever is pushed forwards")
lever = entrance()
elif (kitchenChoice == 3):
print("You don't do anything and return to the entrance")
lever = entrance()
return (lever)
#Pantry Function
def pantry():
dial = "nothing"
print("""
ROOM: PANTRY
_______________________________________________________________
You reach the pantry. All of the foodstocks and goods have been
expired for ages. You notice a dial that can be turned to one of
three colors; red, blue, and green. What will you do?
_______________________________________________________________
Your choices are:
1. Turn the dial to red
2. Turn the dial to blue
3. Turn the dial to green
4. Don't do anything and return to the entrance
""")
pantryChoice = int(input("Your choice: "))
if (pantryChoice not in [1,2,3,4]):
print("ERROR: Please enter 1,2,3 or 4.")
pantryChoice = int(input("Your choice: "))
elif (pantryChoice == 1):
dial == "red"
print("The dial is set to red")
dial = entrance(dial)
elif (pantryChoice == 2):
dial == "blue"
print("The dial is set to blue")
dial = entrance()
elif (pantryChoice == 3):
dial = "green"
print("The dial is set to blue")
dial = entrance()
elif (pantryChoice == 4):
print("You don't do anything and you return to the entrance")
dial = entrance()
return(dial)
#Start function
def start():
entrance()
start()
please initialize 'lever' variabel in entrace as it is used in it else use a global variable 'lever' in the program