NavigationContentFooter
Jump toSuggest an edit

Getting started with Python for complete beginners

Reviewed on 12 August 2024Published on 25 January 2023
  • python
  • elif
  • variables
  • hello-world
  • boolean

This tutorial shows you how to get started with the programming language Python. Python is a great choice if you have never coded before: it is free, it reads like real English, and it is fast and simple to learn the basics. What’s more, Python often figures in the top three of the most in-demand languages by recruiters.

Read on to learn how to install Python on your computer, and learn and practice some basic concepts of this programming language. When you’re done, you can move on to the second tutorial in this series.

1: Installing Python

The first essential step is to install Python on your computer - but why, and what does this mean exactly? In order to code with Python, we need our machine to be able to interpret Python, that is to say to read our code, check that the code obeys the rules of Python, and carry out the actions we asked for in the code. To this end, we must install Python on our machine.

We give you two main options for installing Python:

Option A: Download and install from python.org

Python.org is the home of the official Python Software Foundation, which produces and maintains Python.

Follow their beginners guide to download and install the correct version of the Python interpreter for your operating system (Windows, Mac, or Linux).

Option B: Download and install via Anaconda

Anaconda bundles together the basic Python interpreter with some other useful tools that can make the Python experience more user-friendly, notably:

  • Extra packages such as NumPy, pandas, SciPy, and Matplotlib. At a basic level, you can think of packages like “add-ons”, letting you use extra commands and functions in your code that do not come with the basic Python installation. For example, the NumPy package gives you a range of complex mathematic functions and random number generators.
  • Conda: a package manager, which makes it easy for you to install and manage other Python packages in the future.
  • Jupyter Notebook: an application that runs in your web browser, and gives you a user-friendly alternative to running your code in the terminal.

To download Anaconda (and benefit from the Python interpreter plus these extra features), download and install the correct version depending on your operating system on this page.

2: Getting ready to code: opening the Python Interactive Shell

We will be coding from the terminal, also referred to as the command line or Command Line Interface. We’ll start off by using the Python Interactive Shell, which is great for testing quick snippets of code. Later, we’ll show how you can write and save all your code in a text file, and just use the terminal to run the code.

  1. Open the terminal on your computer.

    Tip

    The terminal application usually has an icon similar to this:

    Note

    If you installed Python via Anaconda, instead of the terminal open the Anaconda Prompt.

  2. Type the following command into the shell, and hit enter:

    python3

    An output similar to the following displays, showing that you are in the Python Interactive Shell:

    Python 3.9.12 (main, <date>, <time>)
    [GCC 5.4.0 20160609] on <OS>
    Type "help", "copyright", "credits" or "license" for more information.
    >>>
    Tip

    Python is now on its third major release version, which is the version that will have been installed on your machine during the previous step, hence python3. Different operating systems may handle the naming of Python differently: you may be able to use the shorter python command.

    To exit the interactive shell at any time, type exit() and hit enter.

You’re now ready to start coding with Python!

3: Hello world and the print() command

You might have heard people talk about “Hello world” before. When learning a new programming language, “Hello World” generally refers to the most basic task possible: coding something that displays “Hello world” on the screen. You can think of it as the entry-level onboarding task to familiarize yourself with the basic syntax of the language.

So how do we get Python to display “Hello World”? The answer is: via the print() command. This has nothing to do with printing onto paper, and everything to do with displaying text. You can think of it like “printing” something to the screen.

  • The brackets () contain the text you want to print
  • The text must be contained in quotation marks " " or ' '
  1. Type the following command into the shell and hit enter:

    print("Hello world")

    The following output displays:

    Hello world

    Congratulations, you’re now a Python programmer!

  2. Use the print(" ") command to practice displaying any text of your choice.

4: Variables and assignment

Variables are used to store and label data. They are a key part of any programming language: they help us to organize and manipulate data, in a way that is readable by a human but understandable by the programming language.

  1. Type the following command into the shell and hit enter:

    my_new_variable = "Hello world"

    No output displays. This is because you have created a new variable (with the label my_new_variable) and assigned it (with the = operator) a value (Hello world) but you have not asked Python to do anything with that variable. Let’s try that in the next step.

  2. Type the following command into the shell and hit enter:

    print(my_new_variable)

    The following output displays:

    Hello world

    When we ask Python to print the variable, it displays the value of that variable. Note that this time we did not use quotation marks in our print statement: these are only necessary for strings, not for variables or numbers.

    Tip

    The variable we created holds string data. Let’s look at just some of the different types of data we can store inside a variable, and how the data type affects the syntax of creating and assigning variables.

    TypeDescriptionExample of variable assignment
    intA whole numbermy_variable = 3
    floatA decimal numbermy_variable = 2.667
    stringA character, or sequence of characters. Represents text, not numbers to be used in calculation.my_variable = "I saw 7 sheep"
    booleanA true or false value.my_variable = True
    listA collection of values. These values could be ints, floats, strings, booleans etc, or a mixture.my_variable = [1, 7, "hello", 2.5, True]

    With Python, there is no need to specify what type of variable you are creating. It automatically understands from the syntax of the creation statement (for example, whether there are quotation marks, or whether a number has a decimal point) what type the variable should be.

    These are not all the data types available in Python, but they are the main ones you’ll need to get started with the basics.

    You can change the value of a variable from one thing to another. Next, we change my_new_variable so that instead of holding the string “Hello world”, it now contains the float (decimal number) 3.5:

  3. Type the following command into the shell and hit enter:

    my_new_variable = 3.5
    Tip

    Remember that no quotation marks should be used for number variables.

  4. Type the following command into the shell and hit enter:

    print(my_new_variable)

    The following output displays:

    3.5

    Let’s see how you can use Python to do mathematical operations on number variables. It is pretty simple!

  5. Enter the following commands one by one. With these commands, you assign different numbers to different variables, then create a new variable that adds them together and prints the result:

    dogs = 3
    cats = 2
    total_animals = dogs + cats
    print(total_animals)

    The following output displays, showing you the total number of dogs and cats:

    5
  6. Type the following commands to use the += operator, which handily allows you to increase the value of a number variable by the amount specified:

    dogs += 1
    print(dogs)

    The following output displays, and we see that dogs is now 4 instead of 3:

    4

    Has the value of total_animals also increased, to show that we now have 4 dogs and 2 cats? Let’s check:

  7. Type the following command:

    print(total_animals)

    The following output displays:

    5

    total_animals still has a value of 5. This shows us something important: variables do not recalculate their values based on other variables they were created from, unless we explicitly tell them to. We must rerun the statement total_animals = dogs + cats to get it to recalculate its value.

    Tip
    • You can choose whether to include spaces in your commands or not. dogs=3 and dogs = 3 do the same thing.
    • While you’re in the Python Interactive Shell, you can skip the print() command to display the value of a variable! Just type the variable name and hit enter, and the value will display. You can also use this tip if you want to use the shell as a basic calculator: enter 3+2 and Python will display the result of 5.

5: If statements

This is where things start to get really interesting! If statements are fundamental to a lot of computer programs and scripts. They tell Python to only carry out an action if a certain condition is satisfied. Let’s try some examples.

We assume that, as per our previous commands, we already have the variables dogs (=4) and cats (=2).

  1. Enter the following into the Python shell:

    if dogs > cats:
    print("There are more dogs than cats")
    Note

    Note the syntax of an if statement:

    • The first line contains the condition, in the format: if condition :
    • The second line is indented with a tab or four spaces, and contains the command to execute if the condition is fulfilled. Indentation is crucial in Python for the code to be interpreted correctly. Make sure you always follow the indentation pattern shown in examples.

    Hit enter twice after you have finished typing, to make it clear to the Python shell that you do not have any other elements to add to this command.

    The following output displays:

    There are more dogs than cats

    The condition was true - the number of dogs is 4 which is greater than the number of cats (2) - so the print statement was executed. Let’s see what happens if we reverse the condition:

  2. Enter the following into the Python shell:

    if cats > dogs:
    print("There are more cats than dogs")

    No output displays!

    We can see that the print statement is not executed, as the condition is not true.

    Let’s add an “else” statement. This lets us tell Python to do one thing if the condition is true, and a different thing if it is false.

  3. Enter the following into the Python shell:

    if cats > dogs:
    print("There are more cats than dogs")
    else:
    print("There are fewer cats than dogs")

    The following output displays:

    There are fewer cats than dogs

    We have 2 cats and 4 dogs, so the printed statement is true!

    However, what if we had an equal number of dogs and cats?

  4. Enter the following into the Python shell:

    cats = 3
    dogs = 3
    if cats > dogs:
    print("There are more cats than dogs")
    else:
    print("There are fewer cats than dogs")

    The following output displays:

    There are fewer cats than dogs

    The statement outputted by Python is incorrect, as in fact the number of dogs and cats is the same. Python checked to see if the number of cats was greater than the number of dogs, and when that condition was false, it printed the else statement without checking anything else. This is a great example of how code is interpreted completely logically by Python, but if you, the human programmer, are not careful, you can end up with bugs.

    Let’s modify the if/else statement to add an elif. This is the final possible component you can add to this type of statement, and allows you to deal with multiple conditions.

  5. Enter the following into the Python shell. The values of cats and dogs should both remain at 3 from our previous input.

    if cats > dogs:
    print("There are more cats than dogs")
    elif cats == dogs:
    print("There are the same number of cats and dogs")
    else:
    print("There are fewer cats than dogs")

    The following output displays:

    There are the same number of cats and dogs

    Our elif condition (else if) told Python to check for the possibility that the number of cats and dogs were equal to each other (represented with ==) and added an output for this possibility. The printed statement is correct.

    Try changing the number of cats and dogs and/or playing with the if/elif/else statement to see how the output is affected. You can add as many elif statements as you want.

    Tip

    We’ve seen a number of operators already in the code examples we’ve used. Let’s take a look in more detail at just some of the different Python operators.

    Operator TypeOperator(s)Description
    Assignment=Use to assign a value to a variable (a = 3)
    Assignment+=Use to reassign the value of a variable by adding (a +=2 adds 2 to the current value of a)
    Assignment-=Use to reassign the value of a variable by subtracting (a -=25 subtracts 5 from the current value of a)
    Arithmetic+ - * /Use these operators in your code to add, subtract, multiply and divide.
    Arithmetic% ModuloGet the remainder when two numbers are divided. For example, 11 % 2 gives 1 (11/2 = 5, with remainder of 1
    Comparison> <Use to check whether a value is greater than another (a > b) or less than another (a < b)
    Comparison>= <=Use to check whether a value is greater than or equal to another (a >= b) or less than or equal to another (a <= b)
    Comparison==Use to check whether a value is equal to another (a == b)
    Comparison!=Use to check whether a value is not equal to another (a != b)

    Note the difference between using a single = to assign a value to a variable (cats = 2) versus using a double == as the is equal to conditional operator, which tests whether two values/variables have the same value (if cats == dogs).

    These are not all the operators available in Python, but they give you a good range to get started. Try playing with some of the code examples in this tutorial to use different operators and see how the output changes.

  6. Exit the Python Interactive Shell by entering the following command:

exit()

6: From the shell to a script

So far, we’ve been doing all our coding in the Python Interactive Shell, where you type your code directly into the terminal, and it spits out the output. Although this is great for testing and playing around, it has its limitations. Often when writing code, you will write in a text file, save the file with a .py extension, and then execute the file in the terminal. Let’s see how to do that next.

  1. Open a text editor.

    Tip

    This could simply be the default text editor that comes with your operating system, e.g. Notepad for Windows users or TextEdit for Apple users. However, we recommend that you download and install a text editing application that is specifically geared towards coding. Applications such as Visual Studio Code or Sublime Text can be used as very basic text editors, just like Notepad, but also offer a range of extra features and extensions that will help you along your coding journey.

    Check out the official download and installation guides for Visual Studio Code or Sublime Text to install one of these programs to your machine. You do not need to worry about all the extra features right now, though they will be useful to you in the future. You can start off just using it as a basic text editor, to write text and save it in a file.

  2. Type the following code into a blank file in your text editor. Remember to pay attention to indentation.

    cats = 11
    dogs = 5
    if cats > dogs:
    print("There are more cats than dogs")
    elif cats == dogs:
    print("There are the same number of cats and dogs")
    else:
    print("There are fewer cats than dogs")
  3. Save the file as animals.py. Take note of where you save this file, specifically the path to the file. If you are using a graphical interface for your OS, you should be able to right-click the saved file and choose properties or similar to see the path of the file, e.g. /home/user/animals.py

  4. Open the terminal, as you did in the earlier step.

  5. Tell Python to run the code in animals.py by entering the following command. Make sure you replace the path to the file with the path you noted in step 3.

    python3 /home/user/animals.py

    The following output displays:

    There are more cats than dogs

    Python has read our .py file and the output displays directly to the terminal. This makes it really easy to edit and play around with the code in your file, save it, and run it again to see how your changes affect the output. If you navigate within the terminal to the location of the file (in this case, via cd /home/users/) you can run the code directly just by typing python3 animals.py.

    Let’s try modifying the code in our file one final time.

  6. Open animals.py in your text editor, overwrite the existing code with the following, and save:

    cats = 11
    dogs = 12
    too_many_pets = False
    if cats + dogs >= 20:
    too_many_pets = True
    if too_many_pets == True:
    print("You have too many pets!")
    if cats > dogs:
    print("You should rehome some cats")
    elif cats == dogs:
    print("You should rehome some cats or dogs")
    else:
    print("You should rehome some dogs")
    else:
    print("Enjoy your pets!")

    Note the following changes:

    • We have introduced a boolean variable too_many_pets, which starts with a value of False
    • We use an if statement to change the value of too_many_pets to True if the total number of animals is greater than or equal to (>=) 20
    • We put an if statement inside an if statement, to say that if there are too_many_pets it should print text to say so, AND then do some further if/elif/else tests to choose a string to print with a recommendation about rehoming. The final else statement is carried out if the initial if too_many_pets condition was found to be untrue.
  7. Tell Python to run the code in animals.py by entering the following command. Make sure you replace the path to the file with the path you noted in step 3:

    python3 /home/user/animals.py

    The following output displays:

    You have too many pets!
    You should rehome some dogs

Summary

Time to recap everything we have learned in this tutorial:

Python Interactive Shell: to code directly in the Python Interactive Shell, enter python3 in your terminal, and you are ready to go. Enter your input statements, and Python will produce an output based on your code. Type exit() to leave the interactive shell.

Coding in a script: to write your code in a script, save it in a text file with the .py extension and then enter python3 path/to/script/myfile.py in the terminal to run the script.

Print statements: “printing” in Python just means displaying an output. The print statement syntax is print("hello world!"). If you’re printing a number, boolean, or variable, you should omit the quotation marks.

Variable types and assignment: to assign a value to a variable, use the = operator. Depending on the syntax we use, Python knows what type of variable to create. a = 1 creates an int, a = 1.5 creates a float, a = "1" creates a string, a = True creates a boolean, a = [1, 2, 3] creates a list. You can change the value of a variable after creating by just repeating the a = statement and finishing with the new value you want.

If statements: use if statements to test whether certain conditions are true, and tell Python to vary the next actions accordingly. You can choose to add elif statements to add further conditions to test for and conditional actions to carry out, and/or an else statement to show what to do if the if condition is not met. The comparison operators >, <, >=, <=, == and != are particularly useful to use when creating conditions in if and elif statements.

Do not hesitate to play around with all the code examples in this tutorial and see how changing the code changes the output. For example:

  • What happens if you use the + operator to add two string variables together, and print the result?
  • Can you modify the “cats and dogs” if/else statement to include other animals and print other outputs like “Your pet is lonely, get more pets!” if there is only one cat or dog?
  • Can you write an if/else statement that tests whether any number is odd or even and prints a statement like <number> is an even number? Hint: try using the modulo operator.

Next steps

Check out the second tutorial in our Python beginner series, on lists and dictionaries.

Was this page helpful?
API DocsScaleway consoleDedibox consoleScaleway LearningScaleway.comPricingBlogCareers
© 2023-2024 – Scaleway