When I use this code, my aim is to try and make sure that any input will not break the code like letters or numbers not between 0-3. But when i use this code the whole list isn't coming up. How would i fix this?
The output should look like this
Hello Megan the four games avaliable are:
0 Mario Cart
1 Minecraft
2 Angry Birds
3 Grabd Theft Auto
What number game do you want? h
Please choose a valid number
What number game do you want? 23
Please choose a number between 0 and 3
What number game do you want? 1
You have chosen Minecraft
Instead, the output is
Hello the four games avaliable are:
0 Mario Cart
What number game do you want? 2
1 Minecraft
What number game do you want? h
Please enter a valid value
The code i am using is:
#Ask user what game they would like to play
def game () :
global gametype,gamelist
gamelist = ["Mario Cart","Minecraft","Angry Birds","Grabd Theft Auto"]
gamecount = 0
print ("Hello the four games avaliable are:")
while gamecount < 4:
print (gamecount," ",gamelist[gamecount])
gamecount = gamecount + 1
try:
gametype = int(input("What number game do you want? "))
while gametype <0 or gametype >3:
print (" Please enter a value between 0 and 3")
except ValueError:
print ("Please enter a valid value " )
return gametype
game ()
I have also tried another way, using 'while True' before 'try' but the program says that is an invalid syntax.
SECOND TRY
I have used this new code, but again it won't let me run the code as it says I have an invalid syntax when I put While True, with True highlighted in red.
#Ask user what game they would like to play
def game () :
global gametype,gamelist
gamelist = ["Mario Cart","Minecraft","Angry Birds","Grabd Theft Auto"]
gamecount = 0
print ("Hello the four games avaliable are:")
while gamecount < 4:
print (gamecount," ",gamelist[gamecount])
gamecount = gamecount + 1
while True:
try:
gametype = int(input("What number game do you want? "))
if 0 <= gametype <= 3 :
return game
print ("Please enter a value between 0 and 3 ")
except ValueError:
print ("Please enter whole number from 0 to 3 " )
return game
game ()
I think you want something like this:
gamelist = ["Mario Cart", "Minecraft", "Angry Birds", "Grand Theft Auto"]
def game(name):
""" Ask user what game they would like to play """
print ("Hello, {}, the four available games are:".format(name))
for gamenum, gamename in enumerate(gamelist):
print(gamenum, ":", gamename)
while True:
try:
gamenum = int(input("What number game do you want? "))
if 0 <= gamenum <= 3:
return gamenum
print("Please enter a value between 0 and 3")
except ValueError:
print ("Please enter a whole number from 0 to 3")
name = input("What's your name? ")
gamenum = game(name)
print("You chose", gamelist[gamenum])
demo output
What's your name? Megan
Hello, Megan, the four available games are:
0 : Mario Cart
1 : Minecraft
2 : Angry Birds
3 : Grand Theft Auto
What number game do you want? 4
Please enter a value between 0 and 3
What number game do you want? Minecraft
Please enter a whole number from 0 to 3
What number game do you want? 2
You chose Angry Birds
The main change I made to your code is to put the try.. except stuff inside a while True block, so we keep asking for input until we get something valid. I also used enumerate to print each game with its number. That's neater than your while gamecount < 4: loop.
If you have to print the list of games using a while loop then you can do it like this:
gamelist = ["Mario Cart", "Minecraft", "Angry Birds", "Grand Theft Auto"]
def game(name):
""" Ask user what game they would like to play """
print ("Hello, {}, the four available games are:".format(name))
gamenum = 0
while gamenum < len(gamelist):
print(gamenum, ":", gamelist[gamenum])
gamenum += 1
while True:
try:
gamenum = int(input("What number game do you want? "))
if 0 <= gamenum <= 3:
return gamenum
print("Please enter a value between 0 and 3")
except ValueError:
print ("Please enter a whole number from 0 to 3")
name = input("What's your name? ")
gamenum = game(name)
print("You chose", gamelist[gamenum])
I made gamelist a global list so we can access it outside the game function. We don't need to use the global statement in the function because we aren't changing gamelist. In general, you should avoid using the global statement.
Related
I'm trying to create a menu for a POS like system. I have my gift card balances with their numbers and I'm trying to incorporate this in a menu. In the menu for example, if a user click the number '1', I want the menu to prompt the user for the gift card number in which they will need to enter the correct gift card number (giftnum1). If the user does not click on a valid number or does not enter the correct gift card, I would like the menu to ask the user to click on a valid number or if the user enters the wrong gift card number, I would like for the menu to ask the user to check the gift card number and try again. I am new at this, so I know that most of my menu code is wrong and could be corrected somehow, but I'm not sure how to do this and all other posts relating to this do not make sense with this post.
Here is my code that I have:
gift1 = 100
gift2 = 13.50
gift3 = 67.40
giftnum1 = 123456
giftnum2 = 998765
giftnum3 = 456789
print("Here are your current gift cards with the current balances: " + "$" + str(gift1) + " with the gift \ncard number of " + str(giftnum1) + ", $" + str(gift2) + " with a gift card number of " + str(giftnum2) + ", and $" + str(gift3) + " with a gift card number of " + str(giftnum3) + ".")
#making the POS system
def itemmenu():
print ("Here are the current items with their price. You must choose the correct gift card to go along with the item.")
print ("1. Nike Shoes ($100)")
print ("2. Bluetooth Headphones ($67.40)")
print ("3. Gloves ($13.50)")
print ("4. Exit")
loop = True
while loop:
itemmenu()
buyitems = int(input("Enter the number corresponding to the item that you would like to buy: "))
if buyitems == 1:
input("Please enter the correct gift card to buy the Nike Shoes: ")
if buyitems == giftnum1:
print("You have successfully entered the correct gift card to buy the Nike Shoes, please follow the directions to be sent a confirmation email.")
if buyitems != giftnum1:
print("You have entered an incorrect gift card number.")
elif buyitems == 2:
input("Please enter the correct gift card to but the Bluetooth Headphones: ")
if buyitems == giftnum2:
print("You have successfully entered the correct gift card to buy the Bluetooth Headphones, please follow the directions to be sent a confirmation email.")
while loop:
itemmenu()
buyitems = int(input("Enter the number corresponding to the item that you would like to buy: "))
if buyitems == 1:
input("Please enter the correct gift card to buy the Nike Shoes: ")
if buyitems == giftnum1:
You aren't saving the result of the second input() call, so buyitems is still the same value it was before.
You probably want something like this:
if buyitems == 1:
giftcard = int(input("Please enter the correct gift card to buy the Nike Shoes: "))
if giftcard == giftnum1:
Please try below code :
gift1 = 100
gift2 = 13.50
gift3 = 67.40
giftnum1 = 123456
giftnum2 = 998765
giftnum3 = 456789
print("Here are your current gift cards with the current balances: " + "$" + str(gift1) + " with the gift \ncard number of " + str(giftnum1) + ", $" + str(gift2) + " with a gift card number of " + str(giftnum2) + ", and $" + str(gift3) + " with a gift card number of " + str(giftnum3) + ".")
#making the POS system
def itemmenu():
print ("Here are the current items with their price. You must choose the correct gift card to go along with the item.")
print ("1. Nike Shoes ($100)")
print ("2. Bluetooth Headphones ($67.40)")
print ("3. Gloves ($13.50)")
print ("4. Exit")
loop = True
while loop:
itemmenu()
buyitems = int(input("Enter the number corresponding to the item that you would like to buy: "))
if buyitems == 1:
while loop:
giftcardno = int(input("Please enter the correct gift card to buy the Nike Shoes: "))
if giftcardno == giftnum1:
print("You have successfully entered the correct gift card to buy the Nike Shoes, please follow the directions to be sent a confirmation email.")
break
else:
print("You have entered an incorrect gift card number. Try again")
elif buyitems == 2:
giftcardno = input("Please enter the correct gift card to but the Bluetooth Headphones: ")
if giftcardno == giftnum2:
print("You have successfully entered the correct gift card to buy the Bluetooth Headphones, please follow the directions to be sent a confirmation email.")
else:
print("You have entered an incorrect gift card number. Try ag")
else:
break
Hetal Thaker and John Gordon answers are what you are looking for. One issue that may arise though, as you have probably noticed, is that your loop becomes endless even when you select the correct gift card number. To fix that simply set your loop variable to False once an item is purchased and it will work.
I have played around with your code a bit and made some transformations using dictionaries and less hard coding. Check it out, it might help in case you have larger data of variables - you can simply put them into the 2 dictionaries and the rest will work on it's own. Note that I did not implement any logic on what happens when the user selects "Exit" as I am not sure what behavior exactly you expect from the program for that. It would also be good to add logic in case the correct gift card is entered but its balance is not enough.
gift1_balance = 100
gift2_balance = 13.50
gift3_balance = 67.40
gift1_num = 123456
gift2_num = 998765
gift3_num = 456789
gift_cards = {gift1_num: gift1_balance, gift2_num: gift2_balance, gift3_num: gift3_balance}
merch_to_sell = {"Nike Shoes": [100, 1], "Bluetooth Headphones": [67.40, 2], "Gloves": [13.50, 3]}
print("Here are your current gift cards with the current balances:")
for key, value in gift_cards.items():
print(f"${value} with the gift card number of {key}")
def item_menu():
print ("Here are the current items with their price. You must choose the correct gift card to go along with the item.")
index = 1
for key, value in merch_to_sell.items():
print(f"{index}. {key} (${value[0]:.2f})")
index += 1
print(f"{index}. Exit")
is_item_bought = False
while not is_item_bought:
item_menu()
number_of_item = int(input("Enter the number corresponding to the item that you would like to buy: "))
current_item = 0
current_price = 0
current_index = 0
get_gift_num = 0
for k, v in merch_to_sell.items():
current_item = k
current_price = v[0]
current_index = v[1]
if is_item_bought:
break
if number_of_item == current_index:
get_gift_num = int(input(f"Please enter the correct gift card to buy the {current_item}: "))
for k, v in gift_cards.items():
if get_gift_num == k and gift_cards[k] == current_price:
print(f"You have successfully entered the correct gift card to buy the {current_item}, please follow the directions to be sent a confirmation email.")
is_item_bought = True
break
if not is_item_bought:
print("You have entered an incorrect gift card number.")
If you take this code, you can refactor it and eliminate some unnecessary variables within it and optimize it even further.
Cheers!
I'm trying to get this For loop to repeat itself for an amount equal to "totalNumStudents"
for score in range(totalNumStudents):
# Prompt to enter a test score.
test_score = int(input("Enter the test score: "))
# If the test score entered is in range 0 to
# 100, then break the loop.
if 0 <= test_score <= 100:
break
However, the code never gets to this loop and restarts from the beginning.
Here is the first half of the code including the loop.
freshman = 0
sophomore = 0
junior = 0
senior = 0
test_score = 0
totalTestScores = 0
totalNumStudents = freshman + sophomore + junior + senior
# Start a while loop.
while True:
# Display the menu of choices.
print("\nPress '1' to enter a student")
print("Press '2' to quit the program")
print("NOTE: Pressing 2 will calculate your inputs.\n")
# Prompt to enter a choice.
choice = input("Enter your choice: ")
# If the choice is 1.
if choice == '1':
# Start a while loop to validate the grade level
while True:
# Prompt the user to enter the required grade level.
freshman = int(input("How many students are Freshman? "))
sophomore = int(input("How many students are Sophomores? "))
junior = int(input("How many students are Juniors? "))
senior = int(input("How many students are Seniors? "))
break
for score in range(totalNumStudents):
# Prompt to enter a test score.
test_score = int(input("Enter the test score: "))
# If the test score entered is in range 0 to
# 100, then break the loop.
if 0 <= test_score <= 100:
break
# Otherwise, display an error message.
else:
print("Invalid test score! Test score " +
"must be between 0 and 100.")
# Calculate total test scores
totalTestScores = totalTestScores + test_score
What am I missing here?
Since you add up before get those numbers, your totalNumStudents is all always zero. You should put the add up statement after you get the numbers:
...
# Start a while loop to validate the grade level
while True:
# Prompt the user to enter the required grade level.
freshman = int(input("How many students are Freshman? "))
sophomore = int(input("How many students are Sophomores? "))
junior = int(input("How many students are Juniors? "))
senior = int(input("How many students are Seniors? "))
break
# add up here
totalNumStudents = freshman + sophomore + junior + senior
for score in range(totalNumStudents):
# Prompt to enter a test score.
test_score = int(input("Enter the test score: "))
# If the test score entered is in range 0 to
# 100, then break the loop.
if 0 <= test_score <= 100:
break
...
BTW since your while True loop only runs once, you don't need the loop. Just remove it.
There are a few problems with my code that I don't know how to fix.
When I am printing out the message of what game and the level they chose, at the end, it isn't printing out the level (beginner, intermediate or advanced). It only prints out the game. I have put 'num' to print it but i have also tried 'Level' and 'number' in place. The code is
print ("Play",gamelist[gametype], "at" ,num)
When asking the user what game they would like to play, if they input a number out of the range of 0-3 or a letter it breaks further down in the code when printing the message at the end. This is only when asking what game, not the level they want the game at.
Anything to help would be appreciated.
#Ask user what game they would like to play
def game () :
global gametype,gamelist
gamelist = ["Mario Cart","Minecraft","Angry Birds","Grabd Theft Auto"]
gamecount = 0
print ("Hello",name,"the four games avaliable are:")
while gamecount < 4:
print (gamecount," ",gamelist[gamecount])
gamecount = gamecount + 1
gametype = int(input("What number game do you want? (Please choose between 0 and 3) "))
print ( "You have chosen",gamelist[gametype],)
print ("")
#Ask game level
def number():
while True:
try:
Level = int(input("What is the level you would like to play at? "))
if Level <= 25:
print ("Begginer ")
break
elif Level >=26 and Level <=75:
print ("Intermediate")
break
elif Level >=76 and Level <=100:
print ("Advanced")
break
else:
print("Out Of range(1-100): Please enter a valid number:")
except ValueError:
print("Please enter a valid number")
#Create a subroutine to print out the action message
def printmessage ():
print ("")
print ("# #")
print ("########################################################")
print ("#################### ACTION MESSAGE ####################")
print ("########################################################")
print ("# #")
print ("Play",gamelist[gametype], "at" ,num)
print ("# #")
print ("########################################################")
print ("#################### ACTION MESSAGE ####################")
print ("########################################################")
print ("# #")
#This is to let the program work
name = input("What is your name? ")
print ("")
game ()
num = number()
printmessage()
I put comment with the changes:
#Ask user what game they would like to play
def game (name) :
global gametype,gamelist
gamelist = ["Mario Cart","Minecraft","Angry Birds","Grabd Theft Auto"]
gamecount = 0
print ("Hello "+name+" the four games avaliable are:")
while gamecount < 4:
print (gamecount," ",gamelist[gamecount])
gamecount = gamecount + 1
gametype = int(input("What number game do you want? (Please choose between 0 and 3) "))
print ( "You have chosen "+gamelist[gametype])
print ("")
#Ask game level
def number():
while True:
try:
Level = int(input("What is the level you would like to play at? "))
if Level <= 25:
print ("Begginer ")
return("Begginer ")#changed break with return so it will break and return the selected value
elif Level >=26 and Level <=75:
print ("Intermediate")
return("Intermediate ")#changed break with return so it will break and return the selected value
elif Level >=76 and Level <=100:
print ("Advanced")
return("Advanced ")#changed break with return so it will break and return the selected value
else:
print("Out Of range(1-100): Please enter a valid number:")
except ValueError:
print("Please enter a valid number")
#Create a subroutine to print out the action message
def printmessage (num):
print ("")
print ("# #")
print ("########################################################")
print ("#################### ACTION MESSAGE ####################")
print ("########################################################")
print ("# #")
print ("Play "+gamelist[gametype]+" at "+num)
print ("# #")
print ("########################################################")
print ("#################### ACTION MESSAGE ####################")
print ("########################################################")
print ("# #")
#This is to let the program work
name = raw_input("What is your name? ") # I changed input with raw_input because you are sending a string not integer
print ("")
game (name)
num = number()
printmessage(num)
This is the Output:
What is your name? Test
Hello Test the four games avaliable are:
(0, ' ', 'Mario Cart')
(1, ' ', 'Minecraft')
(2, ' ', 'Angry Birds')
(3, ' ', 'Grabd Theft Auto')
What number game do you want? (Please choose between 0 and 3) 0
You have chosen Mario Cart
What is the level you would like to play at? 1000
Out Of range(1-100): Please enter a valid number:
What is the level you would like to play at? 1
Begginer
# #
########################################################
#################### ACTION MESSAGE ####################
########################################################
# #
Play Mario Cart at Begginer
# #
########################################################
#################### ACTION MESSAGE ####################
########################################################
#
Add the following line of code at the end of function def number:
return Level
I'm new to Computer Science and to Stack Overflow and I'm currently stuck with this IGCSE summer work. I'm creating a game called "100" in Python and the rule is whoever reaches 100 first wins. The coding's below:
# Exercise 4 - Beginner
while True:
print("~~~~~ THE 100 GAME - CODED BY SASU ~~~~~")
print('----- MENU -----')
print('1 - Start multiplayer game')
print('2 - Quit game')
choice = int(input('What are you going to do? Input the number representing your choice.'))
if choice == 1:
print('Let's do it!')
elif choice == 2:
print('See you soon.')
break # In order to stop the program and quit
else:
print('What the heck? Type again.')
print("~~~~~ THE 100 GAME - CODED BY SASU ~~~~~")
print('----- MENU -----')
print('1 - Start multiplayer game')
print('2 - Quit game')
choice = int(input('What are you going to do? Input the number representing your choice.'))
if choice == 1:
print('Let's do it!')
elif choice == 2:
print('See you soon.')
break # In order to stop the program and quit
else:
print('What the heck? Type again.') # After this it just starts the multiplayer game right away I don't know how to fix this
while True:
print('Yooo player 1, tell me your name:')
oneName = input()
print('Well then, player 2, what about ya?')
twoName = input()
print('Well hey there, ' + oneName + ' and ' + twoName + ', and welcome to 100!')
print('You will each take turns to choose a number between 1 and 10.')
print('The first person to reach 100 is the winner.')
print("Have fun, and let's get started!")
totalNumber = 0
while True:
while totalNumber < 100:
numberOne = input(oneName + ', give me a number between 1 and 10.') # I don't know how to limit the range though
numberOne = int(numberOne)
totalNumber += numberOne
print("Got it, " + oneName + "! Below is the total right now:")
print(totalNumber)
break
while totalNumber < 100:
numberTwo = input(twoName + ', give me a number between 1 and 10.')
numberTwo = int(numberTwo)
totalNumber += numberTwo
print("Got it, " + twoName + "! Below is the total right now:")
print(totalNumber)
break
After all these codes, when we run the game, players can input numbers until the total reaches the number 100. However, I don't know how to make the game announce the winner. Like, keep track of the players' progress. If anyone can help, that would be great! Also, if you can help me out in fixing my problems in the code, that would be a huge help! Thank you :)
Just a hint. Use dict in python.
for example :
d = {'one' = 0,'two' = 0}
Increment key value each time and check if it reaches to 100.
Hope you get it.
so I've been working on this code for a little bit just to test my abilities and I've run into a brick wall. For some reason my code is breaking out of my for loop. If I say I want to see how much 2 rooms cost it goes through the first one fine but them asks me how many rooms I want to check again. If I input 2 again, it will go through it once and then go on through the rest of the code normally. I have two for loops setup the exact same as each other but for some reason one works and the other doesn't. I'm probably making a stupid mistake but I've been trying to fix it for ages now but no cigar. Appreciate all help!
def start():
print ("Welcome to Caroline's Painting and Decorating cost estimator")
print ("Here you can see an estimate to see how much the job will cost")
print ("First though, you have to enter a few details about the job")
customerNumber = input ("Please enter your customer number ")
dateofEstimate = input ("Please enter the current date ")
def roomCalculator():
surfaceAreaCost = 0
totalPrice = 0
price = 0
count = 0
rooms = int(input("Please enter the number of rooms that require painting "))
for i in range(0, rooms):
roomName = input ("What room needs decorating? ")
wallsNumber = int(input("How many walls are in the room? "))
wallpaper = input ("Is there any wallpaper thats needs to be removed? Enter Y for yes and N for no ")
if wallpaper == "Y".lower():
surfaceAreaCost + 70
for i in range(0, wallsNumber):
count = count + 1
print ("Please enter the dimensions for wall", count)
height = int(input("How high is the wall? "))
width = int(input("How long is the wall? "))
surfaceAreaWall = height*width
wallCost = surfaceAreaWall * 15
price = surfaceAreaCost + wallCost
employeeType = input ("What employee would you like? Enter AP for apprentice or FQ for Fully-Qualified ")
if employeeType == "AP".lower():
price = price + 100
print ("You are having an apprentice do the job")
print ("The price for the", roomName, "without V.A.T is", price)
return price
elif employeeType == "FQ".lower():
price = price + 250
print ("You are having a Fully-Qualified employee to do the job")
print ("The price for the", roomName, "without V.A.T is", price)
return price
Your error is a result of nested for loops, because you use variable i in both. This causes an error since you change value of variable i in first for loop with second for loop. Rename variable in second for loop with j for instance.
Thanks all for the help! It was a stupid error on my part. I used 3.4.4 at my school computer and 3.5.1 at home. It all worked anyway.