I am trying to write a code for a text based chat-bot as my first full scale project and I am having a weird problem with while loops that I can't figure out. My primary loop is dependent on text input, what is supposed to happen is when the user types "bye" the program ends. The only problem is when I run it, no matter what I say to it, it just prints out the same response over and over until I hit cntrl.+c or close the window. Here is the code:
import datetime
print("Hi I am ChatBot V 0.0.1. I am here to converse. ")
user_name=raw_input("What is your name?")
print("Hello " + user_name + "!")
user_input=raw_input().lower().replace(" ","").replace("?","")
is_user_finished=0
while (is_user_finished == 0):
if user_input == "hi" or "hello":
print("Hello. How are you?")
elif user_input == "whatisyourname":
print("I do not have a name at the moment. What do you think I should be named?")
user_input=raw_input().lower().replace(" ","").replace("?","")
print("Good choice! I like that name!")
elif "where" and "you" in user_input:
print("I was typed up by some kid in California")
else:
print("I do not currently understand what you said. Sorry.")
if user_input == "bye":
print("Good bye. It was nice talking to you!")
is_user_finished = 1
What happens is that the line
if user_input == "hi" or "hello":
don't do what you think. Instead, you should do
if user_input == "hi" or user_input == "hello":
or even, in a more compact way:
if user_input in ["hi","hello"]:
Something similar happens with the line
elif "where" and "you" in user_input:
which should be
elif "where" in user_input and "you" in user_input:
syntax issue.
the correct form should be : if A == B or A == C, instead of A == B or C, which is incorrect.
You should change the line
if user_input == "hi" or "hello": to if user_input == "hi" or user_input == "hello":
and
"where" and "you" in user_input: to "where" in user_input and "you" in user_input:,
because "hello" and "where" is always True .
Besides you should put user_input=raw_input().lower().replace(" ","").replace("?","") into the while loop.
Provided you have proper indentation, which if the loop keeps running I assume you do, the problem, besides the things pointed out above about proper use of compound if statements is you need to add a "break" to the "bye" case.
if user_input == "bye":
print("Good bye. It was nice talking to you!")
is_user_finished = 1
break
Related
I am a python noob, I have little experience so the code you will witness is garbage. Its a number guessing game. I keep getting a syntax error on the last line pointing me to just before the parenthesis and I cant figure out what the hell is it trying to say. Also any interpreter suggestions? I have a license in VS but I find it to be infuriating to use.
def func_guessdude(x):
if user_input == x:
print("you got it")
elif user_input > x:
print("just a little less")
else:
print("just a little more")
user_input == 16
print func_guessdude(15)
You are missing parentheses in you last print: print(func_guessdude(15))
You just need to re-format this a bit:
def func_guessdude(x):
if user_input == x:
print("you got it")
elif user_input > x:
print("just a little less")
else:
print("just a little more")
user_input = 16
func_guessdude(15)
This returns "just a little less."
def func_guessdude(x):
global user_input
if user_input == x:
print("you got it")
elif user_input > x:
print("just a little less")
else:
print("just a little more")
user_input = 16
print func_guessdude(15)
Shouldn't your code be like:
user_input = 16
def func_guessdude(x):
if user_input == x:
return "you got it"
elif user_input > x:
return "just a little less"
else:
return "just a little more"
print (func_guessdude(15))
You initialized user_input after your if else, and also your method is not returning anything
Alright so I finally fixed it up to work fine, thanks to kfazi for clearing the main issue out. I am not completely sure what a global var is yet, have to google it. Thanks for the responses. This code should return "you got it"
def func_guessdude(x):
user_input = 16
if user_input == x:
return("you got it")
elif user_input > x:
return("just a little less")
else:
return("just a little more")
print(func_guessdude(16))
So I'm trying to figure out how I can make this simple little program to go back to the raw_input if the user inputs something else then "yes" or "no".
a = raw_input("test: ")
while True:
if a == "yes":
print("yeyeye")
break
elif a == "no":
print("nonono")
break
else:
print("yes or no idiot")
This is what I got so far, I'm new and it's hard to understand. Thanks in advance.
As #DavidG mentioned, just add your raw_input statement in loop:
while True:
a = raw_input("Enter: ")
if a == "yes":
print("You have entered Yes")
break
elif a == "no":
print("You have entered No")
break
else:
print("yes or no idiot")
Simply you can put the first instruction inside the loop; in this way, every time the user inserts a value different to yes or no you can print a message and wait to a new input.
while True:
a = raw_input("test: ")
if a == "yes":
print("yeyeye")
break
elif a == "no":
print("nonono")
break
else:
print("yes or no idiot")
Describe a condition checker for while and read input everytime when your condition is not meet. Inline returns are good for low quantity conditions but when your choice count is too much or condition in condition situations appear, inline returns are becoming trouble.
Thats why you must use condition checkers(like cloop) instead of inline returns.
cloop=True
while cloop:
a = raw_input("test: ")
if a == "yes":
print("yeyeye")
cloop=False
elif a == "no":
print("nonono")
cloop=False
else:
print("yes or no idiot")
cloop=True
I'm a beginner to Python, and am having problems with a function. I am making a program in which I have many parameters for the user to choose from and I need to allow them to confirm or deny their choices. Here is a simplified code section that represents my issue.
my code:
def confirm(function):
while True:
answer = raw_input('Are you sure? ')
if answer == 'yes':
break
elif answer == 'no':
return function() # if the user wants to change their name, recall function
else:
continue # to reprompt user if the answer is not "yes" or "no"
def your_name():
while True:
name = raw_input("What is your name? ")
if not name:
continue # to reprompt user if they do not enter anything
else:
confirm(your_name)
print 'Congratulations! You have a name!'
break
your_name()
When running this program, it will print the congratulatory string the same amount of times that answer received an input.
my output:
What is your name? Bastion
Are you sure? no
What is your name? Artex
Are you sure? no
What is your name? Falcor
Are you sure? yes
Congratulations! You have a name!
Congratulations! You have a name!
Congratulations! You have a name!
My intention is for the congratulatory message to be printed just one time. How can I edit my function(s) in order to achieve this?
What I've tried:
I have attempted all of these, using the exact same input values I used in my output block above.
Within the section of confirm(function) that says:
if answer == 'no':
return function()
I've tried changing it to:
if answer == 'no':
function()
In the output, this will ask for the answer raw_input 3 times, posting the congratulatory message after each input. If I write the code in this way:
if answer == 'no':
print function()
It will print the congratulatory response 3 times and print None on a separate line below for each time. I am looking for an elegant, clean format so this will not do.
So your problem is you are creating a kind of recursive function without meaning to, you don't need to pass the function to be called again as you are already inside the function. I would suggest the following:
def confirm():
while True:
answer = raw_input('Are you sure? ')
if answer == 'yes':
return True
if answer == 'no':
return False
else:
continue # to reprompt user if the answer is not "yes" or "no"
def your_name():
while True:
name = raw_input("What is your name? ")
if not name:
continue # to reprompt user if they do not enter anything
elif confirm():
print 'Congratulations! You have a name!'
break
your_name()
I think the cleanest way is to change your_name to:
def your_name(toplevel=False):
while True:
name = raw_input("What is your name? ")
if not name:
continue # to reprompt user if they do not enter anything
else:
confirm(your_name)
if toplevel: print 'Congratulations! You have a name!'
break
and the very first call from the top level to your_name(True).
There are other ways, but they require global variables (ecch:-) or even dirtier tricks to find out if the function has been called from the top level; telling it explicitly is way cleaner...
Because of the style recursion you're doing (kudos on that) you end up invoking the your_name() function once each time they fill an answer.
I'd try something more like this:
def confirm():
answer = ''
while answer == '':
answer = raw_input('Are you sure? ')
if answer == 'yes':
return True
elif answer == 'no':
return False
else:
answer = ''
def your_name():
name = ''
while name == '':
name = raw_input("What is your name? ")
if confirm():
print 'Congratulations! You have a name!'
else:
your_name()
your_name()
I think you don't have to use all those "recursive" calls, try this:
def your_name():
flag = True
while flag:
name = raw_input("What is your name? ")
if name:
while True:
answer = raw_input('Are you sure? ')
if answer == 'yes':
flag = False
break
elif answer == 'no':
break
print 'Congratulations! You have a name!'
your_name()
Using an inner loop for asking if the user is sure. With the use of a flag to determine whenever or not the main "What is your name? " question cycle is over.
You can just put the print 'Congratulations! You have a name!' inside your confirmation() function instead of your_name() so it will be something like this:
def confirm(function):
while True:
answer = raw_input('Are you sure? ')
if answer == 'yes':
print 'Congratulations! You have a name!'
break
elif answer == 'no':
return function() # if the user wants to change their name, recall function
else:
continue # to reprompt user if the answer is not "yes" or "no"
def your_name():
while True:
name = raw_input("What is your name? ")
if not name:
continue
else:
confirm(your_name)
break
your_name()
BTW, I also modify your conditional syntax in the first function so that the program won't go through two if statements.
This solution is relatively succinct. It loops requesting your name while 'name' is an empty string. When requesting confirmation, it resets name to an empty string and thus continues the loop unless the user confirms 'yes'. It then prints the user's name to confirm its assignment.
def your_name():
name = ''
while name == '':
name = raw_input("What is your name? ")
answer = raw_input('Are you sure (yes or no)? ') if name != '' else 'no'
name = '' if answer != 'yes' else name
print 'Congratulations {0}! You have a name!'.format(name)
from sys import exit
def answer():
answer = raw_input("> ")
if answer == "Yes" or answer == "yes":
#going to next
joint()
elif answer == "No" or answer == "no":
print "You still have something, I know..."
again()
else:
fubar()
def again():
again = raw_input("> ")
if again == "Yes" or again == "yes":
#going to next
joint()
elif again == "No" or again == "no":
print "You still have something, I know..."
else:
fubar()
def fuck():
print "Fubar'd!"
def joint():
print "To be continue..."
def question():
print "Hi duuuude..."
raw_input("To say 'Hi' press Enter")
print "Can you help me?"
answer()
question()
Hi, can you help me with this? I`m trying to repeat the function "answer", when I get answer "NO". Im want to escape function "again"... And also is there a way to escape "answer == "Yes" or answer == "yes": " so no matter I write capital or small letter to accept the answer and not to write like a noob "Yes" or "yes"?
This is usually achieved with a while loop.
Edit: As pointed out, while loops are nice and clear, and avoid recursion limits.
Never thought a simple answer would generate so many votes....
Lets give you an example
while True:
ans = raw_input("Enter only y or n to continue").strip().lower()
if ans == "y":
print "Done!"
break
elif ans == "n":
print "No?"
else:
print "Not valid input."
The simplest solution to your problem is remove your again function, and recurse:
def answer():
ans = raw_input("> ")
if ans == "Yes" or ans == "yes":
#going to next
joint()
elif ans == "No" or ans == "no":
print "You still have something, I know..."
answer() # again()
else:
fubar()
I had to rename your answer variable to ans so that it didn't clash with the function name.
For the second question, you want either:
if answer.lower() == "yes":
or
if answer in ("Yes", "yes"):
I have this word un-scrambler game that just runs in CMD or the python shell. When the user either guesses the word correctly or incorrectly it says "press any key to play again"
How would I get it to start again?
Don't have the program exit after evaluating input from the user; instead, do this in a loop. For example, a simple example that doesn't even use a function:
phrase = "hello, world"
while input("Guess the phrase: ") != phrase:
print("Incorrect.") # Evaluate the input here
print("Correct") # If the user is successful
This outputs the following, with my user input shown as well:
Guess the phrase: a guess
Incorrect.
Guess the phrase: another guess
Incorrect.
Guess the phrase: hello, world
Correct
This is obviously quite simple, but the logic sounds like what you're after. A slightly more complex version of which, with defined functions for you to see where your logic would fit in, could be like this:
def game(phrase_to_guess):
return input("Guess the phrase: ") == phrase_to_guess
def main():
phrase = "hello, world"
while not game(phrase):
print("Incorrect.")
print("Correct")
main()
The output is identical.
Even the following Style works!!
Check it out.
def Loop():
r = raw_input("Would you like to restart this program?")
if r == "yes" or r == "y":
Loop()
if r == "n" or r == "no":
print "Script terminating. Goodbye."
Loop()
This is the method of executing the functions (set of statements)
repeatedly.
Hope You Like it :) :} :]
Try a loop:
while 1==1:
[your game here]
input("press any key to start again.")
Or if you want to get fancy:
restart=1
while restart!="x":
[your game here]
input("press any key to start again, or x to exit.")
Here is a template you can use to re-run a block of code. Think of #code as a placeholder for one or more lines of Python code.
def my_game_code():
#code
def foo():
while True:
my_game_code()
You could use a simple while loop:
line = "Y"
while line[0] not in ("n", "N"):
""" game here """
line = input("Play again (Y/N)?")
hope this helps
while True:
print('Your game yada-yada')
ans=input('''press o to exit or any key to continue
''')
if ans=='o':
break
A simple way is also to use boolean values, it is easier to comprehend if you are a beginner (like me). This is what I did for a group project:
restart = True
while restart:
#the program
restart = raw_input("Press any key to restart or q to quit!")
if restart == "q":
restart = False
You need to bury the code block in another code block.
Follow the instructions below:
Step 1: Top of code def main()
Step 2: restart = input("Do you want to play a game?").lower()
Step 3: Next line; if restart == "yes":
Step 4: Next line; Indent - main()
Step 5: Next line; else:
Step 6: Indent - exit()
Step 7: Indent all code under def main():
Step 8: After all code indent. Type main()
What you are doing is encapsulating the blocks of code into the main variable. The program runs once within main() variable then exits and returns to run the main varible again. Repeating the game. Hope this helps.
def main():
import random
helper= {}
helper['happy']= ["It is during our darkest moments that we must focus to see the light.",
"Tell me and I forget. Teach me and I remember. Involve me and I learn.",
"Do not go where the path may lead, go instead where there is no path and leave a trail.",
"You will face many defeats in life, but never let yourself be defeated.",
"The greatest glory in living lies not in never falling, but in rising every time we fall.",
"In the end, it's not the years in your life that count. It's the life in your years.",
"Never let the fear of striking out keep you from playing the game.",
"Life is either a daring adventure or nothing at all."]
helper['sad']= ["Dont cry because it’s over, smile because it happened.",
"Be yourself; everyone else is already taken",
"No one can make you feel inferior without your consent.",
"It’s not who you are that holds you back, its who you think you're not.",
"When you reach the end of your rope, tie a knot in it and hang on."]
answer = input ('How do you feel : ')
print("Check this out : " , random.choice(helper[answer]))
restart = input("Do you want a new quote?").lower()
if restart == "yes":
main()
else:
exit()
main()
How to rerun a code with user input [yes/no] in python ?
strong text
How to rerun a code with user input [yes/no] in python ?
strong text
inside code
def main():
try:
print("Welcome user! I am a smart calculator developed by Kushan\n'//' for Remainder\n'%' for Quotient\n'*' for Multiplication\n'/' for Division\n'^' for power")
num1 = float(input("Enter 1st number: "))
op = input("Enter operator: ")
num2 = float(input("Enter 2nd number: "))
if op == "+":
print(num1 + num2)
elif op =="-":
print(num1 - num2)
elif op =="*":
print(num1 * num2)
elif op =="/" :
print(num1 / num2)
elif op =="%":
print(num1 % num2)
elif op =="//":
print(num1 // num2)
elif op == "^":
print(num1 ** num2)
else:
print("Invalid number or operator, Valid Operators < *, /, +, -, % , // > ")
except ValueError:
print("Invalid Input, please input only numbers")
restart = input("Do you want to CALCULATE again? : ")
if restart == "yes":
main()
else:
print("Thanks! for calculating keep learning! hope you have a good day :)")
exit()
main()
strong text
You maybe trying to run the entire code with an option for user to type "yes" or "no" to run a program again without running it manually.
This is my code for a 'calculator' in which i have used this thing.
Is that your solution?
By the way this is a reference link from where i learnt to apply this function.
https://www.youtube.com/watch?v=SZdQX4gbql0&t=183s