however = ["In converse","On the other hand"]
furthermore = ["To add insult to injury","To add fuel to fire",]
conclusion = ["To ram the point home","In a nutshell"]
def prompt():
answer = str(input("Type either 'however','furthermore' or 'conclusion': "))
return answer
reply()
def reply():
if answer == "however":
print(however)
elif answer == "furthermore":
print(furthermore)
elif answer == "conclusion":
print(conclusion)
else:
prompt()
prompt()
prompt()
What is going on? it just doesnt print when i type in anything
it just skips and doesnt print anything at all
Your reply() function won't be called, because you exit the prompt() function by returning the answer
Here's how this should be done:
however = ["In converse","On the other hand"]
furthermore = ["To add insult to injury","To add fuel to fire",]
conclusion = ["To ram the point home","In a nutshell"]
def prompt():
answer = str(input("Type either 'however','furthermore' or 'conclusion': "))
reply(answer)
return answer
def reply(answer):
if answer == "however":
print(however)
elif answer == "furthermore":
print(furthermore)
elif answer == "conclusion":
print(conclusion)
else:
prompt()
prompt()
prompt()
Related
I am asking a Yes or No prompt to a user as a function and I want to return what the answer was back to the rest of the code.
How could I get the answer from the yesNo() function to figure out if the user would like to run the intro variable/function?
prompt = " >>> "
def yesNo():
answer = input('(Y/N)' + prompt)
i = 1
while i > 0:
if answer == str.lower("y"):
tutorial()
i = 0
elif answer == str.lower('n'):
startGame()
i = 0
else:
print("command not understood. try again.")
def newGame():
print("would you like a tutorial?")
yesNo()
I think you'll want something closer to this:
def get_user_input(choices):
prompt = "Please enter ({}): ".format("/".join(f"'{choice}'" for choice in choices))
while True:
user_input = input(prompt)
if user_input in choices:
break
prompt = "Unsupported command '{}', Try again: ".format(user_input)
return user_input
def main():
print("Would you like a tutorial?")
user_input = get_user_input(["Yes", "No"])
if user_input == "Yes":
tutorial()
startGame()
The function that gets user input should only be responsible for getting user input, and returning the user's provided input to the calling code. It should not have any other side-effects, like starting a tutorial, or starting the game.
To get the answer of the user outside the yesNo() method, you can use return, and then store the returned value in a variable
Like this:
prompt = " >>> "
def yesNo():
i = 1
while i > 0:
answer = input('(Y/N)' + prompt)
if answer == str.lower("y"):
tutorial()
i = 0
elif answer == str.lower('n'):
startGame()
i = 0
else:
print("command not understood. try again.")
return answer
def newGame():
print("would you like a tutorial?")
answer = yesNo()
How can I go about creating a input and output with Y\N (yes or no) function in a question?
My example; if my question is Would you like some food? (Y \ N):, how can I do this and have the answers show Yes, please. or No, thank you. for either choice and then proceed to the next question with the same function?
I thought about using this: valid=("Y": True, "y": True, "N": False, "n": False) but that only shows up as True or False for me, or is there a way to change from True \ False to Yes \ No? or this one:
def user_prompt(yes_no):
while True:
user_input=input(yes_no)
But I'm really not sure how else to proceed with this one, or if there's any other easier solution to this.
I think what you're looking for is a conditional print statement rather than a true/false return statement on the function.
For example:
def user_prompt():
while True:
user_input = input("Would you like some food? (Y \ N)")
print ("Yes, please" if user_input == 'Y' else "No, thank you")
Or, more readable:
def user_prompt():
while True:
user_input = input("Would you like some food? (Y \ N)")
if (user_input == 'Y'):
print("Yes, please")
elif (user_input == 'N'):
print("No, thank you")
I hope I understood your question correctly, you basically check the first letter (incase user enters yes/no) every time the user enters a value and try to verify that if it's Y/N you break the loop if not you keep asking the same question.
def user_prompt(yes_no):
while True:
user_input=input(yes_no)
if user_input[0].lower() == 'y':
print("Yes, please.")
break
elif user_input[0].lower() == 'n':
please("No, thank you.")
break
else:
print("Invalid, try again...")
Not sure if this is the best way, but I have a class based implementation of same
""" Class Questions """
class Questions:
_input = True
# Can add Multiple Questions
_questions = [
'Question 1', 'Question 2'
]
def ask_question(self):
counter = 0
no_of_question = len(self._questions)
while self._input:
if counter >= no_of_question:
return "You have answred all questions"
user_input = input(self._questions[counter])
self._input = True if user_input.lower() == 'y' else False
counter += 1
return "You have opted to leave"
if __name__ == '__main__':
ques = Questions()
print(ques.ask_question())
Firstly there is many ways you can go around this, but I am guessing you found the solution yourself already but here is one that is the best.
def get_yes_no_input(prompt: str) -> bool:
allowed_responses = {'y', 'yes', 'n', 'no'}
user_input = input(prompt).lower()
while user_input not in allowed_responses:
user_input = input(prompt).lower()
return user_input[0] == 'y'
continue = get_yes_no_input('Would you like to proceed? [Y/N]: ')
And there we go.
I am attempting to create a loop which a user can stop at the end of the program. I've tried various solutions, none of which have worked, all I have managed to do is create the loop but I can't seem to end it. I only recently started learning Python and I would be grateful if someone could enlighten me on this issue.
def main():
while True:
NoChild = int(0)
NoAdult = int(0)
NoDays = int(0)
AdultCost = int(0)
ChildCost = int(0)
FinalCost = int(0)
print ("Welcome to Superslides!")
print ("The theme park with the biggest water slide in Europe.")
NoAdult = int(raw_input("How many adults are there?"))
NoChild = int(raw_input("How many children are there?"))
NoDays = int(raw_input("How many days will you be at the theme park?"))
WeekDay = (raw_input("Will you be attending the park on a weekday? (Yes/No)"))
if WeekDay == "Yes":
AdultCost = NoAdult * 5
elif WeekDay == "No":
AdultCost = NoAdult * 10
ChildCost = NoChild * 5
FinalCost = (AdultCost + ChildCost)*NoDays
print ("Order Summary")
print("Number of Adults: ",NoAdult,"Cost: ",AdultCost)
print("Number of Children: ",NoChild,"Cost: ",ChildCost)
print("Your final total is:",FinalCost)
print("Have a nice day at SuperSlides!")
again = raw_input("Would you like to process another customer? (Yes/No)")
if again =="No":
print("Goodbye!")
return
elif again =="Yes":
print("Next Customer.")
else:
print("You should enter either Yes or No.")
if __name__=="__main__":
main()
You can change the return to break and it will exit the while loop
if again =="No":
print("Goodbye!")
break
Instead of this:
while True:
You should use this:
again = True
while again:
...
usrIn = raw_input("Would you like to process another customer? y/n")
if usrIn == 'y':
again = True
else
again = False
I just made it default to False, but you can always just make it ask the user for a new input if they don't enter y or n.
I checked your code with python 3.5 and it worked after I changed the raw_input to input, since input in 3.5 is the raw_input of 2.7. Since you're using print() as a function, you should have an import of the print function from future package in your import section. I can't see no import section in your script.
What exactly doesn't work?
Additionally: It's a good habit to end a command line application by exiting with an exit code instead of breaking and ending. So you would have to
import sys
in the import section of your python script and when checking for ending the program by the user, do a
if again == "No":
print("Good Bye")
sys.exit(0)
This gives you the opportunity in case of an error to exit with a different exit code.
Change this code snippet
if again =="No":
print("Goodbye!")
exit() #this will close the program
elif again =="Yes":
print("Next Customer.")
exit()#this will close the program
else:
print("You should enter either Yes or No.")
I have researched this subject, and cannot find a relevant answer, here's my code:
#Imports#
import random
from operator import add, sub, mul
import time
from random import choice
#Random Numbers#
beg1 = random.randint(1, 10)
beg2 = random.randint(1, 10)
#Variables + Welcoming message#
correct = 0
questions = 10
print ("Welcome to the Primary School Maths quiz!!")
print ("All you have to do is answer the questions as they come up!")
time.sleep(1)
#Name#
print("Enter your first name")
Fname = input("")
print ("Is this your name?" ,Fname)
awnser = input("")
if awnser == ("yes"):
print ("Good let's begin!")
questions()
if input == ("no"):
print("Enter your first name")
Fname = input("")
print ("Good let's begin!")
#Question Code#
def questions():
for i in range(questions):
ChoiceOp = random.randint (0,2)
if ChoiceOp == "0":
print (("What is " +beg1 ,op ,beg2))
begAns = input("")
if int(begAns) == beg1*beg2:
print("That's right -- well done.\n")
correct = correct +1
else:
print("No, I'm afraid the answer is ",begAns)
if ChoiceOp == "1":
print (("What is " +beg1 ,op ,beg2))
begAns = input("")
if int(begAns) == beg1-beg2:
print("That's right -- well done.\n")
correct = correct +1
else:
print("No, I'm afraid the answer is ",begAns)
if ChoiceOp == "2":
print (("What is " +beg1 ,op ,beg2))
begAns = input("")
if int(begAns) == beg1+beg2:
print("That's right -- well done.\n")
correct = correct +1
else:
print("No, I'm afraid the answer is ",begAns)
questions()
If I'm perfectly honest I'm not quite sure what's wrong, I have had many problems with this code that this wonderful site has helped me with, but anyway this code is designed to ask 10 random addition, subtraction and multiplication questions for primary school children any help I am thankful in advance! :D
You have both a function def questions() and a variable questions = 10. This does not work in Python; each name can only refer to one thing: A variable, a function, a class, but not one of each, as it would be possible, e.g. in Java.
To fix the problem, rename either your variable to, e.g., num_questions = 10, or your function to, e.g., def ask_question()
Also note that you call your questions function before it is actually defined. Again, this works in some other languages, but not in Python. Put your def quesitons to the top and the input prompt below, or in another function, e.g. def main().
This question already has answers here:
Why am I getting "IndentationError: expected an indented block"? [duplicate]
(6 answers)
Closed 8 years ago.
Ok, so I have my program but I'm getting an "expected an indent block" and i don't know where it is I believe I have it right but I'm very confused.
##Cave fuction
def cave():
global lvl
global mhp
global exp
while True:
print("Who whould you like to talk to. (Emily(1), James(2), Paco(3)")
talk = int(input("Who to talk to: "))
ptint(" ")
if talk == 1:
#put storie function here
elif talk == 2:
#put train function here
elif talk == 3:
print("Your level is", lvl, "you have", mhp, "and have", exp, "EXP")
else:
amsterdam = 7 #filler
print("Anthing else needed(y/n)")
ant = input("Anthing: ")
if ant == n:
break
else:
mexico = 19 #filler
Put pass (or print statment or anything that executes really) between your if/elif statements. The comments aren't really read as code.
In Python, there is no such thing as empty block like {} in C. If you want block to do nothing, you have to use pass keyword. For example:
if talk == 1:
pass # Put storie function here.
elif talk == 2:
pass # Put storie function here.
This should fix your problem. After line ending with :, next line MUST be intended, and comments do not count to indentation in that respect.
After the condition of if or elif, and after else, an indented block is expected. Something like this:
if condition:
indented_block
elif condition:
indented_block
else:
indented_block
Just a comment as a block:
if condition:
# ...
is not considered, so you have to put something there. One alternative is using a placeholder:
if condition:
pass
pass is a null operation. When it is executed, nothing happens.
You have to put some valid statements inside if-else statements, where you have written put storie function here. Following code will not throw an error as there is some valid statement for each if-else:
def cave():
global lvl
global mhp
global exp
while True:
print("Who whould you like to talk to. (Emily(1), James(2), Paco(3)")
talk = int(input("Who to talk to: "))
ptint(" ")
if talk == 1:
#put storie function here
pass
elif talk == 2:
#put train function here
pass
elif talk == 3:
print("Your level is", lvl, "you have", mhp, "and have", exp, "EXP")
else:
amsterdam = 7 #filler
print("Anthing else needed(y/n)")
ant = input("Anthing: ")
if ant == n:
break
else:
mexico = 19 #filler
you need to enter some statement before the. elif talk == 2:
if talk == 1:
print 1
elif talk == 2:
Your if blocks are empty. Try this
if talk == 1:
pass
#put storie function here
elif talk == 2:
pass
#put train function here
elif talk == 3:
print("Your level is", lvl, "you have", mhp, "and have", exp, "EXP")
else:
amsterdam = 7 #filler
if that's the exact code you're running, your problem should be within:
while True:
print("Who whould you like to talk to. (Emily(1), James(2), Paco(3)")
talk = int(input("Who to talk to: "))
ptint(" ")
if talk == 1:
#put storie function here
elif talk == 2:
#put train function here
here you get the comment #put storie function here which is not evaluated as code so basically what python interprets is:
while True:
print("Who whould you like to talk to. (Emily(1), James(2), Paco(3)")
talk = int(input("Who to talk to: "))
ptint(" ")
if talk == 1:
elif talk == 2:
[…]
whereas it expects:
while True:
print("Who whould you like to talk to. (Emily(1), James(2), Paco(3)")
talk = int(input("Who to talk to: "))
ptint(" ")
if talk == 1:
print("python wants actual code here in an inner block")
elif talk == 2:
print("python wants actual code here in an inner block as well")
[…]
and thus does not compile