I'm trying to create a simple script that will will ask a question to which the user will input an answer (Or a prompt with selectable answers could appear?), and the program would output a response based on the input.
For example, if I were to say
prompt1=input('Can I make this stupid thing work?')
I would have something along the lines of
if prompt1='yes':
print('Hooray, I can!')
else prompt1='No':
print('Well I did anyway!')
elif prompt1=#an answer that wouldn't be yes or no
#repeat prompt1
I'm probably going about this the wrong way. Please be as descriptive as possible as this is a learning exercise for me. Thanks in advance!
You are pretty close. Read a good tutorial :)
#!python3
while True:
prompt1=input('Can I make this stupid thing work?').lower()
if prompt1 == 'yes':
print('Hooray, I can!')
elif prompt1 == 'no':
print('Well I did anyway!')
else:
print('Huh?') #an answer that wouldn't be yes or no
while True will loop the program forever.
Use == to test for equality.
Use .lower() to make it easier to test for answers regardless of case.
if/elif/elif/.../else is the correct sequence for testing.
Here's a Python 2 version:
#!python2
while True:
prompt1=raw_input('Can I make this stupid thing work?').lower()
if prompt1 == 'yes':
print 'Hooray, I can!'
elif prompt1 == 'no':
print 'Well I did anyway!'
else:
print 'Huh?' #an answer that wouldn't be yes or no
raw_input is used instead of input. input in Python 2 will tries to interpret the input as Python code.
print is a statement instead of a function. Don't use () with it.
Another example, this time as a function.
def prompt1():
answer = raw_input("Can I make this stupid thing work?").lower()
if answer == 'yes' or answer == 'y':
print "Hooray, I can!"
elif answer == 'no' or answer == 'n':
print "Well I did anyway!"
else:
print "You didn't pick yes or no, try again."
prompt1()
prompt1()
Related
I'm trying to create an extremely simple, basic riddle program where Python asks you if you are ready for the riddle, tells you the riddle, checks your answer and repeats.
My problem is I want to create "multiple" answers for the riddle, so it's less case sensitive. Here's my code:
r1Answer = input('')
if r1Answer == 'Silence' # This is where I tried to put my "and" function r1Answer == 'silence' :
print('Correct!')
else:
print('Not quite.')
In Line 2, I've already tried to put an and function in between the two correct answers in my code.
If you want to account for upper or lower you could do the follow:
r1Answer = input('')
if r1Answer.lower() == 'silence': # This is where I tried to put my "and" function r1Answer == 'silence' :
print('Correct!')
else:
print('Not quite.')
the .lower() function will make the string all lower case to keep everything organized...additionally you were missing a : at the end of your if part of your if/else statement, I want ahead and added it.
You can just use a list with all correct answers -
correct_answers = ['ans1', 'ans2']
if answer in correct_answers:
print('Correct')
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.
Hi I'm new to programming, and ran into some problems while practicing using python.
So basically my task is to create a simple quiz with (t/f) as the answer. So here's my code:
def quiz(question,ans):
newpara = input(question)
if newpara == ans:
print("correct")
else:
print("incorrect")
return(newpara)
quiz_eval = quiz("You should save your notebook: ","t")
print("your answer is ",quiz_eval)
When the user input something, this code prints:
your answer is hi
However, I want it to print "your answer is correct/incorrect".
I'm not sure what has gone wrong here. Any thoughts?
Then you should be returning either "correct" or "incorrect". You function returns the value of the input so it's normal to get that output. Try this:
def quiz(question,ans):
newpara = input(question)
if newpara == ans:
answer= "correct"
else:
answer= "incorrect"
return(answer)
quiz_eval = quiz("You should save your notebook: ","t")
print("your answer is ",quiz_eval)
Note that my answer is just to answer your question and give the output the way you want it. If your program requires to limit the input of the user to either "t" or "f", then you need to add more conditions in your code.
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 !")
This question already has answers here:
Why does "a == x or y or z" always evaluate to True? How can I compare "a" to all of those?
(8 answers)
Closed 6 years ago.
I'm trying to create a text bases dungeon game. Just for fun and practice but I'm having a problem with Python not following my if blocks. The weird thing is that it worked when I first typed it out, but a day later it's not. It's treating as if all conditions are true.
choosing_race = True
while choosing_race == True:
print("options: Human, Elf, Dwarf")
p['race'] = input("Choose Race: ",)
print(p['race'], choosing_race)
if p['race'] == "Elf" or "elf":
print()
print("Elves are nimble, both in body and mind, but their form is frail. They gain Bonuses to Intelligence and Dexterity and a Penalty to Constitution")
print()
confirm_race = input("Are you an Elf? ",)
if confirm_race == "yes" or "Yes":
p['int_mod_r'] = 2
p['dex_mod_r'] = 2
p['con_mod_r'] = -2
choosing_race = False
elif confirm_race == "no" or "No":
print()
print("ok, select a different race")
else:
print()
print("Could not confirm, try again")
The p[race] input shows fine, but I can type anything (example duck) and it acts as if I typed elf. When I ask to confirm_race it's always returning yes. I assume I must have put a typo in there, but I can't find it. I redid all my indenting but still no luck. I'm going to try to restructure with functions and maybe that will help. In the mean time I'd love to know what went wrong here so I can prevent it in the future. Thanks. (I'm using Python 3, on my Nexus 5 phone is case that matters)
You are not getting the behavior you expect from lines like
if p['race'] == "Elf" or "elf":
In this case, "elf" evaluates to true every time. You want to instead write
if p['race'] == "Elf" or p['race'] == "elf":
or more concisely
if p['race'] in ["Elf", "elf"]:
or
if p['race'].upper() == "ELF":