How can I have a multiple choice question with each answer a different response and a default answer for an answer that is not understandable?
I am trying to create a game where you use your imagination to complete the game.
I also need to somehow repeat until the correct answer is given.
Here is the code:
answer = input("start?")
while answer.lower() != "start":
answer = input("type start")
else:
print("starting")
answer = input("you find yourself in a car")
while answer != "["look", "get out"]:
print("I don't understand..")
answer = input("Try again")
else:
if answer == "look":
print ("looking")
elif answer == "get out":
print("got out of car")
print("finished")
Related
I'm writing a program where you can play blackjack with a computer. I've implemented a class, a "main" and a bunch of others functions. The problem is that almost all of my them are build to get the proper input from the user. For instance:
def get_the_answer():
while True:
answer = input("Write 'reveal' to reveal cards, 'add' to add one more: ")
if answer in ['reveal', 'add']:
break
else:
continue
return answer
Or this one, which also has some prints in it:
def start_and_greet():
print('', colored('Hi! Shall we play Blackjack?', 'yellow'), '', sep='\n')
print(colored(blackjack()))
print()
while True:
answer = input("Write 'start' / 'exit': ")
if answer in ['start', 'exit']:
break
else:
continue
return answer
If I put all my inputs and prints in "main" function, there will be almost no additional functions besides "main", so this won't be acceptable by the task.
The main reason why I'm worrying about it is that I don't understand how one should test this...
Thank you in advance for your help!
I know that it is not recommended to use a function with print / input, although I saw how David Malan (CS50P course) uses the similar one in lectures:
def get_number():
while True:
n = int(input("What's n? "))
if n > 0:
break
return n
Basic Python Chatbot
An Objective of the task is to create a Basic Python chatbot where any questions asked if the chatbot does not know the answer, it shows request the user to provide the answers. Once the answer is received, it should write that question and its answer it into the pandas dataframe. In the future, a similar question is asked, the chatbot should look into the pandas data frame and give the answer.
Purpose of creating the pandas data frame is that currently, I don't have any ready question and answer, so as time progress I will be adding the question and answer to pandas data frame one by one.
Blockquote
username = "User"
chatbotname = "<>"
chatbotnameknown = False
active = True
def saychatbot(text):
global username
global chatbotname
global chatbotnameknown
global active
if chatbotnameknown:
print(chatbotname + ": " + text)
else:
print("*: " + text)
def speak(user_entry):
global username
global chatbotname
global chatbotnameknown
global active
if user_entry == "Hello!" or user_entry == "hello":
saychatbot("Hi, " + username)
elif user_entry == "How are you?":
saychatbot("I'm fine. And you?")
reply = input("Your answer: ")
if reply == "Great":
saychatbot("I'm glad to hear that.")
else:
saychatbot("I didn't understand you.")
elif user_entry == "Bye":
active = False
else:
saychatbot("I didn't understand you.")
saychatbot("I am still learning, let me learn your language")
if input("Would you like to teach me your language, Say y/n ? ") == "y":
saychatbot("You know i am still infancy, so please teach me your language one question and its answer at a time so i will load it in my database!!")
print("Here I would like to record the question and its answer in Pandas data frame and use that data frame as input to answer the same question in future")
print("Is there any way to achieve it")
def OpenDiscussion():
global username
global chatbotname
global chatbotnameknown
global active
print("********Python - Do you know system can speak****************")
while active:
if chatbotnameknown:
speak(str(input(username + ": " + chatbotname + ", ")))
else:
speak(str(input(username + ": ")))
saychatbot("Bye.")
OpenDiscussion()
First, you can set up a data structure to store the <question, answer> data. In this case, a dictionary would be fine.
If you need use dataframe and add data, pandas.DataFrame.append method would help.
I am trying to set up a fighting game where it prints a question and you have to answer the question correctly to win the fight. But I a finding that I can't find a way to get the code t read the random question to be read thus meaning I can't get it to read the answer as correct.
I've tried making the random be separated into multiple variables but that didn't work. I haven't had much time to try anything else either.
import random
fights=("I run but never walk, I have a bed but never sleep", "What time
of day is the same fowards as it is backwards?", "3+2")
FIGHTS=random.choice(fights)
print(FIGHTS)
ans1="river"
ans2="noon"
ans3="5"
que1=input("What shall you say?\n")
if ans1=="I run but never walk, I have a bed but never sleep":
print("You won!")
elif ans2=="What time of day is the same fowards as it is backwards?":
print("You won!")
elif ans3=="3+2":
print("You won!")
else:
print("You lost...")
If you answer correctly it displays "You won!" and if you answer wrongly it displays "You lost..." but it can't read what is printed so it always displays "You lost..."
A good approach would be to store the questions and answers in a dictionary and use good variable names.
import random
fights = {"I have a bed but never sleep": "river",
"What time of day is the same fowards as it is backwards?": "noon",
"3+2": "5"}
question = random.choice(tuple(fights.keys()))
print(question )
answer = input("What shall you say?\n")
if answer == fights[question]:
print("correct")
else:
print("wrong")
If you are not going to use this dictionary again, you can use fights.popitem() instead. Keep in mind that if using Python >= 3.7 popitem will always return the same key-value pair:
fights = {"I have a bed but never sleep": "river",
"What time of day is the same fowards as it is backwards?": "noon",
"3+2": "5"}
question, correct_answer = fights.popitem()
print(question)
user_answer = input("What shall you say?\n")
if user_answer == correct_answer:
print("correct")
else:
print("wrong")
Let's say I am trying to find a special number from 0-100000. Here is my program to do so:
def checkNum(num):
if num == 43582:
print('Found!')
return True
return False
if __name__ == '__main__':
thingsToCheck = []
for i in range(0, someLargeNumber)
thingsToCheck.append(randomInteger())
pool = Pool(cpu_count())
answers = pool.map_async(checkNum, thingsToCheck)
answers.wait()
answers = nodesPopulated.get()
if True in answers:
print('Answer was found!')
else:
print('No answer :(')
There are two options of output:
Found!
Found!
...
Found!
Answer was found!
For Found! can be printed len(thingsToCheck) times or
No answer :(
But with the sole purpose of checking if we found the number, it seems pointless to find it over and over again when finding it just once is what I am trying to do. So is there a way to loop over the results as they come in and then terminate the other children? I am hoping to do something like this: (pseudo)
answers = pool.map_async(checkNum, thingsToCheck)
while newAnswer has come: #run this loop when a child has finished
answers = nodesPopulated.get() #hopefully returns list of return values or None
for answer in answers:
if answer == complete:
if True in answer:
print('Answer was found!')
answers.killChildren()
quit()
print('No answer :(')
I am new to python I am trying to code this, I am asking a question, hence the "Are you a mutant" and depending on if the user responds with a yes or no it should come up the respective output but it works only for yes but not for no. how do i make it work for the elif output?
print("Are you a mutant?")
answer = input()
if 'Yes':
print("Your application to Xavier's School for Gifted Youngsters has been accepted")
elif 'No':
print("Your application was not successful on this occassion")
`
You need to compare the variable that stores the users input with the thing you are comparing it to. In this case using the ==. Below is revised code off your example:
print("Are you a mutant?")
answer = input()
if answer == 'Yes':
print("Your application to Xavier's School for Gifted Youngsters has been accepted")
elif answer == 'No':
print("Your application was not successful on this occassion")
You have to write raw_input instead of input. 'Input' just takes the text value but 'raw_input'get the input as a string.
If you are using python2, then follow the code below:
print("Are you a mutant?")
answer = raw_input("Yes/No: ")
if answer == "Yes":
print("Your application to Xavier's School for Gifted Youngsters has been accepted")
elif answer == "No":
print("Your application was not successful on this occasion")
In python3 raw_input() was renamed to input(). Then follow the code below:
print("Are you a mutant?")
answer = input("Yes/No: ")
if answer == "Yes":
print("Your application to Xavier's School for Gifted Youngsters has been accepted")
elif answer == "No":
print("Your application was not successful on this occasion")