What are examples of python?
The best way to learn Python is by practicing examples. This page contains examples on basic concepts of Python. We encourage you to try these examples on your own before looking at the solution. Show
All the programs on this page are tested and should work on all platforms. Want to learn Python by writing code yourself? Enroll in our Interactive Python Course for FREE. W3Schools is optimized for learning and training. Examples might be simplified to improve reading and learning. Tutorials, references, and examples are constantly reviewed to avoid errors, but we cannot warrant full correctness of all content. While using W3Schools, you agree to have read and accepted our terms of use, cookie and privacy policy. Copyright 1999-2022 by Refsnes Data. All Rights Reserved. Hi! Welcome. If you are learning Python, then this article is for you. You will find a thorough description of Python syntax and lots of code examples to guide you during your coding journey. What we will cover:
Are you ready? Let's begin! 🔅 💡 Tip:
throughout this article, I will use 🔹 Variable Definitions in PythonThe most basic building-block of any programming language is the concept of a variable, a name and place in memory that we reserve for a value. In Python, we use this syntax to create a variable and assign a value to this variable:
For example:
If the name of a variable has more than one word, then the Style Guide for Python Code recommends separating words with an underscore "as necessary to improve readability." For example:
💡 Tip: The Style Guide for Python Code (PEP 8) has great suggestions that you should follow to write clean Python code. 🔸 Hello, World! Program in PythonBefore we start diving into the data types and data structures that you can use in Python, let's see how you can write your first Python program. You just need to call the
You will see this message after running the program:
💡 Tip: Writing a Great. You just wrote your first Python program. Now let's start learning about the data types and built-in data structures that you can use in Python. 🔹 Data Types and Built-in Data Structures in PythonWe have several basic data types and built-in data structures that we can work with in our programs. Each one has its own particular applications. Let's see them in detail. Numeric Data Types in Python: Integers, Floats, and ComplexThese are the numeric types that you can work with in Python: IntegersIntegers are numbers without decimals. You can check if a number is an integer with the For example:
FloatsFloats are numbers with decimals. You can detect them visually by locating the decimal point. If we call
Here we have some examples:
ComplexComplex numbers have a real part and an imaginary part denoted with These are some examples:
Strings in PythonStrings incredibly helpful in Python. They contain a sequence of characters and they are usually used to represent text in the code. For example:
We can use both single quotes 💡
Tip: Yes! You used a string when you wrote the Strings can contain any character that we can type in our keyboard, including numbers, symbols, and other special characters. For example:
💡 Tip: Spaces are also counted as characters in a string. Quotes Within StringsIf we define a
string with double quotes
If we define a string with single quotes
String IndexingWe can use indices to access the characters of a string in our Python program. An index is an integer that represents a specific position in the string. They are associated to the character at that position. This
is a diagram of the string
💡 Tip: Indices start from For example:
We can also use negative indices to access these characters:
💡 Tip: we commonly use String SlicingWe may also need to get a slice of a string or a subset of its characters. We can do so with string slicing. This is the general syntax:
We can specify two parameters to use the default value of
For example:
💡 Tip: Notice that if the value of a parameter goes beyond the valid range of indices, the slice will still be presented. This is how the creators of Python implemented this feature of string slicing. If we customize the
For example:
We can also use a negative step to go from right to left:
And we can omit a parameter to use its default value. We just have to include the corresponding colon (
💡 Tip: The last example is one of the most common ways to reverse a string. f-StringsIn Python 3.6 and more recent versions, we can use a type of string called f-string that helps us format our strings much more easily. To define an f-string, we just add an For example:
The output is:
Here we have an example where we calculate the value of an expression and replace the result in the string:
The values are replaced in the output:
We can also call methods within the curly braces and the value returned will be replaced in the string when we run the program:
The output is:
String MethodsStrings have methods, which represent common functionality that has been implemented by Python developers, so we can use it in our programs directly. They are very helpful to perform common operations. This is the general syntax to call a string method:
For example:
To learn more about Python methods, I would recommend reading this article from the Python documentation. 💡 Tip: All string methods return copies of the string. They do not modify the string because strings are immutable in Python. Booleans in PythonBoolean values are For example:
If we write them in lowercase, we will get an error:
Lists in PythonNow that we've covered the basic data types in Python, let's start covering the built-in data structures. First, we have lists. To define a list, we use square brackets
💡 Tip: It's recommended to add a space after each comma to make the code more readable. For example, here we have examples of lists:
Lists can contain values of different data types, so this would be a valid list in Python:
We can also assign a list to a variable:
Nested ListsLists can contain values of any data type, even other lists. These inner lists are called nested lists.
In this example, Here we have other valid examples:
We can access the nested lists using their corresponding index:
Nested lists could be used to represent, for example, the structure of a simple 2D game board where each number could represent a different element or tile:
List LengthWe can use
the For example:
Update a Value in a ListWe can update the value at a particular index with this syntax:
For example:
Add a Value to a ListWe can add a new value to the end of a list with the For example:
Remove a Value from a ListWe can remove a value from a list with the For example:
💡 Tip: This will only remove the first occurrence of the element. For example, if we try to remove the number 3 from a list that has two number 3s, the second number will not be removed:
List IndexingWe can index a list just like we index strings, with indices that start from
List SlicingWe can also get a slice of a list using the same syntax that we used with strings and we can omit the parameters to use their default values. Now, instead of adding characters to the slice, we will be adding the elements of the list.
For example:
List MethodsPython also has list methods already implemented to help us perform common list operations. Here are some examples of the most commonly used list methods:
To learn more about list methods, I would recommend reading this article from the Python documentation. Tuples in PythonTo define a tuple in Python, we use parentheses
We can assign tuples to variables:
Tuple IndexingWe can access each element of a tuple with its corresponding index:
We can also use negative indices:
Tuple LengthTo find the length of a tuple, we use the
Nested TuplesTuples can contain values of any data type, even lists and other tuples. These inner tuples are called nested tuples.
In this example, we have a nested tuple For example:
Tuple SlicingWe can slice a tuple just like we sliced lists and strings. The same principle and rules apply. This is the general syntax:
For example:
Tuple MethodsThere are two built-in tuple methods in Python:
💡 Tip: tuples are immutable. They cannot be modified, so we can't add, update, or remove elements from the tuple. If we need to do so, then we need to create a new copy of the tuple. Tuple AssignmentIn Python, we have a really cool feature called Tuple Assignment. With this type of assignment, we can assign values to multiple variables on the same line. The values are assigned to their corresponding variables in the order that they
appear. For example, in For example:
💡 Tip: Tuple assignment is commonly used to swap the values of two variables:
Dictionaries in PythonNow let's start diving into dictionaries. This built-in data structure lets us create pairs of values where one value is associated with another one. To define a dictionary in Python, we use curly brackets The key is separated from the value with a colon
You can assign the dictionary to a variable:
The keys of a dictionary must be of an immutable data type. For example, they can be strings, numbers, or tuples but not lists since lists are mutable.
The values of a dictionary can be of any data type, so we can assign strings, numbers, lists, tuple, sets, and even other dictionaries as the values. Here we have some examples:
Dictionary LengthTo get the number of key-value pairs, we use the
Get a Value in a DictionaryTo get a value in a dictionary, we use its key with this syntax:
This expression will be replaced by the value that corresponds to the key. For example:
The output is the value associated to
Update a Value in a DictionaryTo update the value associated with an existing key, we use the same syntax but now we add an assignment operator and the value:
For example:
Now the dictionary is:
Add a Key-Value Pair to a DictionaryThe keys of a dictionary have to be unique. To add a new key-value pair we use the same syntax that we use to update a value, but now the key has to be new.
For example:
Now the dictionary has a new key-value pair:
Delete a Key-Value Pair in a DictionaryTo delete a key-value pair, we use the
For example:
Now the dictionary is:
Dictionary MethodsThese are some examples of the most commonly used dictionary methods:
To learn more about dictionary methods, I recommend reading this article from the documentation. 🔸 Python OperatorsGreat. Now you know the syntax of the basic data types and built-in data structures in Python, so let's start diving into operators in Python. They are essential to perform operations and to form expressions. Arithmetic Operators in PythonThese operators are: Addition: +
💡 Tip: The last two examples are curious, right? This operator behaves differently based on the data type of the operands. When they are strings, this operator concatenates the strings and when they are Boolean values, it performs a particular operation. In Python, Subtraction: -
Multiplication: *
💡 Tip: you can "multiply" a string by an integer to repeat the string a given number of times. Exponentiation: **
Division: /
💡
Tip: this operator returns a If you try to divide by
Integer Division: //This operator returns an integer if the operands are integers. If they are floats, the result will be a float with
Modulo: %
Comparison OperatorsThese operators are:
These comparison operators make expressions that evaluate to either
We can also use them to compare strings based on their alphabetical order:
We typically use them to compare the values of two or more variables:
💡 Tip: notice thatthe comparison operator is Comparison Operator ChainingIn Python, we can use something called "comparison operator chaining" in which we chain the comparison operators to make more than one comparison more concisely. For example, this checks if
Here we have some examples:
Logical OperatorsThere are three logical operators in Python: The
The
The
These operator are used to form more complex expressions that combine different operators and variables. For example:
Assignment OperatorsAssignment operators are used to assign a value to a variable. They are:
For example:
💡 Tips: these operators perform bitwise operations before assigning the result to the variable: Membership OperatorsYou can check if an element is in a sequence or not with the operators: For example:
We typically use them with variables that store sequences, like in this example:
🔹 Conditionals in PythonNow let's see how we can write conditionals to make certain parts of our code run (or not) based on whether a condition is if statements in PythonThis is the syntax of a basic
If the condition is 💡 Tip: there is a colon ( Here we have some examples: False Condition
The condition is In this case, the condition is True ConditionHere we have another example. Now the condition is
The output is:
Code After the ConditionalHere we have an example with code that runs after the conditional has been completed. Notice that the last line is not indented, which means that it doesn't belong to the conditional.
In this example, the condition
However, if the condition is
The output will be:
Examples of ConditionalsThis is another example of a conditional:
In this case, the output will be:
But if we change the value of
There will be no output because the condition will be
if/else statements in PythonWe can add an This is the general syntax:
💡 Tip: notice that the two code blocks are indented ( Let's see an example with the True Condition
The output is:
When the condition of the False ConditionNow the
Now the output is:
if/elif/else statements in PythonTo
customize our conditionals even further, we can add one or more 💡 Tip: First Condition True
We have two conditions In this case, the output is:
Because the first condition is Second Condition TrueIf the first condition is In this example, the first condition
The output is:
All Conditions are FalseIf all conditions all
The output will be:
Multiple elif ClausesWe can add as many
Each condition will be checked and only the code block of the first condition that evaluates to 🔸 For Loops in PythonNow you know how to write conditionals in Python, so let's start diving into loops. For loops are amazing programming structures that you can use to repeat a code block a specific number of times. This is the basic syntax to write a for loop in Python:
The iterable can be a list, tuple, dictionary, string, the sequence returned by range, a file, or any other type of iterable in Python. We will start with The range() function in PythonThis function returns a sequence of integers that we can use to determine how many iterations (repetitions) of the loop will be completed. The loop will complete one iteration per integer. 💡 Tip: Each integer is assigned to the loop variable one at a time per iteration. This is the general syntax to write a for loop with
As you can see, the range function has three parameters:
You can pass 1, 2, or 3 arguments to
Here we have some examples with one parameter:
Output:
💡 Tip: the loop variable is updated automatically.
Output:
In the example below, we repeat a string as many times as indicated by the value of the loop variable:
Output:
We can also use for loops with built-in data structures such as lists:
Output:
💡 Tip: when you use These are some examples with two parameters:
Output:
Code:
Output:
Code:
Output:
Code:
Now the list is: These are some examples with three parameters:
Output:
Code:
Output:
Code:
Output:
How to Iterate over Iterables in PythonWe can iterate directly over iterables such as lists, tuples, dictionaries, strings, and files using for loops. We will get each one of their elements one at a time per iteration. This is very helpful to work with them directly. Let's see some examples: Iterate Over a StringIf we iterate over a string, its characters will be assigned to the loop variable one by one (including spaces and symbols).
We can also iterate over modified copies of the string by calling a string method where we specify the iterable in the for loop. This will assign the copy of the string as the iterable that will be used for the iterations, like this:
Iterate Over Lists and Tuples
The output is:
Code:
Output:
Iterate Over the Keys, Values, and Key-Value Pairs of DictionariesWe can iterate over the keys, values, and key-value pairs of a dictionary by calling specific dictionary methods. Let's see how. To iterate over the keys, we write:
We just write the name of the variable that stores the dictionary as the iterable. 💡 Tip: you can also write For example:
💡 Tip: you can assign any valid name to the loop variable. To iterate over the values, we use:
For example:
To iterate over the key-value pairs, we use:
💡 Tip: we are defining two loop variables because we want to assign the key and the value to variables that we can use in the loop.
If we define only one loop variable, this variable will contain a tuple with the key-value pair:
Break and Continue in PythonNow you know how to iterate over sequences in Python. We also have loop control statements to customize what happens when the loop runs: The Break StatementThe When a In the example below, we stop the loop when an even element is found.
The Continue StatementThe When it is found during the execution of the loop, the current iteration stops and a new one begins with the updated value of the loop variable. In the example below, we skip the current iteration if the element is even and we only print the value if the element is odd:
The zip() function in Python
We just need to pass the sequences as arguments to the For example:
The enumerate() Function in PythonYou
can also keep track of a counter while the loop runs with the 💡 Tip: By default, the counter starts at For example:
If you start the counter from
You can start the counter from a different number by passing a second argument to
The else ClauseFor loops also have an 💡 Tip: if In the example below, we try to find an element greater than 6 in the list. That
element is not found, so
The output is:
However, if the
The output is:
🔹 While Loops in PythonWhile loops are similar to for loops in that they let us repeat a block of code. The difference is that while loops run while a condition is In a while
loop, we define the condition, not the number of iterations. The loop stops when the condition is This is the general syntax of a while loop:
💡 Tip: in while loops, you must update the variables that are part of the condition to make sure that the condition will eventually become For example:
Break and ContinueWe can also use
For example:
The |