I can't figure out how to make this code give me the output I need. It is supposed to ask the user where they want to go on vacation, and then display the location they have chosen.
print("Congratulations! You have won an all-inclusive vacation!" + '\n')
input("Please enter your first and last name" + '\n')
print("Please choose where would you like to go on vacation?" + '\n'
+ "A. The Bermuda Triangle" + '\n'
+ "B. Space" + '\n'
+ "C. Antarctica" + '\n')
def choose_location():
if choose_location == "A":
print("You chose The Bermuda Triangle")
elif choose_location == "B":
print("You chose Space")
elif choose_location == "C":
print("You chose Antarctica")
choose_location()
not sure why you need the function
your code has a few problems.
first, don't use the same function name as the variable name.
second, instead of print, it should be input.
third, you need to save inputs to variables so you can use them.
but you need to use the input instead of print, and save the input to a variable,
print("Congratulations! You have won an all-inclusive vacation!" + '\n')
name = input("Please enter your first and last name" + '\n')
def choose_location():
location = input("Please choose where would you like to go on vacation?" + '\n'
+ "A. The Bermuda Triangle" + '\n'
+ "B. Space" + '\n'
+ "C. Antarctica" + '\n')
if location == "A":
print("You chose The Bermuda Triangle")
elif location == "B":
print("You chose Space")
elif location == "C":
print("You chose Antarctica")
choose_location()
or even a version that make-use of the function.
Notice that I added .upper() so even if the user enters a small letter it will still work
def choose_location(location):
location = location.upper()
if location == "A":
print("You chose The Bermuda Triangle")
elif location == "B":
print("You chose Space")
elif location == "C":
print("You chose Antarctica")
print("Congratulations! You have won an all-inclusive vacation!" + '\n')
name = input("Please enter your first and last name" + '\n')
choose_location(input("Please choose where would you like to go on vacation?" + '\n'
+ "A. The Bermuda Triangle" + '\n'
+ "B. Space" + '\n'
+ "C. Antarctica" + '\n'))
Related
I'm trying to figure out how to implement a function that will store and print where the user wants to place an "X" in the game of Tic Tac Toe. If there are any other suggests you have to fix my code, it would be greatly appreciated. I just started coding so apologies if it looks terrible.
def print_board():
game_board = ["-", "-", "-", "-", "-", "-", "-", "-", "-"]
print(game_board[0] + " | " + game_board[1] + " | " + game_board[2])
print(game_board[3] + " | " + game_board[4] + " | " + game_board[5])
print(game_board[6] + " | " + game_board[7] + " | " + game_board[8])
print_board()
#selecting a space on the board
selection = int(input("Select a square: "))
try:
if selection > 9 or selection < 1:
print("Sorry, please select a number between 1 and 9.")
else:
print(selection)
except ValueError:
print("Oops! That's not a number. Try again...")
You just need to keep asking until you get a valid number. Also, you need the "try" statement to wrap the function that will fail, in this case the int function. Here's a way to do it without try/except, which is really not the best choice here.
while True:
#selecting a space on the board
selection = input("Select a square: ")
if selection.isdigit():
selection = int(selection)
if 1 <= selection <= 9:
break
print("Sorry, please select a number between 1 and 9.")
else:
print("Oops! That's not a number. Try again...")
Your code looks alright, there are a couple of things to look at though. First, you are storing the game_board inside of the print_board() function, so each time you run print_board() the gamestate resets. Also, your code does not update the board when the user types a number. This can be fixed by changing the corresponding value of the board to an "X", and for a list this is as simple as game_board[selection] = "X". So after those two changes your file might look like this:
game_board = ["-", "-", "-", "-", "-", "-", "-", "-", "-"]
def print_board():
print(game_board[0] + " | " + game_board[1] + " | " + game_board[2])
print(game_board[3] + " | " + game_board[4] + " | " + game_board[5])
print(game_board[6] + " | " + game_board[7] + " | " + game_board[8])
print_board()
#selecting a space on the board
selection = int(input("Select a square: "))
try:
if selection > 9 or selection < 1:
print("Sorry, please select a number between 1 and 9.")
else:
game_board[selection] = "X"
except ValueError:
print("Oops! That's not a number. Try again...")
print_board()
Doing my homework rn and a bit stuck, why does the code execute "else" even thought the "if" has been satisfied? Ignore the sloppy code, I'm very new :/
order1 = input("What would you like to order?: \n \n" + "1: " + orderBurger + "\n" + "2: " + orderFries + "\n" + "3: " + orderDrink + "\n" + "\nAnswer = ")
while order == True:
if order1 == 1:
print("You have selected to order 1: " + orderBurger)
elif order1 == 2:
print("You have selected to order 1: " + orderFries)
elif order1 == 3:
print("You have selected to order 1: " + orderDrink)
else:
print("Invalid Input")
check = input("Is this your final item?:" + "1: " + q1 + "2: " + q2 + "Answer = ")
if check == 1:
print("Your items have been added to the basket")
break
elif check == 2:
check
elif check == 3:
check
else:
print("Invalid input")
This is the output
If you use type(order1), you'll see if your answer is a string or an int. If it's a string (and I think it is), you can convert it into int using int(order1), or replace your code by if order1 == '1'
Indentation is very important in Python. Based on how the indentations are implemented, the code blocks for conditions get executed.
A misplaced indent can lead to unexpected execution of a code block.
Here is a working demo of the ordering program
# File name: order-demo.py
moreItems = True
while (moreItems == True):
order = input("\n What would you like to order?\n"
+ " 1: Burger\n 2: Fries\n 3: Drink\n Answer = ")
if ((order == "1") or (order == "2") or (order == "3")):
print("You have selected to order " + order)
print("Your item has been added to the basket.\n")
else:
print("Invalid Input")
check = input("Is this your final item?: \n 1: Yes \n 2: No \n Answer = ")
if check == "1":
print("\n Thank you. Please proceed to checkout.")
moreItems = False
elif check == "2":
print("Please continue your shopping")
else:
print("Invalid input")
Output
$ python3 order-demo.py
What would you like to order?
1: Burger
2: Fries
3: Drink
Answer = 1
You have selected to order 1
Your item has been added to the basket.
Is this your final item?:
1: Yes
2: No
Answer = 2
Please continue your shopping
What would you like to order?
1: Burger
2: Fries
3: Drink
Answer = 2
You have selected to order 2
Your item has been added to the basket.
Is this your final item?:
1: Yes
2: No
Answer = 1
Thank you. Please proceed to checkout.
$
replace first line with this :
order1 = int( input("What would you like to order?: \n \n" + "1: " + orderBurger + "\n" + "2: " + orderFries + "\n" + "3: " + orderDrink + "\n" + "\nAnswer = ") )
I am wondering if there is a way to repeat a function with different values in the code
I've asked my teacher, searched online, asked some peers and none have the answer
while cashChoice > 0:
cash1 = 200 + int(offer1)*50
cashorBox = input("Would you like the money or the box? You have been offered $" + str(cash1) + ". If you want money, press [m], if you want the box, press [b]")
if cashorBox == "m":
print("Congratulations, you get " + str(cash1) + "! The prize you could've won from the box was " + str(userBox) + ". See you!")
sys.exit
elif cashorBox == "b":
print("Ok... you will be offered another cash amount.")
cashChoice -= cashChoice
if cashChoice == 0:
print("Great! You may have the box. It contains " + str(userBox) + "! Farewell :)")
sys.exit
else:
continue
I want it to repeat but with different values of "cash1" as in "cash2"
There is a very simple answer for this, and it will be very important to know later on if you wish to become proficient in Python. I don't know exactly how you are wanting to implement this, but you can do it like so:
def yourFunction (cash1Param):
while cashChoice > 0:
cash1 = cash1Param
cashorBox = input("Would you like the money or the box? You have been offered $" + str(cash1) + ". If you want money, press [m], if you want the box, press [b]")
if cashorBox == "m":
print("Congratulations, you get " + str(cash1) + "! The prize you could've won from the box was " + str(userBox) + ". See you!")
sys.exit
elif cashorBox == "b":
print("Ok... you will be offered another cash amount.")
cashChoice -= cashChoice
if cashChoice == 0:
print("Great! You may have the box. It contains " + str(userBox) + "! Farewell :)")
sys.exit
else:
continue
Then, when you call the function, you can enter any value for cash1Param, such as:
yourFunction(5)
or
yourFunction(678678967)
You don't even need to use cash1 for everything. You could just replace all of the times you have used it with cash1Param to directly use the parameter.
These are called function parameters. Here is a relevant link for learning them: https://www.protechtraining.com/content/python_fundamentals_tutorial-functions
If you have any further questions, don't be afraid to ask.
So I'm trying to create a while loop so the user can choose whether they want to continue the program or not. Any suggestions?
import random
while True:
print ("--------------------------------------------------------------------\n")
name = input("Please enter your name: ")
pack = [1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21]
random.shuffle(pack)
print ("Welcome {0}! Hope you have fun playing! \n".format(name))
print("Original deck:", pack, "\n")
print ("--------------------------------------------------------------------\n")
for i in range(3):
pack1 = pack[::3]
pack2 = pack[1::3]
pack3 = pack[2::3]
print("1: ", pack1, "\n")
print("2: ", pack2, "\n")
print("3: ", pack3, "\n")
user = input("Pick a number and enter the row it is in: ")
while not (user == "1" or user == "2" or user == "3"):
print(user, " is not a valid answer. Please try again \n")
user = input("Pick a number and enter the row it is in: ")
if user == "1":
pack = pack3 + pack1 + pack2
elif user == "2":
pack = pack1 + pack2 + pack3
elif user == "3":
pack = pack2 + pack3 + pack1
print("The number you are thinking of is:", pack[10], "\n")
answer = input("Would you like to play again (y/n)? ")
if answer != "y" or answer != "n":
break
print ("Please press 'y' or 'n' and then Enter... ")
if answer == "y":
continue
else:
print ("Thank you for playing!")
break
Just to bring in some context about what this is about, this is a 21 Cards Trick program. Try it out if you want.
Edit: Also what's happening when the question at the end is asked is that it's not really restarting the program when you type 'y'.
Use a control boolean to handle the status of the user involvement.
Also your while loop indentation was incorrect, as Vasilis G. pointed out.
import random
controlFlag = True #add boolean control
while controlFlag == True:
print ("--------------------------------------------------------------------\n")
name = input("Please enter your name: ")
pack = [1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21]
random.shuffle(pack)
print ("Welcome {0}! Hope you have fun playing! \n".format(name))
print("Original deck:", pack, "\n")
print ("--------------------------------------------------------------------\n")
for i in range(3):
pack1 = pack[::3]
pack2 = pack[1::3]
pack3 = pack[2::3]
print("1: ", pack1, "\n")
print("2: ", pack2, "\n")
print("3: ", pack3, "\n")
user = input("Pick a number and enter the row it is in: ")
while not (user == "1" or user == "2" or user == "3"):
print(user, " is not a valid answer. Please try again \n")
user = input("Pick a number and enter the row it is in: ")
if user == "1":
pack = pack3 + pack1 + pack2
elif user == "2":
pack = pack1 + pack2 + pack3
elif user == "3":
pack = pack2 + pack3 + pack1
print("The number you are thinking of is:", pack[10], "\n")
answer = input("Would you like to play again (y/n)? ")
if answer == "y":
controlFlag = True # unnecessary, left in for completeness.
elif answer == 'n':
print ("Thank you for playing!")
controlFlag = False
else:
print('wrong choice')
break
General main loop structure usually goes somewhat like this:
def func():
while True
#run your game or whatever
#ask for input somehow
if input==truthy:
break
func()
I need this program to print out the number of guesses you got right and wrong. I have a dictionary (called ccdict) of cities and countries, e.g. "United Kingdom":"London". This is the code:
def choices (Correct):
list=[Correct]
f=0
cities=ccdict.values()
while f + 1<5:
f=f+1
list.append(cities[random.randint(0, len(cities))])
list.sort()
return list
countries = ccdict.keys()
randcountry = countries[random.randint(0, len(countries))]
print "What is the capital of " + randcountry + "?"
print "If you want to stop this game, type 'exit'"
randlist = choices(ccdict[randcountry])
for i in range(0,5):
print str(i+1) + " - " + randlist[i]
input=raw_input("Give me the number of the city that you think is the capital of " + randcountry + " ")
if input == "exit":
print "Now exiting game!" + sys.exit()
elif randlist[int(input)-1] == ccdict[randcountry]:
print "Correct"
else:
print "WRONG! The capital of " + randcountry + " is " + ccdict[randcountry]
Move your int() until after your if test:
input = raw_input("Give me the number of the city that you think is the capital of " + randcountry + " ")
if input == "exit":
print "Now exiting game!"
sys.exit()
elif randlist[int(input) - 1] == ccdict[randcountry]:
print "Correct"
Note how the above version only converts input to an integer at the last minute.