Learning Python - Week 2

evanrpavone

EvanRPavone

Posted on June 18, 2021

Learning Python - Week 2

So this week I learned about creating functions, control flow (if else/elif statements) and for loops. It was a slow week for me so I will only be talking about functions and their scope. I only got through a few lessons but next week I will be talking a lot more about these areas.

For me, creating functions and understanding them seemed a lot easier than learning about functions in the other languages I know even though it is very similar. You would set it up like a function you would see in JavaScript, but for me this looks like a method in Ruby. You would pass a parameter when defining a function and you would pass an argument when you are outputting like so:

def greet_person(value = “your name”): # passing a parameter of value with a default value
    “””
    DOCSTRING: This returns a greeting / This section is also comments
    INPUT: value
    OUTPUT: Hello… name
    “””
    print(“Hello “ + str(value) + “, this is the greet_person function”)

greet_person()
greet_person(“Evan”)
greet_person(23)
Enter fullscreen mode Exit fullscreen mode

The three greet_persons are different examples. The first will just print the default value and place it in the string, the second will put Evan, and the third will change the integer to a string and put 23. The second and the third are passing in arguments which will change the parameter value and place it in the string. Anything outside of this function would be considered the global scope and anything inside the function is considered the local scope. So if I have a variable of age that is set to 23 and a function increase_age that also has a variable of age that is set to 30, I will not get the increase_age function age if I just print(age) outside of the function. I would end up getting the original age outside of the function, 30.

age = 23

def increase_age():
    age = 30
    print(age)

print(age) # returns 23 because it calling the age variable outside of the function - global scope
increase_age() # returns 30 because it is inside the function - local scope
Enter fullscreen mode Exit fullscreen mode

Sorry if this got confusing to read but this is what I learned this week. This wasn’t all I learned but this is what really stood out to me. Python is a lot of fun and I am enjoying it. Come back next week!

💖 💪 🙅 🚩
evanrpavone
EvanRPavone

Posted on June 18, 2021

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related