loading...

#100DaysOfPython Day 2: Functions, Scope and Best Practices

taeluralexis profile image Tae'lur Alexis 🦄⚛ Originally published at taeluralexis.com ・Updated on ・4 min read

link title
So far I've learned a bit about the different types Python posseses and how to print Hello World. Today however, I've learned more about Python's best practices as well as functions and how the language handles access to variables in the local and global scope (spoiler alert: Scope works the same way in Python as it does in JavaScript :-p) .

Update: My collection of notes will always be updated as I learn more things. I'm merely posting as I actively learn. I do not claim to be a Pythonista, I am not an expert.

Advocating for Best Practices

A key quality of an exceptional engineer is consistently writing code that follows best practices. But why is that important? Style guides that contain best practices are basically a set of rules and guidelines that ensures consistency, readability for other humans and efficiency.

The standard that the Python community follows is called PEP-8. My advice, especially when you're a beginner, is to bookmark this style guide (or the relevant style guide to your programming language/framework) and reference it frequently.

Key tip for early-career developers: The best way to write consistently good code is to always practice and reference standard guides.

Here are just a few of Python's Best Practices:

           
RuleMeaningExample
Function & Variable Names Be explicit with variable & function names x = "x is a nondescript variable name"
vs
favorite_food =" This variable name gives us a better hint at what this piece of data is about"
Indentation Indentation is an essential concept in Python Use 4 spaces per indentation level
Underscores create more readability For your descriptive and longer variable and function names, use underscores to make the names more readable self_care_message()
vs.
selfcaremessage()
Refrain from using confusing standalone letters as variable or function names; exception is when they have meaning in math Using the lowercase letter 'l', uppercase letter O or uppercase letter I can be confusing. We don't write code for ourselves, we write for others. i = 1

All About Functions

Indentation Matters, Ya'll

Anatomy of a Function:

link title

  1. def is how you initalize the function
  2. Name the function and be as descriptive as you can be (remember if you're being verbose with the naming, use underscores in between each word for the function name)
  3. Follow the function name with parentheses and a colon! (As a Javascript developer I was initially tripped up by this and kept using a semicolon)
  4. Make an indentation (a tab or 4 spaces) to create your instructions (aka return or print statement)
  5. Complete and Exit the function by pressing enter
  6. Call the function by the name you gave it followed by parentheses

Difference between a return statement versus a print statement

A return statement will explicitly return a value.

A print statement will return nothing.

link title

Local and Global Scope

Scope is what determines what variables you can access. I learned in JavaScript that there is a global scope as well as a local scope.

Local scope is when the variables you define within a function can only be accessed in that very function in which you defined it. It won't be accessible to the global scope (aka rest of the application).

In internal/local scope, the function has access to variables defined within it; has access to variables defined in the global scope (aka rest of application outside that function) but cant change them. Meaning you can't reassign a global variable within a local function.

Functions without proper whitespace leads to an indentation error.

In production-level code, don't have too many global variables outside of a defined scope to prevent confusion and bugs; constants are okay to define outside of a scope

Notes on Arguments

link title
Positional arguments are all required and must be given in the order in which they are declared.

Default arguments is kinda like the fallback/default option when you don't call the last argument when you invoke a function. It is always the last argument in a function.

What Will I Learn Next in Day 3 of the #100DaysOfPython series?

  • More advanced data types like sets, tuples, dictionaries

Discussion

pic
Editor guide
Collapse
dbanty profile image
Dylan Anthony

Cool post, neat to see Python concepts explained from a JavaScript perspective. I have a few notes / clarifications on some of your points.

  1. Return vs print: the way it was phrased made it seem like the print statement was similar to the return statement. It’s not, print is just a function basically equivalent to console.log.

  2. Scopes: you actually can modify global variables from a local scope by using the global keyword, like this:

global_var = 1

def my_func():
    global global_var
    global_var = 2
    local_var = "a"

    def inner_func():
        nonlocal local_var  # similar to global for inner functions
        local_var = "b"
  1. Arguments: you can have any number of optional arguments (arguments with defaults) after required arguments. There are also a lot more things you can do with arguments (arbitrary args, keyword only, required keywords, positional only) that are useful. They usually involve asterisks and I’m sure you’ll come across them later.
Collapse
taeluralexis profile image
Tae'lur Alexis 🦄⚛ Author

These are not meant to be comprehensive tutorials that teach everything about a topic, they're my personal notes that I made into posts. But thanks

Collapse
jnario profile image
Jose Nario

Good stuff. Keep going!

Since you're discussing best practices, it's worth noting that functions should have a "docstring". This string appears directly after the function declaration, and is wrapped in triple-quotes.

This docstring can be accessed/inspected via the REPL, is used by IDEs, and is also returned if you call help(your_function).

More: python.org/dev/peps/pep-0257/

Good luck!

Collapse
taeluralexis profile image
Tae'lur Alexis 🦄⚛ Author

I haven't learned that yet. I'm posting and updating as I learn more. For what it's worth, these are notes not tutorials but thank you :)

Collapse
xaviguasch profile image
Xavi Guasch

Really loving this series so far!

As a JS dev I'm very curious about Python too, but before I finally dive into it, here's a suggestion about a future post that might be useful for others like me: it's the WHY of Python. What makes Python more suitable to data science, machine learning or other specific fields compared to JS? What makes the language special in that sense?

Collapse
westcliffe profile image
westcliffe

thanks for updating.

Collapse
schwitzd profile image
Collapse
miayuxin profile image
Mia

Hi! Im wondering when will you update day 3?? Since I am a real beginner, and would like to join your 100 days activity, hope you will update sooooon><

Collapse
taeluralexis profile image
Tae'lur Alexis 🦄⚛ Author

Hey Mia! I'm really glad you enjoy the series. Aim is to post every few days so it allows me time to edit and add as much info to each post as well as to update old posts too as I'm learning Python.

If you follow me on Twitter @taeluralexis I usually send the link out there as soon as each post is live on dev.

Post #3 comes out on Monday. Post #4 on Wednesday 💙

Collapse
tatianacodes profile image
Tatiana

I continually forget to use a colon, or I'm so stuck on JS that I use the semicolon! Python is so refreshing as a way to get away from front end webdev/JS.