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.
Related
Hello everyone I have my code almost done but I'm trying to add in some sort of check to avoid errors. But I'm not really understanding what statement would be better to use to test the code. I know there are a few options of either using a loop, if-statement, or try. But here is the code in regards to doing captcha. I need it to run the first set of code which if the captcha doesn't pop up I continue on. But if the captcha does pop up solve it then continue on.
Some times captcha doesnt appear and if I run the whole set of code I get an error because we are expecting captcha to pop up.
Or if the captcha does appear to solve it which would.
I would really appreciate any help please as I'm not sure the right statement to use.
try should be used when something would return an error and would otherwise cause your program to stop/crash. An example of this would be:
try:
import pandas
except:
print("Unable to import pandas. Module not installed")
In this example your program will attempt to import the pandas module. If this fails it will then print out a line of text and continue running.
if statements are used to decided when to do something or not based on the returned logic. The key difference is that logic IS returned and not an error.
if x > 10:
print("This is a large number")
else:
print("This is a small number")
With this example, if 'x' did not exist it would produce an error, no more code will be executed, and the program will crash. The main difference between IF and TRY is whether logic is returned as true/false or is something just plains fails.
With your specific example it is important to know if the captcha appearing or not will break your code. Does the logic boil down to captcha = false or does captcha not exist at all and logic fails entirely?
Q: How do you define sometimes captcha doesn't appear (1%, 20%, 50%, ...)?
A: Maybe 5% of the time captcha doesn't appear.
In this case, I prefer to use Exception handling: do stuff and if something goes wrong, fix it
try:
# > 95% of the time the code below works when the captcha appears
except SomeException:
# < 5% of the time the code is called when the captcha doesn't appear
IMHO, you have not really 2 different codes: you have one and a fallback solution, it's really different than:
if x % 2:
...
else:
...
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()
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 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 currently in the process of trying to add a while loop to my code that is shown below. The theory behind what I'm attempting to do is as follows:
As you can see at the very bottom of my code, I confirm the user's reservation and ask if he/she would like to create another. If the user enters 'yes", I would like the program to re-run. If no, then the program should terminate. I'm aware the best way to accomplish this is using a while loop, but I'm having a little difficulty executing this as my textbook is a little confusing on the subject.
I know it's supposed to look something like this (or something along the lines of it):
while True:
expression
break
Though I can't seem to get it to compile. Any suggestions? Below is my code:
user_continue = str(raw_input("Your reservation was submitted successfully. Would you like to do another?"))
if user_continue != 'yes':
print('Thank you for flying with Ramirez Airlines!')
Here's a simple example that shows how to use a while loop:
import time
while True:
print time.ctime()
print 'Doing stuff...'
response = raw_input('Would you like to do another? ')
if response != 'yes':
break
print 'Terminating'
Note that the code inside the while loop must be indented, unlike the code in your first code block. Indentation is very important in Python. Please always ensure that code in your questions (and answers) here is properly indented.
FWIW, the raw_input() input function returns a string, so str(raw_input()) is unnecessary clutter.
The end of your code should look something like:
user_continue = raw_input("Your reservation was submitted successfully. Would you like to do another?")
if user_continue != 'yes':
break
print('Thank you for flying with Ramirez Airlines!')
...
Your print statements are a bit funny. Since you're using Python 2.7 you don't need to do
print ('The total amount for your seats is: $'),user_people * 5180
you can just do
print 'The total amount for your seats is: $', user_people * 5180
or if you wish to use Python 3 style, put everything you're printing inside the parentheses, like this:
print ('The total amount for your seats is: $', user_people * 5180)
However, the output will look a bit messy since there will be a space between the $ and the amount. Please read the python docs to learn how to fix that.
...
Also, you have import time inside your loop. Don't do that. Generally, import statements should be at the top of your script before any other executable code.