Loading lesson path
Python
Exercises, quizzes, examples, and short drills that reinforce foundations.
Get Started With Python At W3Schools, you can try Python without installing anything. Our Online Python Editor runs directly in your browser, and shows both the code and the result: Example print("He…
Challenge: Statements Test your understanding of Python statements by completing a small coding challenge.
Print Text You have already learned that you can use the print() function to display text or output values: Example print("Hello World!") You can use the print() function as many times as you want. E…
Print Numbers You can also use the print() function to display numbers: However, unlike text, we don't put numbers inside double quotes: Example print(3) print(358) print(50000) You can also do math…
Challenge: Output / Print Test your understanding of Python output by completing a small coding challenge.
Challenge: Comments Test your understanding of Python comments by completing a small coding challenge.
Many Values to Multiple Variables Python allows you to assign values to multiple variables in one line: Example x, y, z = "Orange", "Banana", "Cherry" print(x) print(y) print(z) Note: Make sure the n…
Output Variables The print() function is often used to output variables. Example x = "Python is awesome" print(x) In the print() function, you output multiple variables, separated by a comma: Example…
Global Variables Variables that are created outside of a function (as in all of the examples in the previous pages) are known as global variables. Global variables can be used by everyone, both insid…
Python - Variable Exercises
Challenge: Variables Test your understanding of Python variables by completing a small coding challenge.
Challenge: Data Types Test your understanding of Python data types by completing a small coding challenge.
Python Numbers There are three numeric types in Python: int float complex Variables of numeric types are created when you assign a value to them: Example x = 1 # int y = 2.8 # float z = 1j # complex…
Challenge: Numbers Test your understanding of Python number types by completing a small coding challenge.
Challenge: Casting Test your understanding of Python type casting by completing a small coding challenge.
Slicing You can return a range of characters by using the slice syntax. Specify the start index and the end index, separated by a colon, to return a part of the string. Example Get the characters fro…
Python has a set of built-in methods that you can use on strings. Upper Case Example The upper() method returns the string in upper case: a = "Hello, World!" print(a.upper()) Lower Case Example The l…
String Concatenation To concatenate, or combine, two strings you can use the + operator. Example Merge variable a with variable b into variable c a = "Hello" b = "World" c = a + b print(c) Example To…
String Format As we learned in the Python Variables chapter, we cannot combine strings and numbers like this: Example age = 36 #This will produce an error: txt = "My name is John, I am " + age print(…
Escape Character To insert characters that are illegal in a string, use an escape character. An escape character is a backslash \ followed by the character you want to insert. An example of an illega…
Test Yourself With Exercises Now you have learned a lot about Strings, and how to use them in Python. Are you ready for a test? Test your Python String skills with exercises from all categories: Stri…
Challenge: Strings Basics Test your understanding of creating, slicing, modifying, and formatting strings.
Challenge: Booleans Test your understanding of Python booleans by completing a small coding challenge.
Python Operators Operators are used to perform operations on variables and values. In the example below, we use the + operator to add together two values: Example print(10 + 5) Although the + operato…
Arithmetic Operators Arithmetic operators are used with numeric values to perform common mathematical operations: Operator Name Example Try it + Addition x + y Try it » Subtraction x - y Try it » * M…
Assignment Operators Assignment operators are used to assign values to variables: Operator Example Same As Try it = x = 5 x = 5 Try it » += x += 3 x = x + 3 Try it » -= x -= 3 x = x - 3 Try it » *= x…
Comparison Operators Comparison operators are used to compare two values: Operator Name Example Try it == Equal x == y Try it » != Not equal x != y Try it » > Greater than x > y Try it » < Less than…
Logical Operators Logical operators are used to combine conditional statements: Operator Description Example Try it and Returns True if both statements are true x < 5 and x < 10 Try it » or Returns T…
Identity Operators Identity operators are used to compare the objects, not if they are equal, but if they are actually the same object, with the same memory location: Operator Description Example Try…
Membership Operators Membership operators are used to test if a sequence is presented in an object: Operator Description Example Try it in Returns True if a sequence with the specified value is prese…
Bitwise Operators Bitwise operators are used to compare (binary) numbers: Operator Name Description Example Try it & AND Sets each bit to 1 if both bits are 1 x & y Try it » | OR Sets each bit to 1 i…
Operator Precedence Operator precedence describes the order in which operations are performed. Example Parentheses has the highest precedence, meaning that expressions inside parentheses must be eval…
Challenge: Operators Basics Test your understanding of arithmetic, assignment, and comparison operators.
Access Items List items are indexed and you can access them by referring to the index number: Example Print the second item of the list: thislist = ["apple", "banana", "cherry"] print(thislist[1]) No…
Change Item Value To change the value of a specific item, refer to the index number: Example Change the second item: thislist = ["apple", "banana", "cherry"] thislist[1] = "blackcurrant" print(thisli…
Append Items To add an item to the end of the list, use the append() method: Example Using the append() method to append an item: thislist = ["apple", "banana", "cherry"] thislist.append("orange") pr…
Remove Specified Item The method removes the specified item. Example Remove "banana": thislist = ["apple", "banana", "cherry"] thislist.remove("banana") print(thislist) If there are more than one ite…
Loop Through a List You can loop through the list items by using a for loop: Example Print all items in the list, one by one: thislist = ["apple", "banana", "cherry"] for x in thislist: print(x) Lear…
List Comprehension List comprehension offers a shorter syntax when you want to create a new list based on the values of an existing list. Example: Based on a list of fruits, you want a new list, cont…
Sort List Alphanumerically List objects have a sort() method that will sort the list alphanumerically, ascending, by default: Example Sort the list alphabetically: thislist = ["orange", "mango", "kiw…
Join Two Lists There are several ways to join, or concatenate, two or more lists in Python. One of the easiest ways are by using the + operator. Example Join two list: list1 = ["a", "b", "c"] list2 =…
Python List Exercises
Challenge: Lists Basics Test your understanding of creating, accessing, changing, adding, and removing list items.
Access Tuple Items You can access tuple items by referring to the index number, inside square brackets: Example Print the second item in the tuple: thistuple = ("apple", "banana", "cherry") print(thi…
Unpacking a Tuple When we create a tuple, we normally assign values to it. This is called "packing" a tuple: Example Packing a tuple: fruits = ("apple", "banana", "cherry") But, in Python, we are als…
Loop Through a Tuple You can loop through the tuple items by using a for loop. Example Iterate through the items and print the values: thistuple = ("apple", "banana", "cherry") for x in thistuple: pr…
Join Two Tuples To join two or more tuples you can use the + operator: Example Join two tuples: tuple1 = ("a", "b" , "c") tuple2 = (1, 2, 3) tuple3 = tuple1 + tuple2 print(tuple3) Multiply Tuples If…
Python - Tuple Exercises
Challenge: Tuples Basics Test your understanding of creating, accessing, and unpacking tuples.
Add Items Once a set is created, you cannot change its items, but you can add new items. To add one item to a set use the add() method. Example Add an item to a set, using the add() method: thisset =…
Remove Item To remove an item in a set, use the , or the discard() method. Example Remove "banana" by using the method: thisset = {"apple", "banana", "cherry"} thisset.remove("banana") print(thisset)…
Loop Items You can loop through the set items by using a for loop: Example Loop through the set, and print the values: thisset = {"apple", "banana", "cherry"} for x in thisset: print(x)
Python - Set Exercises
Challenge: Sets Basics Test your understanding of creating, adding, removing, and checking set items.
Accessing Items You can access the items of a dictionary by referring to its key name, inside square brackets: Example Get the value of the "model" key: thisdict = { "brand": "Ford", "model": "Mustan…
Change Values You can change the value of a specific item by referring to its key name: Example Change the "year" to 2018: thisdict = { "brand": "Ford", "model": "Mustang", "year": 1964 } thisdict["y…
Adding Items Adding an item to the dictionary is done by using a new index key and assigning a value to it: Example thisdict = { "brand": "Ford", "model": "Mustang", "year": 1964 } thisdict["color"]…
Removing Items There are several methods to remove items from a dictionary: Example The pop() method removes the item with the specified key name: thisdict = { "brand": "Ford", "model": "Mustang", "y…
Nested Dictionaries A dictionary can contain dictionaries, this is called nested dictionaries. Example Create a dictionary that contain three dictionaries: myfamily = { "child1" : { "name" : "Emil",…
Python Dictionary Exercises
Challenge: Dictionaries Basics Test your understanding of creating, accessing, changing, adding, and removing dictionary items.
Short Hand If If you have only one statement to execute, you can put it on the same line as the if statement. Example One-line if statement: a = 5 b = 2 if a > b: print("a is greater than b") Note: Y…
Nested If Statements You can have if statements inside if statements. This is called nested if statements. Example x = 41 if x > 10: print("Above ten,") if x > 20: print("and also above 20!") else: p…
The pass Statement if statements cannot be empty, but if you for some reason have an if statement with no content, put in the pass statement to avoid getting an error. Example a = 33 b = 200 if b > a…
Challenge: If...Else Basics Test your understanding of if, elif, else, and shorthand if statements.
Challenge: Match Test your understanding of Python match by completing a small coding challenge.
Python Loops Python has two primitive loop commands: while loops for loops The while Loop With the while loop we can execute a set of statements as long as a condition is true. Example Print i as lon…
Challenge: While Loops Test your understanding of Python while loops by completing a small coding challenge.
Challenge: For Loops Test your understanding of Python for loops by completing a small coding challenge.
Challenge: Functions Basics Test your understanding of creating functions, parameters, return values, and *args.
Challenge: Range Test your understanding of Python range by completing a small coding challenge.
Challenge: Arrays Test your understanding of Python arrays by completing a small coding challenge.
Challenge: Iterators Test your understanding of Python iterators by completing a small coding challenge.
Challenge: Modules Test your understanding of Python modules by completing a small coding challenge.
Python Dates A date in Python is not a data type of its own, but we can import a module named datetime to work with dates as date objects. Example Import the datetime module and display the current d…
Challenge: Dates Test your understanding of Python dates by completing a small coding challenge.
Challenge: Math Test your understanding of Python math by completing a small coding challenge.
Challenge: JSON Test your understanding of Python json by completing a small coding challenge.
Challenge: RegEx Test your understanding of Python regex by completing a small coding challenge.
Challenge: Try...Except Test your understanding of Python try...except by completing a small coding challenge.
Challenge: String Formatting Test your understanding of Python string formatting by completing a small coding challenge.
Challenge: None Test your understanding of Python's None value by completing a small coding challenge.
User Input Python allows for user input. That means we are able to ask the user for input. The following example asks for your name, and when you enter a name, it gets printed on the screen: Example…