Try Except Block not passing after correct input - python

I'm new to Python and coding in general, and ran into a bit of a bug in my code. Whenever i type in the wrong input in my Try/Except code block, the console prints "Invalid input" However, whenever i type in the correct phrase in the console, it still says "Invalid input". I looked online to try to fix this issue (notated with ##) with these lines of code, but i still get the same issue.
For example, I would type in "Mad Libs" with correct case and everything, and still get "Invalid input" from my != command. Could this be easily fixed by formatting in a different way? This happens with all 3 games.
How can this issue be addressed? Thanks in advance!
def game_selection(): ##
pass ##
while True: ##
try:
playerChoice = input("So, which game would you like to play?: ")
if playerChoice != "Mad Libs":
print("Invalid input")
elif playerChoice != "Guessing Game":
print("Invalid input")
elif playerChoice != "Language Maker":
print("Invalid input")
continue ##
except:
print("Invalid Input")
game_selection() ##
print("Got it! " + playerChoice + " it is!")
sleep(2)
if playerChoice == "Mad Libs":
print("Initializing 'Mad Libs'.")
sleep(.5)
print("Welcome to MadLibs, " + playerName + "! There are a few simple rules to the game.")
print("All you have to do is enter in a phrase or word that is requested of you.")
playerReady = input("Ready to begin? Y/N")

Because you asked it to answer invalid input anyway in this code
While True: ##
try:
playerChoice = input("So, which game would you like to play?: ")
if playerChoice != "Mad Libs":
print("Invalid input")
elif playerChoice != "Guessing Game":
print("Invalid input")
elif playerChoice != "Language Maker":
print("Invalid input")
continue ##
except:
print("Invalid Input")

The thing is, this code will not work because if I enter "Mad Libs" the first if will not pass and so it will pass to all the others elif. So you can't take this approach.
What I advice you to do is to check if the playerChoice string is in an array
from time import sleep
while True:
playerChoice = input("So, which game would you like to play?:")
allowedGames = ["Mad Libs", "Guessing Game", "Language Maker"]
if playerChoice not in allowedGames:
print('Invalid input!')
else:
break
print("Got it! " + playerChoice + " it is!")
sleep(2)
if playerChoice == "Mad Libs":
print("Initializing 'Mad Libs'.")
sleep(.5)
print("Welcome to MadLibs, " + playerName + "! There are a few simple rules to the game.")
print("All you have to do is enter in a phrase or word that is requested of you.")
playerReady = input("Ready to begin? Y/N")

Related

Validate User Input I don't want it to start over when I say no after putting in the wrong input

I am trying to validate a users input by using while True:
When I type the wrong input it tells the user invalid, but when I say no I don't want to continue the code still start's over when I want it to exit the program. How would I fix this?
Output text to the console
def play_again():
print("")
incorrect = ""
while incorrect != "yes" and incorrect != "no":
incorrect = input("Not a valid entry.\n"
"Please choose yes or no:\n").lower()
if "y" in incorrect:
break
elif "n" in incorrect:
break
return incorrect
while True:
print("")
intro()
# Output text to the console
print("")
make_choice()
accept = input("would you like to play again? \n"
"Type yes or no: ").lower()
if 'n' in accept:
print_pause("Thanks for playing!")
break
elif 'y' in accept:
print_pause("Awsome! Lets play again.")
else:
play_again()
All of the logic should be in the play_again function. It can return True if the user wants to play again, else False.
def play_again():
accept = input("would you like to play again?\nType yes or no: ").lower()
while True:
if accept in ["y", "yes"]:
print_pause("Awesome! Lets play again.")
return True
elif accept in ["n", "no"]:
print_pause("Thanks for playing!")
return False
accept = input("Not a valid entry.\nPlease choose yes or no:\n").lower()
while True:
print("")
intro()
print("")
make_choice()
if not play_again():
break

Is there anyway to use 'return' outside a function block to go back to my variable from 'else'?

I've been facing this problem for a bit now. I know that the 'return' command can't work outside a function, but is there an alternative to this or is there a need to define a new function?:
print("Are you", userage(), "years old?")
userinput = input()
if userinput == "yes":
print("Ok, lets get on with the program")
elif userinput =="no":
print("Oh, let's try that again then")
userage()
else:
print("please answer yes or no")
return userinput
Btw, sorry for all the mistakes I make. I'm still a beginner.
You need to use a while loop here:
while (True):
userinput = input("Are you xxx years old?\n")
if userinput == "yes":
print("Ok, lets get on with the program")
break
elif userinput == "no":
print("Oh, let's try that again then")
else:
print("please answer yes or no")
The loop will ever only break when someone types in yes.

Create Loop in if / else statement

I am trying to loop this function in the case the 'else' is reached but I'm having difficulties.
I tried while False and it doesn't do the print statements, I guess it kicks out of the function as soon as it ends up being false. I tried the True and I think that's the way to go but when it hits Else it just repeats. I'm thinking... maybe I need to do another Elif for the repeat of the whole function and the else as just an escape if needed.
def login(answer):
while False:
if answer.lower() == "a":
print("You selected to Login")
print("What is your username? ")
break
elif answer.lower() == "b":
print("You selected to create an account")
print("Let's create an account.")
break
else:
print("I don't understand your selection")
while False:
should be
while True:
otherwise you never enter the loop
Further:
else:
print("I don't understand your selection")
should be:
else:
print("I don't understand your selection")
answer = input("enter a new choice")
You might even refactor your code to call the function without parameter:
def login():
while True:
answer = input("enter a choice (a for login or b for account creation")
if answer.lower() == "a":
print("You selected to Login")
print("What is your username? ")
break
elif answer.lower() == "b":
print("You selected to create an account")
print("Let's create an account.")
break
else:
print("I don't understand your selection")

Menus Looping on Python

for an assignment, I made a menu and must have it work in a way to execute multiple functions. However, the problem is that when I use the menu and put in an answer that doesn't exist, I cannot get it to work correctly. So when I re-enter an option number for "Incorrect option, try again: ", I do not get the number re-evaluated to execute. Since my code is far from finished, right now I want to be able to choose "4" as an input and get "Incorrect option, try again" as an output and input "1" into this to get the output "Choose the level of difficulty".
def main_menu():
print(10*"=","GAME",10*"=",'\n')
print("1. Choose level of difficulty ")
print("2. Start Game")
print("3. Exit the Game",'\n')
print("Current Difficulty: /5")
print("Highest Score Reached:",'\n')
option=input("Enter an option: ")
return option
def user_input():
while True:
try:
if option==1:
difficulty()
break
elif option==2:
start()
break
elif option==3:
exit()
break
except:
option=input("Incorrect option, try again: ")
def difficulty():
d=int(input("Choose level of difficulty: "))
if 1<=d<=5:
start()
else:
int(input("Incorrect option, try again: "))
#difficulty()
return d
Here a is modified version of your code which I believe does what you are looking for.
def main_menu():
print(10 * "=", "GAME", 10 * "=", '\n')
print("Current Difficulty: /5")
print("Highest Score Reached:", '\n')
while True:
print("1. Choose level of difficulty")
print("2. Start Game")
print("3. Exit the Game", '\n')
try:
option = int(input("Enter an option: "))
if option == 1:
difficulty()
elif option == 2:
start()
elif option == 3:
return
else:
print("Incorrect option, try again!")
except ValueError:
print("Invalid option.")
def difficulty():
try:
d = int(input("Choose level of difficulty: "))
if 1 <= d <= 5:
print(d)
start()
else:
print("Incorrect option, try again.")
except ValueError:
print("Invalid value.")
def start():
print("Starting game...")
if __name__ == "__main__":
main_menu()
Let me know if anything is misunderstood or mistaken.

Python Syntax Error: expected an intended block

So first i clicked on Run Module
Then this came up
My code
import time
print("First we need to know you.")
print("Enter your name please.")
time.sleep(2)
name = input("Name: ")
print("Welcome, " + name + "!")
time.sleep(3)
criminal = input("Are you a criminal?: ")
if criminal=='Y':
Right here it highlights print as red
print('Oh no')
elif criminal=='N':
print('Thank god!')
You need to indent after an if and the elif:
if criminal=='Y':
print('Oh no')
elif criminal=='N':
print('Thank god!')
Also, don't indent after the import:
import time
print("First we need to know you.")
You have to indent the print('Oh no'):
if criminal=='Y':
print('Oh no')
elif criminal=='N':
print('Thank god!')

Categories

Resources