Are you looking for a place to learn the basics of how to use Python from a beginner’s perspective? Do you want to get up and running with Python but don’t know where to start? If so, then this tutorial is for you. This tutorial focuses on the essentials you need to know to start programming with Python.
In this tutorial, you’ll learn:
- What Python is and why you should use it
- What basic Python syntax you should learn to start coding
- How to handle errors in Python
- How to get help quickly in Python
- What code style you should apply in your code
- Where to get extra functionalities without reinventing the wheel
- Where to find quality Python content and grow your skills
You’ll also have the opportunity to create your first Python program and run it on your computer. Finally, you’ll have a chance to evaluate your progress with a quiz that’ll give you an idea of how much you’ve learned.
Free Bonus: Click here to get our free Python Cheat Sheet that shows you the basics of Python 3, like working with data types, dictionaries, lists, and Python functions.
Why You Should Use Python
Python, named after the British comedy group Monty Python, is a high-level, interpreted, interactive, and object-oriented programming language. Its flexibility allows you to do many things, both big and small. With Python, you can write basic programs and scripts and also to create complex and large-scale enterprise solutions. Here’s a sampling of its uses:
- Building desktop applications, including GUI applications, CLI tools, and even games
- Doing mathematical and scientific analysis of data
- Building web and Internet applications
- Doing computer systems administration and automating tasks
- Performing DevOps tasks
You can find Python everywhere in the world of computer programming. For example, Python is the foundation of some of the world’s most popular websites, including Reddit, Dropbox, and YouTube, to name a few. The Python web framework Django powers both Instagram and Pinterest.
Python has a bunch of features that make it attractive as your first programming language:
- Free: Python is available free of charge, even for commercial purposes.
- Open source: Anyone can contribute to Python development.
- Accessible: People of all ages, from school children to retirees, have learned Python, and so can you.
- Versatile: Python can help you solve problems in many fields, including scripting, data science, web development, GUI development, and more.
- Powerful: You can code small scripts to automate repetitive tasks, and you can also create complex and large-scale enterprise solutions with Python.
Compared to other programming languages, Python has the following features:
- Interpreted: It’s portable and quicker to experiment with than compiled languages.
- Multiparadigm: It lets you write code in different styles, including object-oriented, imperative, and functional style.
- Dynamically typed: It checks variable types at runtime, so you don’t need to declare them explicitly.
- Strongly typed: It won’t let unsafe operations on incompatible types go unnoticed.
There’s a lot more to learn about Python. But by now, you should have a better idea of why Python is so popular and why you should consider learning to program with it.
How to Download and Install Python
Python works on Linux, Mac, Windows, and several other platforms. It comes preinstalled on macOS and on most Linux distributions. However, if you want to be up to date, then you probably need to download and install the latest version. You also have the choice of using different Python versions in different projects if you want to.
To check what Python version has been installed globally in your operating system, open the terminal or command line and run the following command:
$ python3 -V
This command prints the version of your system’s default Python 3 installation. Note that you use python3
instead of python
because some operating systems still include Python 2 as their default Python installation.
Installing Python From Binaries
Regardless of your operating system, you can download an appropriate version of Python from the official site. Go there and grab the appropriate 32-bit or 64-bit version for your operating system and processor.
Selecting and downloading a Python binary from the language’s official site is often a good choice. However, there are some OS-specific alternatives:
- macOS: You have the option of installing Python from Homebrew.
- Linux: You can install several Python versions using your distribution’s package manager.
- Windows: You can install Python from the Microsoft Store.
You can also use the Anaconda distribution to install Python along with a rich set of packages and libraries, or you can use Miniconda if you want to install only the packages you need.
Note: There are several options for managing Python versions and environments. Choosing the right tools for this task can be overwhelming when you’re starting with the language.
For a guide on this subject, check out An Effective Python Environment: Making Yourself at Home.
For further instructions on installing Python on different platforms, you can check out Python 3 Installation & Setup Guide.
Running Your Python Interpreter
You can do a quick test to ensure Python is installed correctly. Fire up your terminal or command line and run the python3
command. That should open a Python interactive session, and your command prompt should look similar to this:
Python 3.9.0 (default, Oct 5 2020, 17:52:02)
[GCC 9.3.0] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>>
While you’re here, you might as well run your first line of code:
>>> print("Python is fun!")
Python is fun!
That’s it! You’ve just written your first Python program! When you’re done, you can use exit()
or quit()
to leave the interactive session, or you can use the following key combinations:
- macOS and Linux: Ctrl+D
- Windows: Ctrl+D and then press Enter
Keep your terminal or command line open. You still have more to do and learn! You’ll start by learning the basics of Python syntax.
The Basic Python Syntax
The Python syntax is clear, concise, and focused on readability. Readability is arguably one of the more attractive features of the language itself. It makes Python ideal for people who are learning to program. In this section, you’ll learn about several important components of the Python syntax:
This knowledge will help you get up and running with Python. You’ll be able to create your own programs in almost no time.
Comments
Comments are pieces of text that live in your code but are ignored by the Python interpreter as it executes the code. You can use comments to describe the code so that you and other developers can quickly understand what the code does or why the code is written in a given way. To write a comment in Python, just add a hash mark (#
) before your comment text:
# This is a comment on its own line
The Python interpreter ignores the text after the hash mark and up to the end of the line. You can also add inline comments to your code. In other words, you can combine a Python expression or statement with a comment in a single line, given that the comment occupies the final part of the line:
var = "Hello, World!" # This is an inline comment
You should use inline comments sparingly to clear up pieces of code that aren’t obvious on their own. In general, your comments should be short and to the point. PEP 8 advises keeping comments at 72 characters or less. If your comment is approaching or exceeding that length, then you might want to spread it out over multiple lines:
# This is a long comment that requires
# two lines to be complete.
If you need more room for a given comment, then you can use multiple lines with a hash mark on each. This way, you can keep your comments under 72 characters in length.
Variables
In Python, variables are names attached to a particular object. They hold a reference, or pointer, to the memory address at which an object is stored. Once a variable is assigned an object, you can access the object using the variable name.
You need to define your variables in advance. Here’s the syntax:
variable_name = variable_value
You should use a naming scheme that makes your variables intuitive and readable. The variable name should provide some indication as to what the values assigned to it are.
Sometimes programmers use short variable names, such as x
and y
. These are perfectly suitable names in the context of math, algebra, and so on. In other contexts, you should avoid single-character names and use something more descriptive. That way, other developers can make an educated guess of what your variables hold. Think of others, as well as your future self, when writing your programs. Your future self will thank you.
Here are some examples of valid and invalid variable names in Python:
>>> numbers = [1, 2, 3, 4, 5]
>>> numbers
[1, 2, 3, 4, 5]
>>> first_num = 1
>>> first_num
1
>>> 1rst_num = 1
File "<input>", line 1
1rst_num = 1
^
SyntaxError: invalid syntax
>>> π = 3.141592653589793
>>> π
3.141592653589793
Your variable names can be any length and can consist of uppercase and lowercase letters (A-Z
, a-z
), digits (0-9
), and also the underscore character (_
). In sum, variable names should be alphanumeric, but note that even though variable names can contain digits, their first character can’t be a digit.
Note: The lower_case_with_underscores naming convention, also known as snake_case, is commonly used in Python. It isn’t enforced, but it’s a widely adopted standard.
Finally, Python now offers full Unicode support, so you can also use Unicode characters in your variable names like you saw above with the variable π
.
Keywords
Like any other programming language, Python has a set of special words that are part of its syntax. These words are known as keywords. To get the complete list of keywords available in your current Python installation, you can run the following code in an interactive session:
>>> help("keywords")
Here is a list of the Python keywords. Enter any keyword to get more help.
False class from or
None continue global pass
True def if raise
and del import return
as elif in try
assert else is while
async except lambda with
await finally nonlocal yield
break for not
Each of these keywords plays a role in Python syntax. They are reserved words that have specific meanings and purposes in the language, so you shouldn’t use them for anything but those specific purposes. For example, you shouldn’t use them as variable names in your code.
There’s another way of getting access to the whole list of Python keywords:
>>> import keyword
>>> keyword.kwlist
['False', 'None', 'True', 'and', 'as', 'assert', 'async', 'await', 'break', 'cla
ss', 'continue', 'def', 'del', 'elif', 'else', 'except', 'finally', 'for', 'from
', 'global', 'if', 'import', 'in', 'is', 'lambda', 'nonlocal', 'not', 'or', 'pas
s', 'raise', 'return', 'try', 'while', 'with', 'yield']
keyword
provides a set of functions that allow you to determine if a given string is a keyword. For example, keyword.kwlist
holds a list of all the current keywords in Python. These are handy when you need to manipulate keywords programmatically in your Python programs.
Built-In Data Types
Python has a handful of built-in data types, such as numbers (integers, floats, complex numbers), Booleans, strings, lists, tuples, dictionaries, and sets. You can manipulate them with several tools:
In the next few sections, you’ll learn the basics of incorporating Python’s built-in data types into your programs.
Numbers
Python provides integers, floating-point numbers, and complex numbers. Integers and floating-point numbers are the most commonly used numeric types in day-to-day programming, while complex numbers have specific use cases in math and science. Here’s a summary of their features:
Number | Description | Examples | Python Data Type |
---|---|---|---|
Integer | Whole numbers | 1 , 2 , 42 , 476 , -99999 |
int |
Floating-point | Numbers with decimal points | 1.0 , 2.2 , 42.09 , 476.1 , -99999.9 |
float |
Complex | Numbers with a real part and an imaginary part | complex(1, 2) , complex(-1, 7) , complex("1+2j") |
complex |
Integer numbers have unlimited precision. Floating-point numbers’ precision information is available in sys.float_info
. Complex numbers have a real part and an imaginary part, which are both floating-point numbers.
Operators represent operations, such as addition, subtraction, multiplication, division, and so on. When you combine them with numbers, they form expressions that Python can evaluate:
>>> # Addition
>>> 5 + 3
8
>>> # Subtraction
>>> 5 - 3
2
>>> # Multiplication
>>> 5 * 3
15
>>> # Division
>>> 5 / 3
1.6666666666666667
>>> # Floor division
>>> 5 // 3
1
>>> # Modulus (returns the remainder from division)
>>> 5 % 3
2
>>> # Power
>>> 5 ** 3
125
These operators work with two operands and are commonly known as arithmetic operators. The operands can be numbers or variables that hold numbers.
Besides operators, Python provides you with a bunch of built-in functions for manipulating numbers. These functions are always available to you. In other words, you don’t have to import them to be able to use them in your programs.
Note: There are modules available in the Python standard library, such as math
, that also provide you with functions to manipulate numbers.
To use the functions associated with these modules, you first have to import the module and then access the function using module.function_name()
. Alternatively, you can import a function directly from the module using from module import function_name
.
Given an integer number or a string representing a number as an argument, float()
returns a floating-point number:
>>> # Integer numbers
>>> float(9)
9.0
>>> float(-99999)
-99999.0
>>> # Strings representing numbers
>>> float("2")
2.0
>>> float("-200")
-200.0
>>> float("2.25")
2.25
>>> # Complex numbers
>>> float(complex(1, 2))
Traceback (most recent call last):
File "<input>", line 1, in <module>
float(complex(1, 2))
TypeError: can't convert complex to float
With float()
, you can convert integer numbers and strings representing numbers into floating-point numbers, but you can’t convert a complex number into a floating-point number.
Given a floating-point number or a string as an argument, int()
returns an integer. This function doesn’t round the input up to the nearest integer. It simply truncates the input, throwing out anything after the decimal point, and returns the number. So, an input of 10.6
returns 10
instead of 11
. Similarly, 3.25
returns 3
:
>>> # Floating-point numbers
>>> int(10.6)
10
>>> int(3.25)
3
>>> # Strings representing numbers
>>> int("2")
2
>>> int("2.3")
Traceback (most recent call last):
File "<input>", line 1, in <module>
int("2.3")
ValueError: invalid literal for int() with base 10: '2.3'
>>> # Complex numbers
>>> int(complex(1, 2))
Traceback (most recent call last):
File "<input>", line 1, in <module>
int(complex(1, 2))
TypeError: can't convert complex to int
Note that you can pass a string representing an integer to int()
, but you can’t pass a string representing a floating-point number. Complex numbers don’t work either.
Besides these built-in functions, there are a few methods associated with each type of number. You can access them using attribute reference, also known as dot notation:
>>> 10.0.is_integer()
True
>>> 10.2.is_integer()
False
>>> (10).bit_length()
4
>>> 10.bit_length()
File "<input>", line 1
10.bit_length()
^
SyntaxError: invalid syntax
These methods can be a useful tool to learn about. In the case of integer numbers, to access their methods through a literal, you need to use a pair of parentheses. Otherwise, you get a SyntaxError
.
Booleans
Booleans are implemented as a subclass of integers with only two possible values in Python: True
or False
. Note that these values must start with a capital letter.
You use Boolean values to express the truth value of an expression or object. Booleans are handy when you’re writing predicate functions or when you’re using comparison operators, such as greater than (>
), lower than (<
), equal (==
), and so on:
>>> 2 < 5
True
>>> 4 > 10
False
>>> 4 <= 3
False
>>> 3 >= 3
True
>>> 5 == 6
False
>>> 6 != 9
True
Comparison operators evaluate to Boolean values, True
or False
. Feel free to play with them in your Python interactive session.
Python provides a built-in function, bool()
, that is closely related to Boolean values. Here’s how it works:
>>> bool(0)
False
>>> bool(1)
True
>>> bool("")
False
>>> bool("a")
True
>>> bool([])
False
>>> bool([1, 2, 3])
True
bool()
takes an object as an argument and returns True
or False
according to the object’s truth value. To evaluate the truth value of an object, the function uses Python’s truth testing rules.
On the other hand, int()
takes a Boolean value and returns 0
for False
and 1
for True
:
>>> int(False)
0
>>> int(True)
1
This is because Python implements its Boolean values as a subclass of int
, as you saw before.
Strings
Strings are pieces of text or sequences of characters that you can define using single, double, or triple quotes:
>>> # Use single quotes
>>> greeting = 'Hello there!'
>>> greeting
'Hello there!'
>>> # Use double quotes
>>> welcome = "Welcome to Real Python!"
>>> welcome
'Welcome to Real Python!'
>>> # Use triple quotes
>>> message = """Thanks for joining us!"""
>>> message
'Thanks for joining us!'
>>> # Escape characters
>>> escaped = 'can\'t'
>>> escaped
"can't"
>>> not_escaped = "can't"
>>> not_escaped
"can't"
Note that you can use different types of quotes to create string objects in Python. You can also use the backslash character (\
) to escape characters with special meaning, such as the quotes themselves.
Once you define your string objects, you can use the plus operator (+
) to concatenate them in a new string:
>>> "Happy" + " " + "pythoning!"
'Happy pythoning!'
When used on strings, the plus operator (+
) concatenates them into a single string. Note that you need to include a blank space (" "
) between words to have proper spacing in your resulting string. If you need to concatenate a lot of strings, then you should consider using .join()
, which is more efficient. You’ll learn about .join()
a little bit later in this tutorial.
Python comes with many useful built-in functions and methods for string manipulation. For example, if you pass a string as an argument to len()
, then you’ll get the string’s length, or the number of characters it contains:
>>> len("Happy pythoning!")
16
When you call len()
using a string as an argument, you get the number of characters, including any blank spaces, in the input string.
The string class (str
) provides a rich set of methods that are useful for manipulating and processing strings. For example, str.join()
takes an iterable of strings and joins them together in a new string. The string on which you call the method plays the role of a separator:
>>> " ".join(["Happy", "pythoning!"])
'Happy pythoning!'
str.upper()
returns a copy of the underlying string with all the letters converted to uppercase:
>>> "Happy pythoning!".upper()
'HAPPY PYTHONING!'
str.lower()
returns a copy of the underlying string with all the letters converted to lowercase:
>>> "HAPPY PYTHONING!".lower()
'happy pythoning!'
str.format()
performs a string formatting operation. This method provides a lot of flexibility for string formatting and interpolation:
>>> name = "John Doe"
>>> age = 25
>>> "My name is {0} and I'm {1} years old".format(name, age)
"My name is John Doe and I'm 25 years old"
You can also use an f-string to format your strings without using .format()
:
>>> name = "John Doe"
>>> age = 25
>>> f"My name is {name} and I'm {age} years old"
"My name is John Doe and I'm 25 years old"
Python’s f-strings are an improved string formatting syntax. They’re string literals with an f
at the beginning, outside the quotes. Expressions that appear in embedded curly braces ({}
) are replaced with their values in the formatted string.
Strings are sequences of characters. This means that you can retrieve individual characters from a string using their positional index. An index is a zero-based integer number associated with a specific position in a sequence:
>>> welcome = "Welcome to Real Python!"
>>> welcome[0]
'W'
>>> welcome[11]
'R'
>>> welcome[-1]
'!'
An indexing operation retrieves the character at the position indicated by the given index. Note that a negative index retrieves the element in reverse order, with -1
being the index of the last character in the string.
You can also retrieve a part of a string by slicing it:
>>> welcome = "Welcome to Real Python!"
>>> welcome[0:7]
'Welcome'
>>> welcome[11:22]
'Real Python'
Slicing operations take the element in the form [start:end:step]
. Here, start
is the index of the first item to include in the slice, and end
is the index of the last item, which isn’t included in the returned slice. Finally, step
is an optional integer representing the number of items to jump over while extracting the items from the original string. A step
of 2
, for example, will return every other element between start
and stop
.
Lists
Lists are usually called arrays in nearly every other programming language. In Python, lists are mutable sequences that group various objects together. To create a list, you use an assignment with a sequence of comma-separated objects in square brackets ([]
) on its right side:
>>> # Define an empty list
>>> empty = []
>>> empty
[]
>>> # Define a list of numbers
>>> numbers = [1, 2, 3, 100]
>>> numbers
[1, 2, 3, 100]
>>> # Modify the list in place
>>> numbers[3] = 200
>>> numbers
[1, 2, 3, 200]
>>> # Define a list of strings
>>> superheroes = ["batman", "superman", "spiderman"]
>>> superheroes
['batman', 'superman', 'spiderman']
>>> # Define a list of objects with different data types
>>> mixed_types = ["Hello World", [4, 5, 6], False]
>>> mixed_types
['Hello World', [4, 5, 6], False]
Lists can contain objects of different data types, including other lists. They can also be empty. Since lists are mutable sequences, you can modify them in place using index notation and an assignment operation.
Since lists are sequences just like strings, you can access their individual items using zero-based integer indices:
>>> numbers = [1, 2, 3, 200]
>>> numbers[0]
1
>>> numbers[1]
2
>>> superheroes = ["batman", "superman", "spiderman"]
>>> superheroes[-1]
"spiderman"
>>> superheroes[-2]
"superman"
Indexing operations also work with Python lists, so you can retrieve any item in a list by using its positional index. Negative indices retrieve items in reverse order, starting from the last item.
You can also create new lists from an existing list using a slicing operation:
>>> numbers = [1, 2, 3, 200]
>>> new_list = numbers[0:3]
>>> new_list
[1, 2, 3]
If you nest a list, a string, or any other sequence within another list, then you can access the inner items using multiple indices:
>>> mixed_types = ["Hello World", [4, 5, 6], False]
>>> mixed_types[1][2]
6
>>> mixed_types[0][6]
'W'
In this case, the first index gets the item from the container list, and the second index retrieves an item from the inner sequence.
You can also concatenate your lists using the plus operator:
>>> fruits = ["apples", "grapes", "oranges"]
>>> veggies = ["corn", "kale", "mushrooms"]
>>> grocery_list = fruits + veggies
>>> grocery_list
['apples', 'grapes', 'oranges', 'corn', 'kale', 'mushrooms']
Since lists are sequences of objects, you can use the same functions you use on any other sequence, such as strings.
Given a list as an argument, len()
returns the list’s length, or the number of objects it contains:
>>> numbers = [1, 2, 3, 200]
>>> len(numbers)
4
You can check out the Python documentation to see all available list methods. Below is a summary of some of the most commonly used methods.
list.append()
takes an object as an argument and adds it to the end of the underlying list:
>>> fruits = ["apples", "grapes", "oranges"]
>>> fruits.append("blueberries")
>>> fruits
['apples', 'grapes', 'oranges', 'blueberries']
list.sort()
sorts the underlying list in place:
>>> fruits.sort()
>>> fruits
['apples', 'blueberries', 'grapes', 'oranges']
list.pop()
takes an integer index as an argument, then removes and returns the item at that index in the underlying list:
>>> numbers_list = [1, 2, 3, 200]
>>> numbers_list.pop(2)
3
>>> numbers_list
[1, 2, 200]
Lists are quite common and versatile data structures in Python. They’re so popular that developers sometimes tend to overuse them, which can make the code inefficient.
Tuples
Tuples are similar to lists, but they’re immutable sequences. This means that you can’t change them after creation. To create a tuple object, can use an assignment operation with a sequence of a comma-separated items on its right side. You commonly use parentheses to delimit a tuple, but they’re not mandatory:
>>> employee = ("Jane", "Doe", 31, "Software Developer")
>>> employee[0] = "John"
Traceback (most recent call last):
File "<input>", line 1, in <module>
employee[0] = "John"
TypeError: 'tuple' object does not support item assignment
If you try to change a tuple in place, then you get a TypeError
indicating that tuples don’t support in-place modifications.
Just like lists, you can also do indexing and slicing with tuples:
>>> employee = ("Jane", "Doe", 31, "Software Developer")
>>> employee[0]
'Jane'
>>> employee[1:3]
('Doe', 31)
Since tuples are sequences, you can use indices to retrieve specific items in the tuples. Note that you can also retrieve slices from a tuple with a slicing operation.
You can also add two tuples using the concatenation operator:
>>> first_tuple = (1, 2)
>>> second_tuple = (3, 4)
>>> third_tuple = first_tuple + second_tuple
>>> third_tuple
(1, 2, 3, 4)
A concatenation operation with two tuples creates a new tuple containing all the items in the two input tuples.
Like with lists and strings, you can use some built-in functions to manipulate tuples. For example, len()
returns the length of the tuple, or the number of items it contains:
>>> numbers = (1, 2, 3)
>>> len(numbers)
3
With a tuple as an argument, list()
returns a list with all the items in the input tuple:
>>> numbers = (1, 2, 3)
>>> list(numbers)
[1, 2, 3]
Because tuples are immutable sequences, many of the methods that are available for lists don’t work on tuples. However, tuples have two built-in methods:
.count()
.index()
tuple.count()
takes an object as an argument and returns the number of times the item appears in the underlying tuple. If the object isn’t in the tuple, then .count()
returns 0
:
>>> letters = ("a", "b", "b", "c", "a")
>>> letters.count("a")
2
>>> letters.count("c")
1
>>> letters.count("d")
0
tuple.index()
takes an object as an argument and returns the index of the first instance of that object in the tuple at hand. If the object isn’t in the tuple, then .index()
raises a ValueError
:
>>> letters = ("a", "b", "b", "c", "a")
>>> letters.index("a")
0
>>> letters.index("c")
3
>>> letters.index("d")
Traceback (most recent call last):
File "<input>", line 1, in <module>
letters.index("d")
ValueError: tuple.index(x): x not in tuple
Tuples are quite useful data structures. They’re memory efficient, immutable, and have a lot of potential for managing data that shouldn’t be modified by the user. They can also be used as dictionary keys, which you’ll learn about in the next section.
Dictionaries
Dictionaries are a type of associative array containing a collection of key-value pairs in which each key is a hashable object that maps to an arbitrary object, the value. There are several ways to create a dictionary. Here are two of them:
>>> person1 = {"name": "John Doe", "age": 25, "job": "Python Developer"}
>>> person1
{'name': 'John Doe', 'age': 25, 'job': 'Python Developer'}
>>> person2 = dict(name="Jane Doe", age=24, job="Web Developer")
>>> person2
{'name': 'Jane Doe', 'age': 24, 'job': 'Web Developer'}
The first approach uses a pair of curly brackets in which you add a comma-separated list of key-value pairs, using a colon (:
) to separate the keys from the values. The second approach uses the built-in function dict()
, which can take keyword arguments and turn them into a dictionary, with the keywords as the keys and the arguments as the values.
Note: Since Python 3.6, dictionaries have been ordered data structures. But before that, they were unordered. So, if you’re using a Python version lower than 3.6 and you need an ordered dictionary, then consider using collections.OrderedDict()
.
You can retrieve the value associated with a given key using the following syntax:
>>> person1 = {"name": "John Doe", "age": 25, "job": "Python Developer"}
>>> person1["name"]
'John Doe'
>>> person1["age"]
25
This is quite similar to an indexing operation, but this time you use a key instead of an index.
You can also retrieve the keys, values, and key-value pairs in a dictionary using .keys()
, .values()
, and .items()
, respectively:
>>> # Retrieve all the keys
>>> person1.keys()
dict_keys(['name', 'age', 'job'])
>>> # Retrieve all the values
>>> person1.values()
dict_values(['John Doe', 25, 'Python Developer'])
>>> # Retrieve all the key-value pairs
>>> person1.items()
dict_items([('name', 'John Doe'), ('age', 25), ('job', 'Python Developer')])
These three methods are fundamental tools when it comes to manipulating dictionaries in Python, especially when you’re iterating through a dictionary.
Sets
Python also provides a set data structure. Sets are unordered and mutable collections of arbitrary but hashable Python objects. You can create sets in several ways. Here are two of them:
>>> employees1 = {"John", "Jane", "Linda"}
{'John', 'Linda', 'Jane'}
>>> employees2 = set(["David", "Mark", "Marie"])
{'Mark', 'David', 'Marie'}
>>> empty = set()
>>> empty
set()
In the first example, you use curly brackets and a list of comma-separated objects to create a set. If you use set()
, then you need to provide an iterable with the objects you want to include in the set. Finally, if you want to create an empty set, then you need to use set()
without arguments. Using an empty pair of curly brackets creates an empty dictionary instead of a set.
One of the most common use cases of sets is to use them for removing duplicate objects from an existing iterable:
>>> set([1, 2, 2, 3, 4, 5, 3])
{1, 2, 3, 4, 5}
Since sets are collections of unique objects, when you create a set using set()
and an iterable as an argument, the class constructor removes any duplicate objects and keeps only one instance of each in the resulting set.
Note: Python also provides an immutable variation of a set called frozenset. You can create them by calling frozenset()
with an iterable as an argument. If you call frozenset()
without arguments, then you’ll get an empty frozenset.
You can use some built-in functions with sets like you’ve done with other built-in data structures. For example, if you pass a set as an argument to len()
, then you get the number of items in the set:
>>> employees1 = {"John", "Jane", "Linda"}
>>> len(employees1)
3
You can also use operators to manage sets in Python. In this case, most operators represent typical set operations like union (|
), intersection (&
), difference (-
), and so on:
>>> primes = {2, 3, 5, 7}
>>> evens = {2, 4, 6, 8}
>>> # Union
>>> primes | evens
{2, 3, 4, 5, 6, 7, 8}
>>> # Intersection
>>> primes & evens
{2}
>>> # Difference
>>> primes - evens
{3, 5, 7}
Sets provide a bunch of methods, including methods that perform set operations like those in the above example. They also provide methods to modify or update the underlying set. For example, set.add()
takes an object and adds it to the set:
>>> primes = {2, 3, 5, 7}
>>> primes.add(11)
>>> primes
{2, 3, 5, 7, 11}
set.remove()
takes an object and removes it from the set:
>>> primes = {2, 3, 5, 7, 11}
>>> primes.remove(11)
>>> primes
{2, 3, 5, 7}
Python sets are quite useful data structures that are an important addition to the Python developer’s tool kit.
Conditionals
Sometimes you need to run (or not run) a given code block depending on whether certain conditions are met. In this case, conditional statements are your ally. These statements control the execution of a group of statements based on the truth value of an expression. You can create a conditional statement in Python with the if
keyword and the following general syntax:
if expr0:
# Run if expr0 is true
# Your code goes here...
elif expr1:
# Run if expr1 is true
# Your code goes here...
elif expr2:
# Run if expr2 is true
# Your code goes here...
...
else:
# Run if all expressions are false
# Your code goes here...
# Next statement
The if
statement runs only one code block. In other words, if expr0
is true, then only its associated code block will run. After that, the execution jumps to the statement directly below the if
statement.
The first elif
clause evaluates expr1
only if expr0
is false. If expr0
is false and expr1
is true, then only the code block associated with expr1
will run, and so on. The else
clause is optional and will run only if all the previously evaluated conditions are false. You can have as many elif
clauses as you need, including none at all, but you can have only up to one else
clause.
Here are some examples of how this works:
>>> age = 21
>>> if age >= 18:
... print("You're a legal adult")
...
You're a legal adult
>>> age = 16
>>> if age >= 18:
... print("You're a legal adult")
... else:
... print("You're NOT an adult")
...
You're NOT an adult
>>> age = 18
>>> if age > 18:
... print("You're over 18 years old")
... elif age == 18:
... print("You're exactly 18 years old")
...
You're exactly 18 years old
In the first example, age
is equal to 21
, so the condition is true, and Python prints You're a legal adult
to your screen. In the second example, the expression age >= 18
evaluates to False
, so Python runs the code block of the else
clause and prints You're NOT an adult
on your screen.
In the final example, the first expression, age > 18
, is false, so the execution jumps to the elif
clause. The condition in this clause is true, so Python runs the associated code block and prints You're exactly 18 years old
.
Loops
If you need to repeat a piece of code several times to get a final result, then you might need to use a loop. Loops are a common way of iterating multiple times and performing some actions in each iteration. Python provides two types of loops:
for
loops for definite iteration, or performing a set number or repetitionswhile
loops for indefinite iteration, or repeating until a given condition is met
Here’s the general syntax to create a for
loop:
for loop_var in iterable:
# Repeat this code block until iterable is exhausted
# Do something with loop_var...
if break_condition:
break # Leave the loop
if continue_condition:
continue # Resume the loop without running the remaining code
# Remaining code...
else:
# Run this code block if no break statement is run
# Next statement
This type of loop performs as many iterations as items in iterable
. Normally, you use each iteration to perform a given operation on the value of loop_var
. The else
clause is optional and runs when the loop finishes. The break
and continue
statements are also optional.
Check out the following example:
>>> for i in (1, 2, 3, 4, 5):
... print(i)
... else:
... print("The loop wasn't interrupted")
...
1
2
3
4
5
The loop wasn't interrupted
When the loop processes the last number in the tuple, the flow of execution jumps into the else
clause and prints The loop wasn't interrupted
on your screen. That’s because your loop wasn’t interrupted by a break
statement. You commonly use an else
clause in loops that have a break
statement in their code block. Otherwise, there’s no need for it.
If the loop hits a break_condition
, then the break
statement interrupts the loop execution and jumps to the next statement below the loop without consuming the rest of the items in iterable
:
>>> number = 3
>>> for i in (1, 2, 3, 4, 5):
... if i == number:
... print("Number found:", i)
... break
... else:
... print("Number not found")
...
Number found: 3
When i == 3
, the loop prints Number found: 3
on your screen and then hits the break
statement. This interrupts the loop, and execution jumps to the line below the loop without running the else
clause. If you set number
to 6
or any other number that’s not in the tuple of numbers, then the loop doesn’t hit the break
statement and prints Number not found
.
If the loop hits a continue_condition
, then the continue
statement resumes the loop without running the rest of the statements in the loop’s code block:
>>> for i in (1, 2, 3, 4, 5):
... if i == 3:
... continue
... print(i)
...
1
2
4
5
This time, the continue
statement restarts the loop when i == 3
. That’s why you don’t see the number 3
in the output.
Both statements, break
and continue
, should be wrapped in a conditional. Otherwise, the loop will always break when it hits break
and continue when it hits continue
.
You normally use a while
loop when you don’t know beforehand how many iterations you need to complete a given operation. That’s why this loop is used to perform indefinite iterations.
Here’s the general syntax for a while
loop in Python:
while expression:
# Repeat this code block until expression is false
# Do something...
if break_condition:
break # Leave the loop
if continue_condition:
continue # Resume the loop without running the remaining code
# Remaining code...
else:
# Run this code block if no break statement is run
# Next statement
This loop works similarly to a for
loop, but it’ll keep iterating until expression
is false. A common problem with this type of loop comes when you provide an expression
that never evaluates to False
. In this case, the loop will iterate forever.
Here’s an example of how the while
loop works:
>>> count = 1
>>> while count < 5:
... print(count)
... count = count + 1
... else:
... print("The loop wasn't interrupted")
...
1
2
3
4
The loop wasn't interrupted
Again, the else
clause is optional, and you’ll commonly use it with a break
statement in the loop’s code block. Here, break
and continue
work the same as in a for
loop.
There are situations in which you need an infinite loop. For example, GUI applications run in an infinite loop that manages the user’s events. This loop needs a break
statement to terminate the loop when, for example, the user exits the application. Otherwise, the application would continue running forever.
Functions
In Python, a function is a named code block that performs actions and optionally computes the result, which is then returned to the calling code. You can use the following syntax to define a function:
def function_name(arg1, arg2, ..., argN):
# Do something with arg1, arg2, ..., argN
return return_value
The def
keyword starts the function header. Then you need the name of the function and a list of arguments in parentheses. Note that the list of arguments is optional, but the parentheses are syntactically required.
The final step is to define the function’s code block, which will begin one level of indentation to the right. In this case, the return
statement is also optional and is the statement that you use if you need to send a return_value
back to the caller code.
Note: The full syntax to define functions and their arguments is beyond the scope of this tutorial. For an in-depth resource on this topic, check out Defining Your Own Python Function.
To use a function, you need to call it. A function call consists of the function’s name, followed by the function’s arguments in parentheses:
function_name(arg1, arg2, ..., argN)
You can have functions that don’t require arguments when called, but the parentheses are always needed. If you forget them, then you won’t be calling the function but referencing it as a function object.
How to Handle Errors in Python
Errors are something that irritates and frustrates programmers at every level of experience. Having the ability to identify and handle them is a core skill for programmers. In Python, there are two types of code-based errors: syntax errors and exceptions.
Syntax Errors
Syntax errors occur when the syntax of your code isn’t valid in Python. They automatically stop the execution of your programs. For example, the if
statement below is missing a colon at the end of the statement’s header, and Python quickly points out the error:
>>> if x < 9
File "<stdin>", line 1
if x < 9
^
SyntaxError: invalid syntax
The missing colon at the end of the if
statement is invalid Python syntax. The Python parser catches the problem and raises a SyntaxError
immediately. The arrow (^
) indicates where the parser found the problem.
Exceptions
Exceptions are raised by syntactically correct code at runtime to signal a problem during program execution. For example, consider the following math expression:
>>> 12 / 0
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ZeroDivisionError: integer division or modulo by zero
The expression 12 / 0
is syntactically correct in the eyes of the Python parser. However, it raises a ZeroDivisionError
exception when the interpreter tries to actually evaluate the expression.
Note: In Python, you’ll commonly rely on exceptions to control the flow of a program. Python developers favor this coding style, known as EAFP (Easier to Ask for Forgiveness than Permission), over the coding style known as LBYL (Look Before You Leap), which is based on using if
statements. For more information on these two coding styles, check out LBYL vs EAFP: Preventing or Handling Errors in Python.
Python provides several convenient built-in exceptions that allow you to catch and handle errors in your code.
Semantic Errors
Semantic errors happen as a result of one or more problems in the logic of a program. These errors can be difficult to find, debug, and fix because no error message is generated. The code runs but generates unexpected output, incorrect output, or no output at all.
A classic example of a semantic error would be an infinite loop, which most programmers experience at least once in their coding lifetime.
How to Get Help in Python
Like a good friend, Python is always there to help if you get stuck. Perhaps you want to know how a specific function, method, class, or object works. In this case, you can just open an interactive session and call help()
. That’ll take you directly to Python’s help utility:
>>> help()
Welcome to Python 3.9's help utility!
If this is your first time using Python, you should definitely check out
the tutorial on the Internet at https://docs.python.org/3.9/tutorial/.
...
help>
Once there, you can type in the name of a Python object to get helpful information about it:
>>> help()
...
help> len
Help on built-in function len in module builtins:
len(obj, /)
Return the number of items in a container.
When you type the name len
at the help>
prompt and hit Enter, you get help content related to that built-in function. To leave the content and get back to the help>
prompt, you can press Q. To leave the help utility, you can type quit
and hit Enter.
You can also use help()
with the name of an object as an argument to get information about that object:
>>> help(dir)
Help on built-in function dir in module builtins:
dir(...)
dir([object]) -> list of strings
...
Speaking of dir()
, you can use this function to inspect the methods and attributes that are available in a particular object:
>>> dir(str)
['__add__', '__class__', ..., 'title', 'translate', 'upper', 'zfill']
>>> dir(tuple)
['__add__', '__class__', ..., 'count', 'index']
When you call dir()
with the name of a Python object as an argument, the function attempts to return a list of valid attributes for that specific object. This is a convenient way to get an idea of what a given object can do.
Tools for Coding in Python
There are three main approaches to coding in Python. You already used one of them, the Python interactive interpreter, also known as the read-evaluate-print loop (REPL). Even though the REPL is quite useful for trying out small pieces of code and experimenting, you can’t save your code for later use.
To save and reuse your code, you need to create a Python script or module. Both of them are plain text files with a .py
(or .pyw
on Windows) extension. To create scripts and modules, you can use a code editor or an integrated development environment (IDE), which are the second and third approaches to coding in Python.
REPLs (Read-Evaluate-Print Loops)
Although you can create functions in an interactive session, you’ll typically use the REPL for one-line expressions and statements or for short compound statements to get quick feedback on your code. Fire up your Python interpreter and type the following:
>>> 24 + 10
34
The interpreter simply evaluates 24 + 10
, adding the two numbers, and outputs the sum, 34
. Now try one more:
>>> import this
Take a minute to read the output. It states some important principles in Python, which will help you write better and more Pythonic code.
So far, you’ve used the standard Python REPL, which ships with your current Python distribution. However, this isn’t the only REPL out there. Third-party REPLs provide many useful features, such as syntax highlighting, code completion, and so on. Here are some popular options:
- IPython provides a rich toolkit to help you code in Python interactively.
- bpython is an interface to the Python interpreter for Linux, BSD, macOS, and Windows.
- Ptpython is a Python REPL that also works on Linux, BSD, macOS, and Windows.
Keep in mind that once you close the REPL session, your code is gone. In other words, the code typed into a REPL isn’t persistent, so you can’t reuse it. As a developer, you want code that you can reuse to save precious keystrokes. In this situation, code editors and IDEs come in handy.
Code Editors
The second approach to coding in Python is to use a code editor. Some people prefer an integrated development environment (IDE), but a code editor is often better for learning purposes. Why? Because when you’re learning something new, you want to peel off as many layers of complexity as possible. Adding a complex IDE into the mix can make the task of learning Python more difficult.
A Python program, in its bare-bones form, consists of lines of text (code) saved in a file with a .py
or .pyw
extension. You can write Python code in something as basic as Notepad on Windows, but there’s no reason to put yourself through such an ordeal since there are much better options available.
At its core, a code editor should provide several features to help programmers create programs. In most cases, you can customize the code editor to suit your needs and style. So, what should you look for in a code editor? The answer to this question might depend on your personal needs, but in general, you should look for at least the following features:
- Syntax highlighting
- Auto-indentation
- Auto-completion
- Tabbed interface
- Line numbering
- Customizable look and feel
- A curated set of plugins
Take a look at the following comparison example:
The code in the editor at the top (Sublime Text) is more readable due to the syntax highlighting and line numbering. The editor also identifies three errors, one of which is a showstopper. Can you figure out which one?
Meanwhile, the editor at the bottom (Notepad) doesn’t display the errors and is hard on the eyes since it’s in black and white.
Here’s a non-exhaustive list of some modern code editors that you can use:
- Visual Studio Code is a full-featured code editor available for Linux, macOS, and Windows platforms.
- Sublime Text 3 is a powerful and cross-platform code editor.
- Gedit is also cross-platform and comes installed in some Linux distributions that use GNOME.
- Notepad++ is also a great editor, but it’s for Windows only.
- Vim is available for Mac, Linux, and Windows.
- GNU Emacs is free and available on every platform.
There are many different options, both free and commercial, when it comes to code editors. Do your research and don’t be afraid to experiment! Keep in mind that your code editor should help you adhere to Python coding standards, best practices, and idioms.
IDEs (Integrated Development Environments)
An IDE is a program dedicated to software development. IDEs commonly integrate several features, such as code editing, debugging, version control, the ability to build and run your code, and so on. There are a lot of available IDEs that support Python or that are Python-specific. Here are three popular examples:
-
IDLE is Python’s Integrated Development and Learning Environment. You can use IDLE interactively exactly as you use the Python interpreter. You can also use it for code reuse since you can create and save your code with IDLE. If you’re interested in using IDLE, then check out Getting Started With Python IDLE.
-
PyCharm is a full-featured, Python-specific IDE developed by JetBrains. If you’re interested in using it, then check out PyCharm for Productive Python Development (Guide). It’s available on all major platforms and comes in free Edu and Community versions as well as a paid Professional version.
-
Thonny is a beginner-friendly IDE that will enable you to start working with Python right away. If you’re thinking of using Thonny, then check out Thonny: The Beginner-Friendly Python Editor.
This list of IDEs isn’t nearly complete. It’s intended to give you some guidance on how to get the right Python IDE for you. Explore and experiment before you make your choice.
Python Code Style
PEP 8 is the official style guide for Python code. Although it’s not required to write workable Python code, studying PEP 8 and applying it consistently in your Python code will make your programs more readable and maintainable. Luckily, you don’t need to memorize PEP 8 to give your Python code a Pythonic style.
Most code editors and IDEs that support Python internally implement automatic checks to find and point out PEP 8 violations. This will help you consistently improve the style of your code and will also reinforce PEP 8’s recommendations in your mind.
You can also take advantage of code linters, such as Flake8, Pylint, and pycodestyle. You can even use code formatters, such as Black and isort, to consistently format your code. Some of these tools are conveniently integrated into some of the currently available code editors and IDEs.
If you want to learn more about how you can improve the quality of your code using PEP 8 and other code style best practices, then check out How to Write Beautiful Python Code With PEP 8 and Python Code Quality: Tools & Best Practices.
Get Extra Features in Python
So far, you’ve learned a few basic Python concepts and features. When you start to dive deeper into the language, you may find that you need a certain feature and decide to code it by yourself. If that’s the case, then consider that you might be reinventing the wheel.
Python’s been in use for almost three decades now. It has an incredibly large community of developers, and it’s likely that someone else has run into the same problem as you. With a little research, you may be able to find a code snippet, library, framework, or other solution that can save you a lot of time and effort.
The first place to look is the Python standard library. If you don’t find anything there, then you can also look at the Python Package Index (PyPI). Finally, you can check out some other third-party libraries.
The Standard Library
One of the great things about Python is the plethora of available modules, packages, and libraries both built into the Python core and made available by third-party developers. These modules, packages, and libraries can be quite helpful in your day-to-day work as a Python coder. Here are some of the most commonly used built-in modules:
math
for mathematical operationsrandom
for generating pseudo-random numbersre
for working with regular expressionsos
for using operating system–dependent functionalitiesitertools
for working with iteratorscollections
for specialized container data types
For example, here you import math
to use pi
, find the square root of a number with sqrt()
, and raise a number to a power with pow()
:
>>> import math
>>> math.pi
3.141592653589793
>>> math.sqrt(121)
11.0
>>> math.pow(7, 2)
49.0
Once you import math
, you can use any function or object defined in that module. If you want a complete list of the functions and objects that live in math
, then you can run something like dir(math)
in an interactive session.
You can also import specific functions directly from math
or any other module:
>>> from math import sqrt
>>> sqrt(121)
11.0
This kind of import statement brings the name sqrt()
into your current namespace, so you can use it directly without the need to reference the containing module.
If you’re using modules, such as math
or random
, then make sure not to use those same names for your custom modules, functions, or objects. Otherwise, you might run into name conflicts, which can cause in unexpected behavior.
The Python Package Index and pip
The Python package index, also known as PyPI (pronounced “pie pea eye”), is a massive repository of Python packages that includes frameworks, tools, packages, and libraries. You can install any PyPI package using pip
. This is one of the recommended tools for managing third-party modules, packages, and libraries in Python.
New coders frequently hit a wall when they’re following an example and they see ModuleNotFoundError: No module named module_x
when they run the code. This means that the code depends on module_x
, but that module isn’t installed in the current Python environment, creating a broken dependency. Modules like module_x
can be manually installed using pip
.
For example, say you’re trying to run an application that uses pandas, but you don’t have this library installed on your computer. In this case, you can open your terminal and use pip
like this:
$ pip3 install pandas
This command downloads pandas and its dependencies from PyPI and installs them in your current Python environment. Once the installation is finished, you can run your application again and, if there’s no other broken dependency, the code should work.
Take Your Python Skills to the Next Level
Here at Real Python, you can find all kinds of resources that can help you out on your path to learning how to program in Python:
- Tutorials that can help you learn Python with a step-by-step approach
- Video courses with detailed and in-depth content but also with a progressive learning approach
- Quizzes to test your knowledge and measure your learning improvements and progress
- Learning Paths in which you can study and learn different topics about Python from the ground up
- A community for you to meet the Real Python team and other Pythonistas actively looking to improve their skills
At Real Python, you can also find many other resources, such as books and courses, podcast episodes, Office Hours sessions, a newsletter, and so on. Some of them are totally free, others cost a modest fee supports the site and allows us to continue creating and updating content for you.
If you’re just beginning with Python, then check out the book Python Basics: A Practical Introduction to Python 3. It’ll help you make the leap from beginner to intermediate Python developer.
Of course, there are many other courses, tutorials, and resources about Python available online. Again, this is a personal choice. Do your research before making a decision. A good source of free learning materials is the official Python documentation, which you should keep handy as a reliable and quick reference. Just be aware that the material can be less reader-friendly than what you’ll find at Real Python.
Above all, it’s important that you don’t fall into trying to find the best book or video ever and get lost in the process. Do some research. Ask around. But pick something and stick with it! Open your code editor and start coding a Python project! Make a commitment to yourself to find a way to bring your vision to life and complete your project.
Coding Is Like Riding a Bike
Coding is like riding a bike. You can watch people to learn how it’s done and sometimes you can get a push, but in the end, it’s a solo event. When you get stuck or need to brush up on a new concept, you can often work through the problem yourself by doing some research on Google. If you get an error message, then typing in the exact error message into Google will often bring up a result on the first page that might solve the problem.
Stack Overflow is another fundamental place to go when you’re looking for answers. The Q&A for coding has some great explanations of Python topics. Understanding slice notation and Manually raising (throwing) an exception in Python are just two truly excellent examples.
If you get stuck on a problem, then try these suggestions:
-
Stop coding!
-
Get a piece of paper and map out how to solve the problem using plain words. Use a flowchart if necessary.
-
Don’t use a
try
andexcept
block until your code is working. Thetry
can suppress valuable error messages that help identify problems in your code. -
Use
print()
to quickly inspect your variables and make sure they have the expected value. This is an effective quick-and-dirty problem solver. -
Use the rubber duck debugging technique. Explain your code, line by line, to the duck. You might find the solution to your problems in the process.
-
Use the Python Visualizer if you’re still stumped. This tool allows you to step through your code as it executes. The Python Visualizer has examples to help you if needed.
One final and important note: A frustrated brain is not going to help. When you start to get annoyed because something isn’t working, take a break to clear your mind. Go for a run or do something else. You will be amazed just how effective this can be. Often, you’ll come back with fresh eyes and see a simple typo, a misspelled keyword, or something similar.
Advising New Python Coders
Coders expect other coders, even beginners, to try and resolve the issue by themselves. At some point, though, you’ll need guidance. Once you’ve tried everything you can think of and have truly hit the wall, ask for help before you smash your keyboard or another inanimate object.
There are several places to get help, including code forums, Facebook groups, and the IRC channel #python, to name a few. Take a minute to read any rules or guidelines for any of the groups that you use. Make it easy for others to help you by explaining the problem and what you’ve tried. If there’s an error, then include that information as well.
Have fun coding!
Code an Example: Count to 10
Many programmers get overwhelmed when they start to solve a problem. An effective approach to help you solve a problem, regardless of size, is to logically divide the problem into smaller parts.
For example, say you need to code a program that counts from 1 to 10. Each time the count increments, you want to display its value. One approach to help in the development of a workflow is to use pseudocode:
Since you you’ll be more productive on an organized machine, first create a folder named something like python_code
where you’ll store the example files. Learning to code is a hands-on adventure, so fire up your code editor and enter the following code. Don’t just copy and paste the code! Typing it yourself will be much more beneficial to your learning:
1count = 1
2
3# Code block 1
4while count < 11:
5 print(count)
6 count = count + 1
7
8# Code block 2
9if count == 11:
10 print("Counting complete!")
Note that lines 3 and 8 start with a hash character (#
) followed by a space and then an explanation. Those are comments. Comments can have many purposes, but for the most part, you use them to either explain the code or summarize a specific approach you took as the developer. Do the comments in the above examples make sense to you? If not, then improve them or even remove them.
Did you notice that the examples use both a single equals sign (=
) and a double equals sign (==
)? This can be confusing, so here’s how it works:
- In the statement
count = count + 1
, the=
assigns the value of1
to the variablecount
. Can you tell what the final value ofcount
would be? - In the conditional statement
if count == 11:
, the==
compares the value ofcount
with11
, returning a BooleanTrue
orFalse
according to the result of the operation. Can you tell what the statement evaluates to in each iteration?
Save the file as count_to_ten.py
in the folder you created, then exit the editor. Open a terminal or command prompt and navigate to the folder. Now run the following command:
$ python count_ten.py
You may need to replace python
with python3
depending on your setup. The output will look something like this:
1
2
3
4
5
6
7
8
9
10
Counting complete!
That’s it! You just wrote your first Python program. Can you explain what each line of code in the program does?
Test Your Knowledge
If you’ve read through this tutorial up to this point, then you might want to answer some Python-related questions and test what you’ve learned. Go ahead and test your knowledge:
- What does it mean that Python is a strong, dynamically typed language?
- How do you run the Python interpreter?
- How do you define a variable?
- What’s the difference between a variable name and a variable value?
- What are Python’s built-in data types?
- What’s the difference between an integer and a floating-point number?
- What are Boolean values?
- What does the
%
operator do? - What’s the difference between a list and a tuple?
- What is a dictionary?
- Why should you use comments in your code?
- What does
help()
do, and when is it useful? - What does
dir()
do, and when is it useful? - What’s the difference between syntax errors and exceptions?
- What is
pip
?
Now open your text editor and create a new file called exercise.py
. Copy and paste the following code into it:
# Modify the variables so that all of the statements evaluate to True.
var1 =
var2 =
var3 =
var4 =
var5 =
var6 =
# Don't edit anything below this comment
# Numbers
print(isinstance(var1, int))
print(isinstance(var6, float))
print(var1 < 35)
print(var1 <= var6)
# Strings
print(isinstance(var2, str))
print(var2[5] == "n" and var2[0] == "p")
# Lists
print(isinstance(var3, list))
print(len(var3) == 5)
# Tuples
print(isinstance(var4, tuple))
print(var4[2] == "Hello, Python!")
# Dictionaries
print(isinstance(var5, dict))
print("happy" in var5)
print(7 in var5.values())
print(var5.get("egg") == "salad")
print(len(var5) == 3)
var5["tuna"] = "fish"
print(len(var5) == 3)
Following the instructions, update the code. When you’re done, run the code from your terminal to test using the python exercise.py
command. Good luck!
Now that you know the basics of Python programming, be sure to check out the wide range of Python tutorials, video courses, and resources here at Real Python to continue building your skills.
Conclusion
Learning how to use Python and get your programming skills to the next level is a worthwhile endeavor. Python is a popular, productive, and powerful high-level programming language that is in high demand. In this tutorial, you learned essential concepts about Python and started to apply them to your Python code.
In this tutorial, you learned:
- What Python is and why you should consider using it
- What basic Python syntax you should learn to start coding
- How you can handle errors in Python
- How you can get help in Python quickly
- What code style you should use in your code
- Where to get extra functionalities without reinventing the wheel
- Where to get quality Python content and grow your skills
You also created your first Python program and ran it on your computer. With all this knowledge, you can dive deeper into Python and learn a lot more of the language.