Getting Started With Python and VS Code

Tom Tobar
The Startup
Published in
12 min readSep 24, 2020

In my experience, learning a new programming language is easier if you already know one. When I started learning Python, I noticed similarities to Ruby and JavaScript; which I’m comfortable with. The shapes of the syntax in Ruby are reminiscent of the Python Programming Language and because of its Object-Oriented design, it feels familiar. Invoking functions in JavaScript and Python is basically the same. There were a couple of Python specific syntax rules that were weird at first but with practice, it becomes second nature.

Guido Van Rossum

“ Python is an experiment in how much freedom programmers need. Too much freedom and nobody can read another’s code; too little and expressiveness is endangered.“ Guido Van Rossum, Creator of the Python Programming Language (BDFL)

First Things First

If you’re on a Mac, you might already have Python installed on your computer but you want to make sure that you have the latest version. At the time of this writing, Python 3.8.5 is latest and greatest from the Python.org website.

  • Download the installer and save it to your desktop.
https://www.python.org/downloads/release/python-385/
  • Double click the package and follow the prompts on the installer.
  • Now you can confirm that you have Python installed by running the following command command in your terminal:
python3 --version

You should get the above output in the terminal if you’ve installed it correctly.

Hello World 🌎

Now, we can fire up a Python3 session right in our terminal. Just type:

python3

and hit the return key. You will get the following in the terminal:

It’s like the big bang just happened and we have a blank Python universe to play with and create in.

The print( ) Function 🖨

As the name implies, the print function will print a message to the screen. It can take in zero or more Python objects (like strings, variables, and even other functions etc) that will be converted to a string before being written to the screen.

Try adding multiple strings separated by space or commas or a combination of the two to see how it affects the output.

Add integers (whole numbers) to the mix and see what happens. Error messages are pretty helpful in letting you know what the problem is.

In this case, Python needs to have the strings and integers separated by a comma.

Running the above code with a comma separating the strings from the integers makes the interpreter happy again and we get the following output:

To exit a terminal Python session, call the exit() function:

>>> exit()

and press the return key. This will escape the Python terminal session.

Data Types in Python

Python has different ways of storing data. The different types of data can do different things and can be leveraged in different ways.

Visit https://www.w3schools.com/python/python_datatypes.asp for a more in depth look at data types in Python.

Python + VS Code = ❤️

Visual Studio Code is my preferred text editor and it is what I have been using to learn Python. I really love the Debug Console for Python because the output is really easy to read and it is user friendly.

Go to https://code.visualstudio.com/ and get the version that is right for your OS. After downloading and unzipping, drag the app icon from the Downloads to your Applications.

Now launch the program and once it is open, type:

command(⌘) + shift(⇧) + p

This will open up your Command Palette at the top of the screen and it will look like:

In the Command Palette search bar, type:

>shell command

You should see the following:

Click on Shell Command: Install ‘code’ command in PATH. What this is going to allow you to do is to start VSCode from the terminal using the ‘code’ command. You can also open a directory and its contents from terminal in VSCode using the ‘code .’ (don’t forget the space after ‘code’) command which we will use in just a sec.

One more thing. Get the Microsoft Python Extension. Click the “Extensions” icon on the left side of the screen. Looks like this:

‘Extensions’

You will then see this window:

In the search bar at the top, search for ‘python’ and look for:

Python by Microsoft

Click on Python by Microsoft and this window will pop up:

Click the install button and you’re all set.

Create a New Directory

Open your terminal and navigate to the Desktop. Then create a new directory named “python”.

Desktop % mkdir python

Change directory into that folder.

Desktop % cd python

Once you’re there, we can open that folder in VSCode by typing ‘code .’

python % code .

VSCode will open up and you will see a ‘Welcome’ screen. In the top left corner where it says ‘EXPLORER’, you will see:

  • OPEN EDITORS
  • PYTHON (The empty directory we just made)

Click on the ‘python’ directory and you will see:

Click on the ‘new file’ button and create the ‘hello_world.py’

Now we can write some code in the new file.

Functions

Functions in Python are defined starting with the ‘def’ keyword. That is followed by the name of the function, a set of parenthesis with or without parameters, and a colon : (The toughest part about my transition to Python is remembering to put a colon at the start of the function body) :

Above are two defined functions. The top function, though functional, just illustrates how a Python function comes together. We can call function_two and get some output in the Debug Console.

Calling functions or, invoking functions, is a lot like calling functions in JavaScript.

On line 14, function_two is being invoked and the code inside of it will be executed. Let’s run this saved file in the VSCode’s Debug Console.

The Debug Console

The ‘Run’ button

On the left side of the screen you will find this icon. Click it and then you will see this:

Click on the create a launch.json file

Click on the create a launch.json file. This will open up the Debug Configuration. Select the Python File Debug the currently active Python file pictured below.

Select the ‘Python File Debug the currently active Python file”

This will create a ‘.vscode’ file in your directory and it contains the ‘launch.json’ file which controls the behavior of VSCode during a debugging console session.

Inside of the ‘configurations’ array lives an object and its last value is named “console”. We should be able to hit the run button and get some output in the integrated terminal window that pops up at the bottom of the VSCode screen at this point but it is just not as awesome as the Debug Console. Take a look at this monstrosity:

To set the Debugging Console as the default, we will need to change the “console” value in the ‘launch.json’ file from ‘integratedTerminal’ to ‘internalConsole’.

The “console” key’s value has been changed from ‘integratedTerminal’ to ‘internalConsole’.

Save the ‘launch.json’ file and then click on DEBUG CONSOLE in the terminal window:

Now click the run button:

The ‘Run’ button

Then click the green triangle button at the top of the screen next to the ‘Python: Curre’ dropdown:

And we get some nice output in the Debug Console:

Parameters and Arguments in Functions

You can add parameters to your functions that will be used in the body of the function to change return value based on user input. We can calculate the square of a number by multiplying it times itself. Comment out the code (highlight all code and press command(⌘) + /) in the file or delete it and add this code:

The ‘num’ in the parenthesis on line three is called a parameter. A parameter is a function variable that can be used inside of the function’s body in a specific way. ‘Num’ is being multiplied times itself and save to the ‘answer’ variable. Then, ‘answer’ is printed to the console using the print function.

When calling or invoking the function on lines 8–10, the number that is passed into the parenthesis is called the argument. The argument will replace the parameter in the function and be passed into the body where it is referenced. We can also write the functions to take in multiple arguments.

Multiple Parameters and Arguments

Multiple parameters can be set in a function separated by a comma. Once again, clear or comment out the previous code and insert:

There are a few new things happening in the code above. Starting at line two, the ‘introduction_with_language’ function is being defined. This function will take two arguments when invoked, a name and language.

On line three, the print function is rendering a string to the console. The string starts with an ‘f’. This is called an ‘f-string’ and it is a way to interpolate information into another string. When the Python interpreter gets to {name} in the print function, ‘name’ is being evaluated to the string “Tom” and being inserted instead of the variable ‘name’. The process repeats for ‘language’.

Line 6 is an interesting one. It’s is a Python ‘if’ statement and it is checking to see if the ‘__name__’ property, given to the module (Python files are called modules and they are identified by the ‘py.’ extension) by the Python interpreter, has the assigned value of ‘__main__’. If that is the case, then the expression will evaluate to True and the ‘introduction_with_language’ function will be called.

Parameter Default Values

Function parameters can be configured to have a default value:

On line two in the parenthesis, you see the parameters:

name, language = "Python"

Line 7 in the code invokes the function and only one argument is given, “Tom”. If a second parameter is not given for this function, it will default to the string “Python”. If you were to provide an argument, the parameter will be set to the argument you provide:

Variable Number of Arguments

You can also configure functions to accept a varying number of arguments. Lets create a function that will add all numbers that are passed to it and return the total:

Conditionals

Making decisions is an essential part of your programs. The Python if statement will be something that will be used regularly in your code:

On lines 10–12, the main function is invoked and passed in different values for the parameters “a” and “b”. Inside the main function on line 2, the “if” statement begins and a comparison between “a” and “b” is evaluated.

Each line in the ‘if’ statement is like a gateway. If the expression that follows ‘if, elif, else’ evaluates to “True”, that specific block of code will be executed.

In the case of line 10, ‘a’ is 5 and ‘b’ is 10. When those values are plugged into the expression in line 2, 5 is greater than 10 and that block will execute.

Line 11 passes in 10 for both ‘a’ and ‘b’ so line 4 will evaluate to “True” and that block will fire.

Line 12, 15 is greater than 10 so line 7 will be executed.

Below is another example that will choose a line to print out based on the chance of rain and the temperature.

Loops

While

The ‘while’ loop will execute the code block as long as its expression evaluates to “True”.

Inside of the while_loop function on line 3, the variable x is set to 0. Then on line 4, the while loop is defined and the expression x < 5 is evaluated to True because 0 is less than 5. The block of code inside of the while loop is executed and 0 is printed to the console. Then, x is incremented by one and the while loop repeats itself until x = 5. If the expression on line 4 said:

while x <= 5:

then the output would include the number 5:

For loop

We can use the for loop to iterate over different data structures that store data like lists, tuples, dictionaries, strings, or sets. To iterate over something is to stop on and inspect, or do something with, the value of each place in the data structure.

In the for_loop function above, each value of the_list is being printed to the console. On line 4, I start by defining the ‘for’ loop with the ‘for’ keyword. That is followed by the placeholder variable, ‘each_individual_value’, that will be assigned the value of each item inside of the list on each iteration. This variable could have been named ‘x’ or any other name (other than a Python keyword) but I wanted to illustrate a bit better what was happening in the loop.

On the first iteration of the the ‘for’ loop, ‘each_individual_value’ will be assigned the value of 1 since ‘the_list’ first value on the left is a 1. Inside of the ‘for’ loop block, the variable ‘each_individual_value’ is printed to the console and the loop repeats until it has reached the end of ‘the_list’.

Index in a List

Given a list:

days_of_week = ["Mon", "Tues", "Wed", "Thurs", "Fri", "Sat", "Sun"]

you can reference each value based on its index or position in the list. Each position, left to right, has a number associated with it starting at 0. We can pull the value of the first position and print it to the console:

Above, the variable ‘first_index’ is assigned the value of the first position in the days_of_week list which is ‘Mon’. The variable ‘first_index’ is then printed to the console.

We can inspect the second position by adding this line to the code:

days_of_week[1]

Im going to assign it to a variable ‘second_index’ and print it to the console:

Enumerate Function

We can use the built in Python ‘enumerate’ function to print out the index of each place in days_of_week:

Happy Coding

We have only just scratched the surface of the Python Programming Language but hopefully this is enough to get you started and curious. W3C Schools is always a great resource for anything coding related so check it out to continue down this Python wormhole!

--

--

Tom Tobar
The Startup

Motorcycle Mechanic turned Full Stack Web Dev