The terminal application usually has an icon similar to this:
Getting started with Python for complete beginners
- 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.
-
Open the terminal on your computer.
TipNoteIf you installed Python via Anaconda, instead of the terminal open the Anaconda Prompt.
-
Type the following command into the shell, and hit enter:
python3An 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.>>>TipPython 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 shorterpython
command.
To exit the interactive shell at any time, typeexit()
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' '
-
Type the following command into the shell and hit enter:
print("Hello world")The following output displays:
Hello worldCongratulations, you’re now a Python programmer!
-
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.
-
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. -
Type the following command into the shell and hit enter:
print(my_new_variable)The following output displays:
Hello worldWhen 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.
TipThe 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.
Type Description Example of variable assignment int A whole number my_variable = 3
float A decimal number my_variable = 2.667
string A character, or sequence of characters. Represents text, not numbers to be used in calculation. my_variable = "I saw 7 sheep"
boolean A true or false value. my_variable = True
list A 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: -
Type the following command into the shell and hit enter:
my_new_variable = 3.5TipRemember that no quotation marks should be used for number variables.
-
Type the following command into the shell and hit enter:
print(my_new_variable)The following output displays:
3.5Let’s see how you can use Python to do mathematical operations on number variables. It is pretty simple!
-
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 = 3cats = 2total_animals = dogs + catsprint(total_animals)The following output displays, showing you the total number of dogs and cats:
5 -
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 += 1print(dogs)The following output displays, and we see that
dogs
is now 4 instead of 3:4Has the value of
total_animals
also increased, to show that we now have 4 dogs and 2 cats? Let’s check: -
Type the following command:
print(total_animals)The following output displays:
5total_animals
still has a value of5
. 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 statementtotal_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
anddogs = 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: enter3+2
and Python will display the result of5
.
- You can choose whether to include spaces in your commands or not.
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).
-
Enter the following into the Python shell:
if dogs > cats:print("There are more dogs than cats")NoteNote 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 catsThe 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:
- The first line contains the condition, in the format:
-
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.
-
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 dogsWe have 2 cats and 4 dogs, so the printed statement is true!
However, what if we had an equal number of dogs and cats?
-
Enter the following into the Python shell:
cats = 3dogs = 3if 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 dogsThe 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 anelif
. This is the final possible component you can add to this type of statement, and allows you to deal with multiple conditions. -
Enter the following into the Python shell. The values of
cats
anddogs
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 dogsOur
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 manyelif
statements as you want.TipWe’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 Type Operator(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 ofa
)Assignment -=
Use to reassign the value of a variable by subtracting ( a -=25
subtracts 5 from the current value ofa
)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
gives1
(11/2 = 5, with remainder of 1Comparison >
<
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.
-
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.
-
Open a text editor.
TipThis 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.
-
Type the following code into a blank file in your text editor. Remember to pay attention to indentation.
cats = 11dogs = 5if 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") -
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
-
Open the terminal, as you did in the earlier step.
-
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.pyThe following output displays:
There are more cats than dogsPython 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, viacd /home/users/
) you can run the code directly just by typingpython3 animals.py
.Let’s try modifying the code in our file one final time.
-
Open
animals.py
in your text editor, overwrite the existing code with the following, and save:cats = 11dogs = 12too_many_pets = Falseif cats + dogs >= 20:too_many_pets = Trueif 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 ofFalse
- We use an
if
statement to change the value oftoo_many_pets
to True if the total number of animals isgreater than or equal to
(>=
) 20 - We put an
if
statement inside anif statement
, to say that if there aretoo_many_pets
it should print text to say so, AND then do some furtherif/elif/else
tests to choose a string to print with a recommendation about rehoming. The finalelse
statement is carried out if the initialif too_many_pets
condition was found to be untrue.
- We have introduced a boolean variable
-
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.pyThe 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.