I am trying to make a sort-of AI thing with Python, but I've got stuck on some part.
When the AI says something, (says hello at the beginning), it gives you the ability to input text, once you've entered that, it would go through if 'keyword' in answer statements to provide a reply. Once it replies, it calls the AImain() function, restarting that process. I can't seem to get it to restart, as compiling would just say hello initially (as intended), but give no input text ability, which results in the script ending. Here's the code:
def AImain():
response = input("YOU:")
if 'Hello' or 'Hi' in answer:
print(random.choice(welcomeMessages))
AImain()
I'm new to python and I don't understand why this isn't working.
Thanks!
Your code has an indentation problem at the Aimain() function and we can't see how answer is declared. You are assigning the input to response but reading answer in your code.
Here is my suggestion to your code
response = "Hi" #you can eliminate this, assuming response is declared somewhere else
def AImain():
global response
response = input("You:")
while response == 'Hello' or response == "Hi":
print(random.choice(welcomeMessages))
AImain()
Related
I'm a beginner at Python and coding in general, and I've been primarily using the trinket interpreter to work out some of my scripts. I was just trying to get used to defining a function with if and elif lines alongside the return command.
The code I'm trying to run is a pretty simple one, but when I run it regularly nothing shows up. However, when I run it through the console it
comes out fine. What am I doing wrong?
def the_line(text):
if text == ("just a boy"):
phrase = ("I fly alone")
elif text == "syndrome":
phrase = ("darn you syndrome")
return phrase
the_line("just a boy")
The first picture is what happens when I run it regularly and the second is through the console.
In the console, when you run a statement but don't assign it to anything, the shell will print the resulting object. You call the function but don't save it in a variable, so it is displayed. The "console" in your IDE is also called a Read, Evaluate and Print Loop (REPL).
But your code really just discarded that return value. That's what you see in the first case, the returned object wasn't assigned to anything and the object was deleted. You could assign it to a variable and print, if you want to see it.
def the_line(text):
if text == ("just a boy"):
phrase = ("I fly alone")
elif text == "syndrome":
phrase = ("darn you syndrome")
return phrase
foo = the_line("just a boy")
print(foo)
(As a side note, 4 spaces for indents please. We are not running out of spaces).
This is very clearly explained in Think Python's section 2.4. It has everything to do with the Read-Eval-Print-Loop (REPL) concept.
Briefly, the console is a REPL, so you see the output because it Prints what it Evaluated after Reading something (and then it prompts again for you to input something, that's the loop part). When you run the way you call "regularly", you are in what is called "script mode" (as in Think Python). Script mode simply Reads and Evaluates, there is not the Print-Loop part. A REPL is also called "interactive mode".
One could say that a REPL is very useful for prototyping and testing things out, but script mode is more useful for automation.
What you need to see the output would be like
print(the_line("just a boy"))
for line number 9.
Slowly progressing with my learning with Python and would love a little hand with some code I've tried to create.
I previously had this program running with Global Variables to get a proof of concept to learn about passing variables between functions. Fully worked fine. However, rather than running the function and returning to the menu, it will just stop where I return the value and not progress back to the main menu I created. It is at the point of "return AirportDetailsGlobal".
I'm sure its a simple one, and as said - still learning!
Really appreciate any help on this!
Full code is on pastebin for further reference - pastebin 89VqfwFV
print("\nEnter airport code for overseas")
osCode = input()
airports = airData
for line in airports:
if osCode in line:
print (osCode, "Found\n\n")
print("Airport Name:",line[1])
OverseaCodeGlobal = osCode
x = int(line[2])
AirDataGlobal = x #changed here
return AirportDetailsGlobal
break
else:
print('Incorrect Choice')
menu()
menu()
If you do a return then your code goes back to where it was called from. If it wasn't called from anywhere (ie. you just ran that script directly) then calling return is in most ways equivalent to calling sys.exit(), ie. the program terminates. It'll never hit your break, leave the loop, or hit your call to menu().
Also, your indentation as given there isn't right, the else is at the same level as the for, not the if. I don't think that's the problem but you might hit it next. ;-)
I'm quite new to coding. I've wrote a simple piece of code which will take a URL as an input, load the URL and put the status code for that URL in a variable. I have put this in a function. But when I run the code I get no errors and yet the function won't run. It seems like the interpreter is just flying past my function. I know I have some simple error but no matter how much I search I can't fix it. Please help me understand. Oh, and the code is incomplete. But the function should run.
import urllib.request, click, threading
url = input("Enter domain name >> \n")
def get_stat():
status = urllib.request.urlopen("http://"+url).getcode()
if status == 200:
return "Site loads normally!\nHost Said: '%s'!" %(str(status))
else:
return "Site Needs To Be Checked!\nHost Said: '%s'!" %(str(status))
get_stat()
if click.confirm("Would you like to set a uptime watch?"):
click.echo("You just confirmed something!!")
count = input("Enter the number of times you wish your site to be checked: ")
interval = input("Enter the time interval for status requests (Time is in minutes): ")
You function certainly is working. The problem you are facing is that you are returning a value from get_stat() (this is what the return statement does) but you never actually say that this value should print.
My guess is you want to print the values that are returned in which case you need to add the print statement:
print(get_stat())
Or you could store what the value as a variable:
a = get_stat()
print(a)
As said in quamrana's comment below although the following method is considered bad practice you can put the print() statement inside your function for debugging purposes and replace it later:
if status == 200:
print("Site loads normally!\nHost Said: '%s'!" %(str(status)))
else:
print("Site Needs To Be Checked!\nHost Said: '%s'!" %(str(status)))
This will prove that the function is indeed being executed.
This post might help you understand a little bit better what the return statement does and how you can get values from it.
I'm working on a chatbot which has two scenarios.
1: When the user types a question, if that question is available it training dataset, It picks a response for that question from the training dataset.
2: If the question typed by user is not available in the dataset, system gives response from default answers which are defined with in the code.
My problem is, when the system gets a question statement that is not in the training data, it picks a random answer from the code (Fine). But from that point, it starts giving default answers no matter which question we ask. It never picks an answer from training data despite having that particular question and its answer in the training data.
The entire code is too large to paste here. I'm writing just those functions where the problem occurs. Hope someone could help me with this.
def response(sentence, userID='123', show_details=False):
results = classify(sentence)
# if we have a classification then find the matching intent tag
if results:
# loop as long as there are matches to process
while results:
#some if else statements to match the question
results.pop(0)
while not results:
pairs = (
(r'I need (.*)',
("Why do you need %1?",
"Would it really help you to get %1?",
"Are you sure you need %1?")),
(r'Why don\'t you (.*)',
("Do you really think I don't %1?",
"Perhaps eventually I will %1.",
"Do you really want me to %1?"))
)
aida_chatbot = Chat(pairs, reflections)
def aida_chat():
aida_chatbot.converse()
def demo():
aida_chat()
if __name__ == "__main__":
demo()
else:
response()
# sentence = sys.stdin.readline()
sys.stdout.write("> ")
sys.stdout.flush()
classify(sentence=sys.stdin.readline())
while True:
response(sentence=sys.stdin.readline())
When I put the pairs outside the while statement, (e.g in else statement after the if statement is closed), program never enters the else statement and this part of code is never executed.
Cany anybody help me with this?
if __name__ == "__main__":
demo()
else:
response()
You are not passing question text from this response function call. Just pass your question as an argument from this response function call.
I'm experimenting/having a little fun with wave robot python apiv2.
I made a little 8ball app for the robot which works fine, and now I'm trying to make a trivia app.
I've never programmed in Python but I'm pretty sure my syntax is correct. Here is the relevant code:
elif (bliptxt == "\n!strivia"):
reply = blip.reply()
if (triviaStatus != "playing"):
reply.append("Trivia Started!")
triviaStatus = "playing"
else:
reply.append("Trivia is already running!")
elif (bliptxt == "\n!etrivia"):
reply = blip.reply()
if (triviaStatus == "playing"):
reply.append("Trivia Ended!")
triviaStatus = "stopped"
else:
reply.append("Trivia is not running! To start trivia, type !strivia")
else: (snipped out)
Okay so basically I want it to work so that when someone blips "strivia" the bot recognizes that someone wants to play so it first checks a variable called triviaStatus to see if we are already playing and goes from there. Pretty simple stuff.
In order for this to work (and, actually, this code is really meant to test this question out) the variables would need to effectively be like the php $_SESSION variables - that is, it remembers the value of the variable every time someone blips and does not reset each time.
Nevertheless, whether or not that is the case (if it isn't then I assume I can do the same thing by saving variable settings in a txt file or something) I am baffled because the code above does not work at all. That is to say, the robot is not replying on !strivia or on !etrivia. If the variables didn't save then if anything the robot should just reply with "Trivia Started" or with "Trivia is not running!" each time. But it just does not reply at all.
If I remove the check for triviaStatus, the robot DOES reply. But then there's no logic and I can't test my question out.
I also tried making a !trivstatus where it would reply back with
"Trivia status is " + triviaStatus
but that ALSO choked up. Why is it that every time I want to USE triviaStatus, the bot just dies? Note that I am able to SET triviaStatus fine (I just can't ever check what the output is by replying with it....)
So, to sum this up...how come the above code does not work but the following code DOES work:
elif (bliptxt == "\n!strivia"):
reply = blip.reply()
reply.append("Trivia Started!")
trivia_status = "playing"
elif (bliptxt == "\n!etrivia"):
reply = blip.reply()
reply.append("Trivia Ended!")
trivia_status = "stopped"
Thanks!
It seems that you should rename triviaStatus to trivia_status and make sure that trivia_status has some value e.g., bind it to None before the first use. Otherwise your code might raise UnboundLocalError or NameError exceptions due to triviaStatus/trivia_status doesn't refer to any object.