Getting started with Python for complete beginners
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.
-
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. >>>
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 world
Congratulations, 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 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.
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.5
-
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!
-
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
-
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: -
Type the following command:
print(total_animals)
The following output displays:
5
total_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.
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")
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:
-
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 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?
-
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 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 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 manyelif
statements as you want. -
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.
-
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")
-
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.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, 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 = 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 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.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.
Visit our Help Center and find the answers to your most frequent questions.
Visit Help Center