What is wrong with this piece of code [Python]? - python

# For updating the version!
version = "0.1"
# For game start!
from choice1 import choice1
# insert import functions from checkpoints choices here!
def gamemenu():
print("Welcome to the RTG!")
# Starts the game
print("1. START!")
# Goes to an earlier checkpoint
print("2. CHECKPOINTS!")
# Views the "about' page
print("3. ABOUT")
# Shows my website address!
print("4. INFO ABOUT CREATOR")
# Exits the game
print("5. EXIT")
# The user input!
option = input("Make your choice, buddy! "
if option == "1":
choice1()
# elif option == "2":
# Not added yet
elif option == "3":
print("Random Text RPG, version %s" % version)
print("This is just a random game made by me for fun")
print("Please dont't take offence :(")
elif option == "4":
print("Made by Lightning Bolt."))
elif option == "5":
break
else:
print("ERROR: invalid option")
menu()
menu()
Hello everyone,
I am a beginning programmer and I have encountered a problem which I am inable to solve. When I run my program in the Python 3 shell it says invalid syntax and marks the ":" in line 1 red, which means that there is something wrong there. With all other if/else/ifelse statements it doesn't say that the : is invalid syntax. If I remove the ":" it marks choice1() in red for improper syntax, while it's indented with exactly 4 spaces.
I really have no idea what's wrong with the code, thanks for anyone who helps me!
here is a screenshot: http://imgur.com/wuWMa0L (indentation and such)

Close the parenthesis on the line that gets input from the user
Remove the extra parenthesis under elif option == "4"
Remove the break statement, there's no loop there
Code:
# For updating the version!
version = "0.1"
# For game start!
from choice1 import choice1
# insert import functions from checkpoints choices here!
def gamemenu():
print("Welcome to the RTG!")
# Starts the game
print("1. START!")
# Goes to an earlier checkpoint
print("2. CHECKPOINTS!")
# Views the "about' page
print("3. ABOUT")
# Shows my website address!
print("4. INFO ABOUT CREATOR")
# Exits the game
print("5. EXIT")
# The user input!
option = input("Make your choice, buddy! ") #you missed a closing parenthesis here :D
if option == "1":
choice1()
# elif option == "2":
# Not added yet
elif option == "3":
print("Random Text RPG, version %s" % version)
print("This is just a random game made by me for fun")
print("Please dont't take offence :(")
elif option == "4":
print("Made by Lightning Bolt.") # there was an extra paren here
elif option == "5":
pass #as #Padraic mentioned, there should be no break statement
else:
print("ERROR: invalid option")
menu()
menu()

Related

Menus and submenus in Python

I am a complete beginner in learning Python. Currently working on an assignment and having issues in creating menu with submenus.I am trying to connect functions properly and make my program work.
How can I make my submenu work? Output doesnt show the submenu options.
type def display_header():
main = "Main Menu"
txt = main.center(90, ' ')
print('{:s}'.format('\u0332'.join(txt)))
print("Please choose an option from the following menu:")
print("I. Invitee's Information")
print("F. Food Menu")
print("D. Drinks Menu")
print("P. Party Items Menu")
print("Q. Exit")
def get_user_choice():
choice = input("Enter your choice: ")
return choice
def invitees_menu():
invitees_menu()
while True:
choice = invitees_menu()
if choice == "a":
enter_invitee()
if choice == "e":
edit_invitee()
if choice == "v":
drinks_menu()
if choice == "b":
display_header()
print("Invitees' Information Menu")
print("Please choose an option from the following menu:")
print("A. Add new invitee information")
print("E. Edit existing invitee information")
print("V. View all invitees")
print("B. Go back to main menu")
choice = input("Enter your sub-menu choice: ")[0].lower
return choice
if __name__ == "__main__":
display_header()
while True:
choice = get_user_choice()
if choice == "i":
invitees_menu()
if choice == "f":
food_menu()
if choice == "d":
drinks_menu()
if choice == "p":
party_menu()
if choice == "q":
print ("Thank you for using the program!")
break
I might be wrong in understanding the code, but here's what I think's happened.
when you call your invitees_menu function it immediately calls itself. This breaks a rule of recursion (a function calling itself) and causes an infinite loop of just calling the start of the function over and over again. Which gives us this error:
RecursionError: maximum recursion depth exceeded
So first i'd remove the first invitees_menu line completely. Then in the while loop you're calling the invitees_menu again. This is again the same problem because each time you call the function, it will call itself again and never get to returning any item. Here i've replaced it with:
print("Invitees' Information Menu")
print("Please choose an option from the following menu:")
print("A. Add new invitee information")
print("E. Edit existing invitee information")
print("V. View all invitees")
print("B. Go back to main menu")
choice = input("Enter your sub-menu choice: ")[0].lower
You then have the problem of never actually leaving the while True loop. Since entering B should break out and then go back to the main loop in the __main__ call, so i replaced the display_header with break.
Finally, the last few smaller things are:
removing the "type" at line 1
moving the display header in main inside the while loop
fixing up the irregular tab structure in invitees_menu
And here it is
def display_header():
main = "Main Menu"
txt = main.center(90, ' ')
print('{:s}'.format('\u0332'.join(txt)))
print("Please choose an option from the following menu:")
print("I. Invitee's Information")
print("F. Food Menu")
print("D. Drinks Menu")
print("P. Party Items Menu")
print("Q. Exit")
def get_user_choice():
choice = input("Enter your choice: ")
return choice
def invitees_menu():
while True:
print("Invitees' Information Menu")
print("Please choose an option from the following menu:")
print("A. Add new invitee information")
print("E. Edit existing invitee information")
print("V. View all invitees")
print("B. Go back to main menu")
choice = input("Enter your sub-menu choice: ")[0].lower()
if choice == "a":
enter_invitee()
if choice == "e":
edit_invitee()
if choice == "v":
drinks_menu()
if choice == "b":
break
return choice
if __name__ == "__main__":
display_header()
while True:
choice = get_user_choice()
if choice == "i":
invitees_menu()
if choice == "f":
food_menu()
if choice == "d":
drinks_menu()
if choice == "p":
party_menu()
if choice == "q":
print ("Thank you for using the program!")
break
I suggest as first step to clean up the mess with recursive function calls in following section:
def invitees_menu():
invitees_menu()
while True:
choice = invitees_menu()
Next step in cleaning up the mess would be to remove the entire unnecessary parts of the code preventing the sub-menu from showing up when calling invitees_menu().

Using a while loop with try catch python

I'm trying to catch an invalid input by the user in this function when the user runs the program. The idea is to use a try,exception block with a while loop to ensure that the code is continuously run until a valid input is made by the user, which is 1-5.
def door_one():
print("This door has many secrets let's explore it")
print("\nMake a choice to discover something")
print("1 2 3 4 5")
while True:
explore = input(" > ")
if explore not in ("1","2","3","4","5"):
raise Exception ("Invalid input")
if explore == "1":
print("You fought a bear and died")
elif explore == "2" or explore == "3":
print("You become superman")
elif explore == "4":
print(f"Dance to save your life or a bear eats you")
suffer("HAHAHAHAHAHAHAHA!!!!!!")
elif explore == "5":
a_file = input("Please input a file name > ")
we_file(a_file)
suffer("HAHAHAHAHAHAHAHA!!!!!!")
I would advise against using exceptions for controlling flows.
Instead, I would keep iterating until the value is correct and use a return statement to indicate I'm done.
def door_one():
print("This door has many secrets let's explore it")
print("\nMake a choice to discover something")
print("1 2 3 4 5")
while True:
explore = input(" > ")
if explore not in ("1","2","3","4","5"):
continue
if explore == "1":
print("You fought a bear and died")
elif explore == "2" or explore == "3":
print("You become superman")
elif explore == "4":
print(f"Dance to save your life or a bear eats you")
suffer("HAHAHAHAHAHAHAHA!!!!!!")
elif explore == "5":
a_file = input("Please input a file name > ")
we_file(a_file)
suffer("HAHAHAHAHAHAHAHA!!!!!!")
return

Python Redirecting

So I am trying to make a Password checker and generator. So first i need to make a menu to tell if the user wants to check or generate or password. But I'm having a bit of a problem to redirect the user to their choice.
I've tried to use this 'if main = name' but that doesn't even work. I've also tried to place the 'def' above the all the other text. But wouldn't work because it would display that def first instead of displaying the menu
import sys, os
def mainmenu():
print()
print("________________________________________________________")
print("Hello and welcome to the password checker and generator.")
print("________________________________________________________")
input()
print("Mainmenu")
input()
print("Press 1 to Check a password.")
print("Press 2 to Generate a password.")
print("Press 3 to quit.")
UserOp = int(input("What is your choice?:"))
if UserOp == 1:
checkpass()
elif UserOp == 2:
generatepass()
elif UserOp == 3:
sys.exit(0)
else:
print("This option is seen to be invalid.")
mainmenu()
def checkpass():
print()
print("You have chosen to check a password.")
def generatepass():
print()
print("You have chosen to generate a password.")
So what I'm trying to re-arrange or add code to make the program display the menu first then redirect the user to their designated options.
Unless you just typed it in wrong on stackoverflow it looks like none of your initial print options are in the mainmenu function
It’s looks at tho the options are also outside of the functions and mix in with your other functions
Check your indentation, pieces of your code are out of places where they should be.
import sys, os
def mainmenu():
print()
print("________________________________________________________")
print("Hello and welcome to the password checker and generator.")
print("________________________________________________________")
input()
print("Mainmenu")
input()
print("Press 1 to Check a password.")
print("Press 2 to Generate a password.")
print("Press 3 to quit.")
UserOp = int(input("What is your choice?:"))
if UserOp == 1:
checkpass()
elif UserOp == 2:
generatepass()
elif UserOp == 3:
sys.exit(0)
else:
print("This option is seen to be invalid.")
mainmenu()
def checkpass():
print()
print("You have chosen to check a password.")
def generatepass():
print()
print("You have chosen to generate a password.")
if __name__ == '__main__':
mainmenu()

I'm making a text based adventuere game in python and trying to add a third option but it's not working

I'm trying to make a simple text adventure game with three choices. But I can't seem to figure out why this isn't working.
This is the code I have been working on:
#Text based medieval adventure game
#Imported libraries are required
import random
import time
def displayWelcome():
print ("\nText adventure game\n")
print ("Welcome to the medieval adventure game!")
print ("You will have many choices through out this game")
print ("Be sure to pick the right one")
print (" Good Luck! ")
answer = askYesNo("Would you like help with this program? (Y/N): ")
if answer == "Y":
helpForUser()
time.sleep(3)
def askYesNo (question):
# This function will ask you a yes or no question and will keep asking until one is chosen.
# The following function is used to erase the variable response of any values
response = None
while response not in ("Y", "N"):
response = input (question).upper()
return response
def helpForUser():
#This function will show the user some helpful advice if they desire it
print ("\n+++++++++++++++++++++++++++++++++++++++ Help +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++")
print ("This game is a adventure text based game set in the medieval times")
print ("You will be asked multiple questions with a yes or no response")
print ("you must answer the questions with the answers supplied to you suches as yes or no")
print ("If you don't answer the q uestion with the given answers it will be repeated untill a valid response occurs")
print ("The program can end when you choose")
print ("++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++")
def displayIntro():
#Displays intro to game
print ("\n It's been a rough day in the wild and you despratly need shelter")
print ("There is currently a war going on and nowhere is safe")
print ("But you intend to find somwhere with food and a bed but it wont be easy...")
print ()
def choosePath(lower,middle,upper):
#This functions allows you to choose between multiple options
path = 0
while path < lower or path > upper:
number = input("What path will you take(" + str(lower) + " - " + str(upper) + ")?: ")
if number.isdigit():
path = int (number)
else:
path = 0
return path
def followPath(chosenPath):
print ("you head down a long road\n")
time.sleep(3)
print ("You come across an abandoned campsite and decide to stay there for the night")
time.sleep(3)
print("You wake up to a sudden sound of voices and begin to realise that this campsite wasn't abandoned...")
time.sleep(3)
print("You start to freak out")
time.sleep(3)
if chosenPath == 1:
print("You grab your sword out and decide to go out the tent")
print ("Four well trained knights surround you")
print ("They strike without any hesitation, you counter two knights trying to hit you from the front as two from behind stab you in the back")
print ("The knights decide to burn your body and leave nothing left of you.\n")
elif chosenPath == 2:
print("You dart out of the tent and head for the exit")
print("All the guards try and get you whilst shooting arrows")
print("Several arrows hit you leaving you injured unable to run")
print ("Suddenly a man with a giant axe appears before you and slices you head off in a clean swoop\n")
else chosenPath == 3:
print("You keep calm and decide to sneak past all the guards")
print ("You're close to the exit when suddenly a guard notices you")
print("He's about to call for back up when you dash right into his chest with your sword, leaving it in him and running out the campsite")
print("You make it to a safe forest and decide to rest\n")
displayWelcome()
playAgain = "Y"
while playAgain == "Y":
displayIntro()
choice = choosePath()
followPath(choice)
playAgain = askYesNo ("Would you like to play again?")
print ("\nBye")
Error Number one: line 63, else should be elif or get rid of the condition "chosenPath == 3:
Current state
else chosenPath == 3:
What it should look like
elif chosenPath == 3:
or
else:
The other error is that nothing ever happens on initialization of choice because you forgot to input the "lower, middle, upper" values.

How do I ask the user if they want to play again and repeat the while loop?

Running on Python, this is an example of my code:
import random
comp = random.choice([1,2,3])
while True:
user = input("Please enter 1, 2, or 3: ")
if user == comp
print("Tie game!")
elif (user == "1") and (comp == "2")
print("You lose!")
break
else:
print("Your choice is not valid.")
So this part works. However, how do I exit out of this loop because after entering a correct input it keeps asking "Please input 1,2,3".
I also want to ask if the player wants to play again:
Psuedocode:
play_again = input("If you'd like to play again, please type 'yes'")
if play_again == "yes"
start loop again
else:
exit program
Is this related to a nested loop somehow?
Points for your code:
Code you have pasted don't have ':' after if,elif and else.
Whatever you want can be achived using Control Flow Statements like continue and break. Please check here for more detail.
You need to remove break from "YOU LOSE" since you want to ask user whether he wants to play.
Code you have written will never hit "Tie Game" since you are comparing string with integer. User input which is saved in variable will be string and comp which is output of random will be integer. You have convert user input to integer as int(user).
Checking user input is valid or not can be simply check using in operator.
Code:
import random
while True:
comp = random.choice([1,2,3])
user = raw_input("Please enter 1, 2, or 3: ")
if int(user) in [1,2,3]:
if int(user) == comp:
print("Tie game!")
else:
print("You lose!")
else:
print("Your choice is not valid.")
play_again = raw_input("If you'd like to play again, please type 'yes'")
if play_again == "yes":
continue
else:
break

Categories

Resources