Using a while loop with try catch python - 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

Related

Input from the use in a try/except block

List item
i want to let the user type 1 , 2 or quit otherwise i want to put him to type again one of them. everything works with 1 and 2 but for quit doesn't work, and i also want if he types quit to use sys.exit('message') - this part is from a function where u can choose your difficulty level. also its a hangman game. tanks
Sloved!!
import sys
while True:
difficulty = input("Choose difficulty 1 for easy 2 for hard: ").lower()
try:
if difficulty == '1':
print('Easy game mode is set!')
elif difficulty =='2':
print('Hard game mode is set!')
elif difficulty =='quit':
print('Sheeeeeeeeeeeeeeesh')
except:
continue
if difficulty == '1' or difficulty =='2':
break
elif difficulty == 'quit':
sys.exit('byeeeee')
break
#elif difficulty
else:
print('invalid ')
You are storing the user input in uppercase for difficulty variable.
And in if condition verifying in lowercase.
So remove the upper() from
input("Choose difficulty 1 for easy 2 for hard: ").upper()
try: and except: is probably not what you want to use here because you won't get a ValueError and thus the except does not execute. Maybe try something like:
while True:
difficulty = input("Choose difficulty 1 for easy 2 for hard: ").upper()
if difficulty == '1':
print('Easy game mode is set!')
break
elif difficulty =='2':
print('Hard game mode is set!')
break
elif difficulty =='QUIT':
print('bye')
break
else:
print("you can only choose 1, 2, or quit.")
It breaks the loop when the correct input is given, and keeps looping otherwise.
If you would LIKE to have a ValueError when they enter a wrong input you can use raise like so:
while True:
difficulty = input("Choose difficulty 1 for easy 2 for hard: ").upper()
if difficulty == '1':
print('Easy game mode is set!')
break
elif difficulty =='2':
print('Hard game mode is set!')
break
elif difficulty =='QUIT':
print('bye')
break
else:
print("you can only choose 1, 2, or quit.")
raise ValueError #notice the additional line here

How to make the program go back to the top of the code with a while loop?

I need to include a decrement life counter that has 5 lives. I need to use a while loop and once the player loses a life it needs to send them back to the choice between going left and right in the code. I am new to python so I am not very familiar with it, any help is appreciated.
answer = input("Do you want to go on an adventure? (Yes/No) ")
if answer.lower().strip() == "yes":
x=5
while x > 0:
print("You have ",x,"lives left.")
if x > 0:
break
x-=1
if x == 0:
break
answer= input("You are lost in the forest and the path splits. Do you go left or right? (Left/Right) ").lower().strip()
if answer == "left":
answer = input("An evil witch tries to cast a spell on you, do you run or attack? (Run/Attack) ").lower().strip()
if answer == "attack":
print("She turned you into a green one-legged chicken, you lost!")
elif answer == "run":
print("Wise choice, you made it away safely.")
answer = input("You see a car and a plane. Which would you like to take? (Car/Plane) ").lower().strip()
if answer == "plane":
print("Unfortunately, there is no pilot. You are stuck!")
elif answer == "car":
print("You found your way home. Congrats, you won!")
elif answer != "plane" or answer != "car":
print("You spent too much time deciding...")
else:
print("You are frozen and can't talk for 100 years...")
elif answer == "right":
import random
num = random.randint(1, 3)
answer = input("Pick a number from 1 to 3: ")
if answer == str(num):
print("I'm also thinking about {} ".format(num))
print("You woke up from this dream.")
elif answer != num:
print("You fall into deep sand and get swallowed up. You lost!")
else:
print("You can't run away...")
else:
print("That's too bad!")
You should try to add comments to your code, it will help you and others as well.
I think for getting user answer, you should use a different variable. It will make things easier.
I removed the following code, it didn't make any sense to me.
while x > 0:
print("You have ",x,"lives left.")
if x > 0:
break
x-=1
if x == 0:
break
--
This is the code, which works:
# Try to write imported modules at the top, it's a good practice.
import random
# Start the game
answer_start = input("Do you want to go on an adventure? (Yes/No) ")
# user chooses to play
if answer_start.lower().strip() == "yes":
lives=5
# function for displaying the lives
def display_lives():
print("You have ",lives,"lives")
#display lives
display_lives()
# As long lives are more than 0, this will keep going.
while lives>0:
#First choice
answer1= input("You are lost in the forest and the path splits. Do you go left or right? (Left/Right) ").lower().strip()
#User chooses left
if answer1 == "left":
answer2 = input("An evil witch tries to cast a spell on you, do you run or attack? (Run/Attack) ").lower().strip()
if answer2 == "attack":
print("She turned you into a green one-legged chicken, you lost!")
lives=lives-1
display_lives()
# User is running away
elif answer2 == "run":
print("Wise choice, you made it away safely.")
answer3 = input("You see a car and a plane. Which would you like to take? (Car/Plane) ").lower().strip()
if answer3 == "plane":
print("Unfortunately, there is no pilot. You are stuck!")
elif answer3 == "car":
print("You found your way home. Congrats, you won!")
elif answer3 != "plane" or answer3 != "car":
print("You spent too much time deciding...")
else:
print("You are frozen and can't talk for 100 years...")
elif answer1 == "right":
num = random.randint(1, 3)
answer4 = input("Pick a number from 1 to 3: ")
if answer4 == str(num):
print("I'm also thinking about {} ".format(num))
print("You woke up from this dream.")
elif answer4 != num:
print("You fall into deep sand and get swallowed up. You lost!")
lives=lives-1
else:
print("You can't run away...")
#Player chose not to play or player out of lives.
else:
print("That's too bad!")

If else statement does not recognize the lists from input

I am learning how to make a text typed game in python. I could not get it to work. eventhough there is a water in my list (bag) it would still end the game eventhough i have it. Please help me
...
bag = [ ]
sword = ("sword")
water_bucket = ("water")
dead = False
ready = input("are you ready? ")
while dead == False:
print("this is whats inside your bag ")
print(bag)
if ready == "yes":
print("let's start our journey ")
print(
"It was a beautiful morning, you woke up in a dungeon, your quest is to find a dragon and slay his head off")
while dead == False:
if dead == True:
break
else:
first = input("Choose a path front/back/left/right")
if first == "front":
if bag == "water":
print(" You got safe because of the water bucket")
else:
dead = True
print(" You died in a hot lava")
elif first == "back":
ask2 = input("There is a sword, do you want to take it?")
if ask2 == "yes":
bag.append(sword)
print("You got a sword")
elif ask2 == "no":
print("you did not take it and went back to start")
else:
print("please answer with yes or no")
elif first == "left":
if bag == "sword":
print("You fought a dragon and win")
elif bag != "sword":
print("You fought a dragon but lost because you do not have a weapon")
dead = True
elif first == "right":
ask3 = input("Water Buckets! might be helpful, take it? ")
if ask3 == "yes":
bag.append(water_bucket)
print("You got a water bucket")
print(bag)
elif ask3 == "no":
print("you did not take it and went back to start")
else:
print("please answer with yes or no")
else:
print("not a path")
else:
print("See you next time, A journey awaits")
...
It is a text based im learning right now

What is wrong with this piece of code [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()

Python - Looping an Input [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
python, basic question on loops
how to let a raw_input repeat until I wanna quit?
I would like some help with Python please.
I'm writing a program in Py2.7.2, but am having some issues.
What I have so far is something like this:
choice = raw_input("What would you like to do")
if choice == '1':
print("You chose 1")
elif choice == '2':
print("You chose 2")
elif choice == '3':
print("You chose 3")
else:
print("That is not a valid input.")
But after the user chooses either 1, 2, 3 or 4, the program automatically exits. Is there a way that I can loop the program back up so that it asks them again "What would you like to do?"; and so that this continues to happen, until the user exits the program.
You can accomplish that with a while loop. More info here:
http://wiki.python.org/moin/WhileLoop
Example code:
choice = ""
while choice != "exit":
choice = raw_input("What would you like to do")
if choice == '1':
print("You chose 1")
elif choice == '2':
print("You chose 2")
elif choice == '3':
print("You chose 3")
else:
print("That is not a valid input.")
Use a While Loop -
choice = raw_input("What would you like to do (press q to quit)")
while choice != 'q':
if choice == '1':
print("You chose 1")
elif choice == '2':
print("You chose 2")
elif choice == '3':
print("You chose 3")
else:
print("That is not a valid input.")
choice = raw_input("What would you like to do (press q to quit)")
You need a loop:
while True:
choice = raw_input("What would you like to do")
if choice == '1':
print("You chose 1")
elif choice == '2':
print("You chose 2")
elif choice == '3':
print("You chose 3")
else:
print("That is not a valid input.")
Personally this is how i would suggest you do it. I would put it into a while loop with the main being your program then it runs the exit statement after the first loop is done. This is a much cleaner way to do things as you can edit the choices without having to worry about the exit code having to be edited. :)
def main():
choice=str(raw_input('What would you like to do?'))
if choice == '1':
print("You chose 1")
elif choice == '2':
print("You chose 2")
elif choice == '3':
print("You chose 3")
else:
print("That is not a valid input.")
if __name__=='__main__':
choice2=""
while choice2 != 'quit':
main()
choice2=str(raw_input('Would you like to exit?: '))
if choice2=='y' or choice2=='ye' or choice2=='yes':
choice2='quit'
elif choice2== 'n' or choice2=='no':
pass

Categories

Resources