Using multiple try statements with strings - python

Hi so I am working on a game and my game at the start asks the user if they want the rules to the game (y/n). I'm using if statements and else for this, so if user puts in y print rules and if user puts in n start game etc...it works fine, until the user puts in an integer or a word or something python doesn't recognize and it just goes and uses the else statement. My game is a math game so I used try statements before that if the user punched in something that's not a number it tells the user "Invalid, try again". The problem I'm having now is how to tell python to try multiple things...
I tried using try x = 'y' or x = 'n' but it says you can't give try multiple operations or something
Please help,
Cheers

You might want to use the following:
if inp=="Option1":
...
elif inp=="Option2":
...
elif inp=="Option3":
...
else:
print "Not known command"

You need a while loop that will keep taking input until the user inputs either y or n
while True:
inp = raw_input("Add intruction here")
if inp == "y":
# code here
elif inp == "n":
# code here
else:
print "Invalid input"

Related

Struggling with loops and statements

So I've almost finished a calculator but after giving the results, I want it to ask if I'm still gonna use it.
At the beginning of the code I have this loop to make it start again unless I typed 'n'.
# LOOP TO MAKE IT STAY ON
import sys
from colorama import init
from colorama import Fore, Back, Style
init()
while True:
Then the rest of the code which is finished goes on.
Then, at the end, I've tried this:
answer = input()
def badanswer():
if answer != "y" or "n":
return True
else:
return False
while badanswer is True:
print ("Wrong answer")
answer = input(("Wanna keep using the calculator? y/n "))
if badanswer is False:
if answer == "y":
continue
else:
break
sys.exit()
Somehow when I test it I type a random letter (not y or n) and the program continues... What I am missing here? I'm pretty new to python so forgive my mistakes! Thanks.
One problem is the
if answer != "y" or "n":
"or" is a logical operator, and does not allow you to "double" a != comparison like you are trying to do. The actual meaning of this statement is if answer is not "y", or if "n", and "n", like any nonempty string, is always True in boolean context.
You want
if answer not in ("y", "n"):
You also need to actually call badanswer() by adding the parentheses.
There's also no reason to add the if True to the loop condition — while badanswer() does the same thing.
badanswer is a function, not a boolean. You need to call the function and get its return value, like so: if badanswer() is True
However, your logic for exiting the program is needlessly contrived. You don't need the badanswer function at all. Just get the input from the user and check whether it is 'y' or 'n'.
while True: # loop for exit prompt
answer = input("Wanna keep using the calculator? y/n ").lower()
# using .lower() to permit 'Y' and 'N' as well
if answer == "n":
sys.exit()
elif answer == "y":
break
# exits from the 'exit prompt' loop,
# returns to the outside calculator loop
else:
print("Bad answer!")
Note: As mentioned in the comments, sys.exit() is a pretty cutthroat way to exit your program. You can do it more gracefully by modifying a variable that is checked by the outer calculator loop; e.g., initialize a variable keep_running = True, run the main loop with while keep_running: (...) and if the user requests to exit from the calculator, set keep_running = False so that the main loop exits.

How do I continue a python program after a while loop exits?

I have a python3 program that guesses the last name of an individual based on the input of the user. But I figured out how to break if the user answer now, but when the user says yes it just re-enter the loop again with the same initial question.
while True:
answer = input('Do you want me to guess your name? yes/no :')
if answer.lower() == 'no':
print("Great")
else:
time.sleep(2)
exit('Shame, thank you for playing')
lastname = input('Please tell me the first letter in your surname?').lower()
time.sleep(2)
DEMO - If the user answer 'yes'
Do you want me to guess your name? yes/no :
Great
Do you want me to guess your name? yes/no :
Great
Do you want me to guess your name? yes/no :
etc.
So basically I want the program to exit on no, but continue on yes with the next question which is "Please tell me the first letter in your surname?"
Any idea?
I through after picking up some suggestion here, that I could use a while loop, but as the question stands, I did not get it right.
Please answer in a not so technical way, as my knowledge of python is very limited, still trying to learn.
I misunderstood the problem at first. You actually need to break the while loop when the user says Yes, so you can proceed to the 2nd question. And using an exit is fine when he says No, just remember that it will exit the whole program, so if you want to do something else after he says no, it might be better to use return and put them into functions.
Your code should be more or less like this:
import time
while True:
answer = input('Do you want me to guess your name? yes/no :')
if answer.lower() == 'yes':
print("Great")
break # This will break the actual loop, so it can pass to next one.
elif answer.lower() == 'no':
# I recommend printing before so if it's running on a terminal
# it doesn't close instantly.
print('Shame, thank you for playing')
time.sleep(2)
exit()
# I suggest adding this else because users don't always write what we ask :P
else:
print('ERROR: Please insert a valid command.')
pass # this will make it loop again, until he gives a valid answer.
while True:
# code of your next question :P repeat proccess.
Feel free to ask any question you have about the code :)
As CoryKramer in the comments pointed out, use break instead of exit. Exit is a python function that exits the process as a whole and thus it shuts down the interpreter itself.
Break will close the closest loop it belongs to. Thus if you have two while loops, one written inside the other. A break will only close the inner while loop.
In general your code will go something like this
while True:
answer = input('Do you want me to guess your name? yes/no :')
if answer.lower() == 'yes':
print("Great")
lastname = input('Please tell me the first letter in your surname?').lower()
time.sleep(2)
else:
time.sleep(2)
print("Thank you for playing!")
break
This will keep looping as long as the user keeps entering yes.
if you want to you an infinite while loop you need to control your loop state. Also i created a SurnameFunc. Using seperate functions is more readable for big projects.
def SurnameFunc():
return "Test Surname ..."
State= 0
lastname_tip = ""
while(True):
if(State== 0):
answer = input('Do you want me to guess your name? yes/no :')
if(answer == 'no') :
print ("You pressed No ! - Terminating Program ...")
break
else:
State = 1
elif(State == 1):
lastname_tip = input('Please tell me the first letter in your surname?').lower()
State = 2
elif(State == 2):
print ("Your Surname is ..." + SurnameFunc())
State = 0
print ("Program Terminated !")

How to reprint the

How cab I repeat the raw_input sentence because every time I or the user answers the question written the python say press any key to continue but I want to repeat the question to know if the user want to do any thing else using the programme I wish you can help me.
You can use this simple code for that
x = raw_input("Enter a command or q to quit")
while ( x != 'q' ) :
## your code goes.
x = raw_input("Enter a command or q to quit")
This will recursively ask the user for input until he decides to quit.
You mean something as follows?
bool = True
while bool:
input = raw_input(query) #Get raw_input
if condition: #check if you should end the loop or ask again
bool = False #end loop
#your code here
bool is used as a boolean to check if the condition has happened, should call it something else such as run_loop or something like that.

Why is this function creating an infinite loop?

Why is this creating an infinite loop? And if it isn't creating one, why does the program freeze up? Not like IDLE stops responding, It just stops like I created a infinite loop and the only thing it does is input(). Try the code out to see what I mean.
(also, tell me if the for's are correct in the comments please)
Accounts = {}
def create_account(x,y,z,a):
global Accounts
Checked = False
while Checked == False:
if x in Accounts:
print("Sorry, that name has already been taken")
print("Please choose a new name")
x = input()
for dictionary in Accounts:
for key in dictionary:
if a in key:
print("Sorry, password is invalid or not avalible")
print("Please choose a new password")
a = input()
Accounts[x] = {"Proggress":y,"Points":z,"Pass":a}
print(Accounts[x])
Your code creates an infinite loop because there is nothing to stop it.
while checked == False will do exactly what it sounds like, it will loop over the code over and over until checked = True OR until you break
break will simply stop the loop, allowing the program to finish.
checked = True will also stop the loop
I think that what you are trying to do is something like this:
This code is untested
Accounts = {}
def create_account(x,y,z,a):
global Accounts
Checked = False
while Checked == False:
if x in Accounts:
print("Sorry, that name has already been taken")
print("Please choose a new name")
x = input()
else:
passwordOk = True
for dictionary in Accounts:
for key in dictionary:
if a in key:
passwordOk = False
break
if not passwordOk:
break
if not passwordOk:
print("Sorry, password is invalid or not avalible")
print("Please choose a new password")
a = input()
else:
Checked = True # this is the important part that you missed
Accounts[x] = {"Proggress":y,"Points":z,"Pass":a}
print(Accounts[x])
Just for you to know, your code can be optimized. I tried to solve your issue by modifying as minimum code as possible, so that you could understand the problem
There are two issues causing this.
As you say,
the print() is before the input(), and the print never outputs, so it doesn't get that far
However, let's take a step back: the print statements are inside the block if x in Accounts:. At the very first line, you set Accounts to be an empty dictionary (Accounts = {}), so no matter what x is, at that point, x in Accounts will never be true - there's nothing in it.
Now, you do have a line that adds items to Accounts:
Accounts[x] = {"Proggress":y,"Points":z,"Pass":a}
However, as other people have pointed out, you'll never get here - it's outside the loop, and the loop never exits because Checked is never set to True, nor is a break called.
Your program then is essentially just going through the same few steps that don't do anything:
Does Checked == False? Yep, continue the loop.
Is x in Accounts? Nope, skip this block.
For every dictionary in Accounts, do some stuff, but Accounts is empty, so I don't need to do anything.
Does Check == False? Yep, continue the loop.

Python not responding in loop

Here is my code:
from random import randint
doorNum = randint(1, 3)
doorInp = input("Please Enter A Door Number Between 1 and 3: ")
x = 1
while (x == 1) :
if(doorNum == doorInp) :
print("You opened the wrong door and died.")
exit()
now, that works fine, if I happen to get the unlucky number.
else :
print("You entered a room.")
doorNum = randint(1, 3)
This is the part where it stops responding entirely. I am running it in a bash interactive shell (Terminal, on osx). It just ends up blank.
I am new to programming in Python, I spent most of my time as a web developer.
UPDATE:
Thanks #rawing, I can not yet upvote (newbie), so will put it here.
If you are using python3, then input returns a string and comparing a string to an int is always false, thus your exit() function can never run.
Your doorInp variable is a string type, which is causing the issue because you are comparing it to an integer in the if statement. You can easily check by adding something like print(type(doorInp)) after your input line.
To fix it, just enclose the input statement inside int() like:doorInp = int(input("...."))
In python3, the input function returns a string. You're comparing this string value to a random int value. This will always evaluate to False. Since you only ask for user input once, before the loop, the user never gets a chance to choose a new number and the loop keeps comparing a random number to a string forever.
I'm not sure what exactly your code is supposed to do, but you probably wanted to do something like this:
from random import randint
while True:
doorNum = randint(1, 3)
doorInp = int(input("Please Enter A Door Number Between 1 and 3: "))
if(doorNum == doorInp) :
print("You opened the wrong door and died.")
break
print("You entered a room.")
See also: Asking the user for input until they give a valid response

Categories