简体   繁体   中英

Why won't my Python function execute?

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM