programming with python. Image shows programmer and the Python symbol

How to get started with Python | Basic Programming 1

This will be the first post in a series of articles about how to program with Python. I plan to make these tutorials useful for anyone looking to start their programming journey as well as those with some experience in other languages. Therefore, I will assume only very basic knowledge of computer science.

For this post, I’m using Python 3.7 on Ubuntu 20.04 64-bit but most of the stuff here should work for newer versions as well.

By the end of this first tutorial, you should feel comfortable getting your way around Python.

Why Python?

Currently one of the most popular programming languages is Python. I chose to specialize in this language because of its versatility and flexibility, especially in scientific applications.

Python prioritizes code clarity and readability with clear and intuitive syntax. Moreover, unlike compiled languages such as C and C++, Python is interpreted. This means we can test changes in our code much faster and reduce development time significantly.

For these reasons, I think Python is the perfect language to learn programming concepts for beginners but also for anyone interested in data science and other similar applications.

Configure Miniconda with Python

There are a few ways to configure a Python development environment. The one I’ll be using is the Conda package manager.

Note: Conda is a package manager that allows us to install new libraries in Python with a simple command in the terminal. On the other hand, Miniconda is an installation package that already includes conda and python as well as some essential libraries. Finally, Anaconda is a full installation package that contains many libraries. I suggest to start with Miniconda and install any new libraries as needed.

Go to the official site for Miniconda and download the appropriate installation package for your system. It’s likely that your system is 64-bit but if you are not sure, I found this article explaining how to check this.

Once you have the installer downloaded, follow installation instructions from the official site here.

At the end of this process, Conda should be installed in your system and be ready to use. On Ubuntu, Conda should be accessible from the usual terminal if you added it to the path during installation.

On Windows 10, the Conda terminal can be quickly found by pressing the “Windows” key on the keyboard and then typing “cmd” to search for the program. Among the search results, you should see “Anaconda Prompt“. Click on it to open the Conda terminal.

You can double-check the Python version installed by calling the Python interpreter from within the Conda terminal:

python

Exit from the Python interpreter by using exit(). We should also update Conda while we are here. Use the following command in the terminal:

conda update conda

Conda will check all the packages that need an update and will wait for confirmation to proceed with the updates.

Installing An IDE

VS Code is my preferred IDE for any language.

IDE stands for Integrated Development Environment. An IDE is basically a text editor with handy functionality for programming languages.

My preferred IDE is Visual Studio Code (VS Code), and here you can find the official installation instructions. What I like the most is that it supports a number of plugins and integrates well with git and Conda environments.

“Hello World” in Python

We will start with the most trivial example in Python: output “Hello World” text to the console. You can create a new Python file using the IDE, or type the following directly from the terminal (inside the Python interpreter):

print("Hello World")

print is a built-in Python function. Functions are pieces of reusable code. In this case, print takes a string in quotation marks and displays text on the terminal.

That’s all we need to get text output to the console. In order to run our script, we first should save our file. It can go to any folder but I suggest creating a folder for programming projects to stay organized. Let’s save the file as “example.py

With the file saved, we can run it from any terminal by navigating to the folder containing the file. We can also open a terminal window from within VS Code. The top bar should have a tab called Terminal. Then run the following command:

python example.py

The output “Hello World” should appear on the console. Congratulations, you wrote your first Python program!

Basic Python Data Types

Python has many built-in objects to represent different data types. Among those we can find the following:

  • int : (integers)
  • float : (floating-point number)
  • str : (string/text)
  • list: A container type that can hold any number of other types.
  • I will cover other types (dictionaries, sets, tuples, etc) in a future post.

We can experiment with these types:

#This is a comment. The interpreter will ignore
#    anything that comes after a pound ("#") sign 
#    on the same line.
# We can use comments to explain or clarify 
#    parts of our code.
# This can be useful later when collaborating with 
#    others or simply to remember what was done

#-- here we are defining an int variable
num = 145

#-- now we define a float variable
f = 3.14

#-- next we define a string variable
str_example = "Hi, this is a string"

#-- declaring a list of ints
num_list = [1,2,3,400,1000,3000]

#-- we can mix any objects inside a list: ints, floats, strings, sub-lists, etc
#-- we can also add our previous variables to the list:
mixed_list = [num, f, str_example, num_list]

#let's print some of the variables to the terminal
print(f"str example:\n\t{str_example}\n")

print(f"List of integers:\n{num_list}\n")

print(f"Mixed list:\n{mixed_list}\n")

We can save the file in the same way as we did before and run it from the terminal to see the output of the print statements:

Output of the different data types covered here.

Write a Python Function

While writing a program we often need functionality that is not directly included into the language and we need to create it ourselves.

Python comes with the built-in keyword def for defining functions. It is followed by the name of the function and in parenthesis, we put the parameters it needs to do its job. For instance, the following function is a simple area calculator for a square:

def area_square(width,height):
    area = width * height  
    return area

In the example, we are using the keyword def to define a function called area_square. Next, in parenthesis, we put the arguments needed by our function: width and height. We can give our function and its arguments any name we want (as long as it conforms with Python naming rules).

Those with experience in other languages like C will notice that in Python we don’t specify the type of our variables or return values.

Additionally, blocks of code are not delimited inside curly braces ({}) but instead are determined by indentation hierarchy. In the function above, the body starts after the colon “:” and is indented from the def keyword. By convention, indentations are four spaces but as long as it is consistent it will work.

How to Call a Function in Python

Above we defined a function to compute square areas based on the width and height of a box. On its own, the definition doesn’t do anything. We need to call it from somewhere in our code in order to execute it.

If we run the script with the definition, we can test it from the interpreter by providing it with two values for width and height:

print(area_square(width=200,height=100))

Example Program With User Input

In this section, we will see a more complete example of a simple Python program. Our script will ask the user to enter his/her name and height in centimeters. Then it will output a personalized greeting message with the height converted to inches.

Let’s go piece by piece. We will first write a couple of functions to convert the input values:

def cm_to_inches(height_in_cm:float) -> float:
    # Here we define a conversion factor (you can google it)
    conversion_factor = 2.54

    #to get inches we divide the height in cm by the conversion factor
    height_in_inches = height_in_cm / conversion_factor

    #After we have our result we need to return it outside the function
    return height_in_inches

def cm_to_imperial(height_in_cm:float) -> tuple:
    height_in = cm_to_inches(height_in_cm)

    full_feet        = height_in // 12 # double // returns only integer part
    remainder_inches = height_in % 12 #get the remainder of the division

    return (full_feet, remainder_inches)

For these functions, I’m using type-hints (-> float, -> tuple, etc) to clarify the code. I have another post explaining how to use type-hints. You can check it out to learn more about them.

User Input And String Formatting

Our main code will go inside a function named main to make it clear that it is the entry point to our application. Here is where we will ask the user for input:

def main():
    # We will print a title first
    print("Cm to Inches Conversion")
    
    #We ask the user to input data using a built-in function called "input"
    name      = input("Enter your name: ")
    cm_height = float(input("Enter your height in cm: "))

    #Now we call our conversion function on the user data 
    in_height = cm_to_inches(cm_height)
    feet, inches = cm_to_imperial(cm_height)

    #Finally, we show a personalized message with converted height
    print(f"\nHello {name}!\n")
    print(f"Your height is {in_height:.2f} inches")
    print(f"""You are {feet:.0f}'{inches:.0f}" tall""")

The built-in function input will prompt the user with the text we provide and capture that user’s input as a string. However, we need the height as a float to be able to perform mathematical operations on it, so we convert it to a float on line 7 before storing it in the variable cm_height.

The last three lines use Python f-strings to format the text. I will write another post about how to use them in the future.

Finally, to test the program we must first call our main function. It will go under a conditional that makes our code more reusable:

if __name__ == "__main__":
    main()

This little conditional prevents our code from getting executed when we want to call some functions from a different script. Our code will be more reusable this way but I will touch on this another day. For now, just know that it is considered good practice to structure our Python code this way.

Full Python Code

Below is the program with all the pieces put together:

def cm_to_inches(height_in_cm:float) -> float:
    # Here we define a conversion factor (you can google it)
    conversion_factor = 2.54

    #to get inches we divide the height in cm by the conversion factor
    height_in_inches = height_in_cm / conversion_factor

    #After we have our result we need to return it outside the function
    return height_in_inches

def cm_to_imperial(height_in_cm:float) -> tuple:
    height_in = cm_to_inches(height_in_cm)

    full_feet        = height_in // 12 # double // returns only integer part
    remainder_inches = height_in % 12 #get the remainder of the division

    return (full_feet, remainder_inches)
    
def main():
    # We will print a title first
    print("Cm to Inches Conversion")
    
    #We ask the user to input data using a built-in function called "input"
    name      = input("Enter your name: ")
    cm_height = float(input("Enter your height in cm: "))

    #Now we call our conversion function on the user data 
    in_height = cm_to_inches(cm_height)
    feet, inches = cm_to_imperial(cm_height)

    #Finally, we show a personalized message with converted height
    print(f"\nHello {name}!\n")
    print(f"Your height is {in_height:.2f} inches")
    print(f"""You are {feet:.0f}'{inches:.0f}" tall""")

if __name__ == "__main__":
    main()

We can save this script (I saved it as convert_height.py) and run it from the terminal as in the previous examples:

Running the script with Python to convert heights from cm to imperial units

Final Thoughts

This post became longer than I expected. We covered the basic elements of Python programming: variables and functions. I will write more posts like this so that beginners can learn from them. Here is a collection of my programming posts, with many of them focusing on data science and visualization.

Let me know in the comments if you have any questions or suggestions and don’t forget to signup for the newsletter email. It will keep you up to date with my new posts.

Have anything in mind?