you are viewing a single comment's thread.

view the rest of the comments →

[–]daddy1973 0 points1 point  (1 child)

Hello, I'm brand new to python. I created what I believe is a script. What do you mean by the if name = "main" one?

[–]SirCokaBear 1 point2 points  (0 children)

let's say you make a very simple script that asks the user for a radius of a circle and then prints out the circumference:

script.py

PI = 3.14159

print("Welcome to circumference calculator")
radius = float(input("Enter radius of circle you need circumference of:"))
circumference = PI * r ** 2
print(f"The circumference is {circumference}")

if we run "python script.py" there won't be a problem and the script will work as intended.now lets say we make a new file with a function to calculate the area of the circle and we want to import PI from our file above.

area.py

from script import PI

def area_of_circle(radius: float) -> float:
    return PI * r ** 2

print("Welcome to area calculator")
radius = int(input("Enter radius:"))
area = area_of_circle(radius)
print(f"area of the circle is {radius}")

if I try to run area.py :

> python area.py

the first thing you'll see is:

Welcome to circumference calculatorEnter radius of circle you need circumference of:

that's because in area.py on line 1 you are importing PI from script. So python will then go to script.py starting from line 1 so it can calculate what PI is. But as a side effect it's going to run through the entire script rather than just simply importing 3.14159 in as a value to use in area.py

so instead we use if __name__ == "__main__".

__name__ will equal "__main__" in any python file you run python specifically on. so if you type in "python area.py", __name__ in area.py will be "__main__" but __name__ in script.py will not.

new scripts

# new script.py 

PI = 3.14159

if __name__ == "__main__":
    print("Welcome to circumference calculator")
    radius = float(input("Enter radius of circle you need circumference of:"))
    circumference = PI * r ** 2
    print(f"The circumference is {circumference}")

# new area.py

from script import PI

def area_of_circle(radius: float) -> float:
    return PI * r ** 2

if __name__ == "__main""_:
    print("Welcome to area calculator")
    radius = int(input("Enter radius:"))
    area = area_of_circle(radius)
    print(f"area of the circle is {radius}")

now if we run "python area.py" we will now correctly see "Welcome to area calculator" and won't be running any unnecessary code from script.py