Holy Python

HolyPython.com

Beginner Python Exercises

Here are some enjoyable Python Exercises for you to solve! We strive to offer a huge selection of Python Exercises so you can internalize the Python Concepts through these exercises. 

Among these Python Exercises you can find the most basic Python Concepts about Python Syntax and built-in functions and methods .

basic python assignments for beginners

Holy Python is reader-supported. When you buy through links on our site, we may earn an affiliate commission.

Choose the topics you'd like to practice from our extensive exercise list.

Python Beginner Exercises consist of some 125+ exercises that can be solved by beginner coders and newcomers to the Python world.

Majority of these exercises are online and interactive which offers an easier and convenient entry point for beginners.

First batch of the exercises starts with print function as a warm up but quickly, it becomes all about data. 

You can start exercising with making variable assignments and move on with the most fundamental data types in Python:

Exercise 1: print() function    |   (3) : Get your feet wet and have some fun with the universal first step of programming.

Exercise 2: Variables    |   (2) : Practice assigning data to variables with these Python exercises.

Exercise 3: Data Types    |   (4) : Integer (int), string (str) and float are the most basic and fundamental building blocks of data in Python.

Exercise 4: Type Conversion    |   (8) : Practice converting between basic data types of Python when applicable.

Exercise 5: Data Structures    |   (6) : Next stop is exercises of most commonly used Python Data Structures. Namely;

  • Dictionaries and
  • Strings are placed under the microscope.

Exercise 6: Lists    |   (14) : It’s hard to overdo Python list exercises. They are fun and very fundamental so we prepared lots of them. You will also have the opportunity to practice various Python list methods.

Exercise 7: Tuples    |   (8) : Python Tuples Exercises with basic applications as well as common tuples methods

Exercise 8: Dictionaries    |   (11) : Practice with Python Dictionaries and some common dictionary methods.

Exercise 9: Strings    |   (14) : Basic string operations as well as many string methods can be practiced through 10+ Python String Exercises we have prepared for you.

Next batch consist of some builtin Python functions and Python methods. The difference between function and method in Python is that functions are more like standalone blocks of codes that take arguments while methods apply directly on a class of objects.

That’s why we can talk about list methods, string methods, dictionary methods in Python but functions can be used alone as long as appropriate arguments are passed in them.

Exercise 10: len() function     |   (5) : Python’s len function tells the length of an object. It’s definitely a must know and very useful in endless scenarios. Whether it’s manipulating strings or counting elements in a list, len function is constantly used in computer programming.

Exercise 11: .sort() method     |   (7) : Practice sort method in Beginner Python Exercises and later on you’ll have the opportunity practice sorted function in Intermediate Python Exercises.

Exercise 12: .pop() method     |   (3) : A list method pop can be applied to Python list objects. It’s pretty straightforward but actually easy to confuse. These exercises will help you understand pop method better.

Exercise 13: input() function     |   (6) : Input function is a fun and useful Python function that can be used to acquire input values from the user.

Exercise 14: range() function     |   (5) : You might want to take a real close look at range function because it can be very useful in numerous scenarios.

These range exercises offer an opportunity to get a good practice and become proficient with the usage of Python’s range function.

Exercise 15: Error Handling    |   (7) : Error Handling is a must know coding skill and Python has some very explanatory Error Codes that will make a coder’s life easier if he/she knows them!

Exercise 16: Defining Functions    |   (9) : Practicing user defined Python functions will take your programming skills to the next step. Writing functions are super useful and fun. It makes code reusable too.

Exercise 17: Python Slicing Notation     |   (8) : Python’s slicing notations are very interesting but can be confusing for beginner coders. These exercises will help you master them.

Exercise 18: Python Operators    |   (6) : Operators are another fundamental concept. We have prepared multiple exercises so they can be confident in using Python Operators.

If you struggle with any of the exercises, you can always refer to the Beginner Python Lessons .

If you’d like to challenge yourself with the next level of Python exercises check out the Intermediate Python Exercises we have prepared for you.

FREE ONLINE PYTHON COURSES

Choose from over 100+ free online Python courses.

Python Lessons

Beginner lessons.

Simple builtin Python functions and fundamental concepts.

Intermediate Lessons

More builtin Python functions and slightly heavier fundamental coding concepts.

Advanced Lessons

Python concepts that let you apply coding in the real world generally implementing multiple methods.

Python Exercises

Beginner exercises.

Basic Python exercises that are simple and straightforward.

Intermediate Exercises

Slightly more complex Python exercises and more Python functions to practice.

Advanced Exercises

Project-like Python exercises to connect the dots and prepare for real world tasks.

Thank you for checking out our Python programming content. All of the Python lessons and exercises we provide are free of charge. Also, majority of the Python exercises have an online and interactive interface which can be helpful in the early stages of learning computer programming.

However, we do recommend you to have a local Python setup on your computer as soon as possible. Anaconda is a free distribution and it comes as a complete package with lots of libraries and useful software (such as Spyder IDE and Jupyter Notebook) You can check out this: simple Anaconda installation tutorial .

basic python assignments for beginners

10 Python Practice Exercises for Beginners with Solutions

Author's photo

  • python basics
  • get started with python
  • online practice

A great way to improve quickly at programming with Python is to practice with a wide range of exercises and programming challenges. In this article, we give you 10 Python practice exercises to boost your skills.

Practice exercises are a great way to learn Python. Well-designed exercises expose you to new concepts, such as writing different types of loops, working with different data structures like lists, arrays, and tuples, and reading in different file types. Good exercises should be at a level that is approachable for beginners but also hard enough to challenge you, pushing your knowledge and skills to the next level.

If you’re new to Python and looking for a structured way to improve your programming, consider taking the Python Basics Practice course. It includes 17 interactive exercises designed to improve all aspects of your programming and get you into good programming habits early. Read about the course in the March 2023 episode of our series Python Course of the Month .

Take the course Python Practice: Word Games , and you gain experience working with string functions and text files through its 27 interactive exercises.  Its release announcement gives you more information and a feel for how it works.

Each course has enough material to keep you busy for about 10 hours. To give you a little taste of what these courses teach you, we have selected 10 Python practice exercises straight from these courses. We’ll give you the exercises and solutions with detailed explanations about how they work.

To get the most out of this article, have a go at solving the problems before reading the solutions. Some of these practice exercises have a few possible solutions, so also try to come up with an alternative solution after you’ve gone through each exercise.

Let’s get started!

Exercise 1: User Input and Conditional Statements

Write a program that asks the user for a number then prints the following sentence that number of times: ‘I am back to check on my skills!’ If the number is greater than 10, print this sentence instead: ‘Python conditions and loops are a piece of cake.’ Assume you can only pass positive integers.

Here, we start by using the built-in function input() , which accepts user input from the keyboard. The first argument is the prompt displayed on the screen; the input is converted into an integer with int() and saved as the variable number. If the variable number is greater than 10, the first message is printed once on the screen. If not, the second message is printed in a loop number times.

Exercise 2: Lowercase and Uppercase Characters

Below is a string, text . It contains a long string of characters. Your task is to iterate over the characters of the string, count uppercase letters and lowercase letters, and print the result:

We start this one by initializing the two counters for uppercase and lowercase characters. Then, we loop through every letter in text and check if it is lowercase. If so, we increment the lowercase counter by one. If not, we check if it is uppercase and if so, we increment the uppercase counter by one. Finally, we print the results in the required format.

Exercise 3: Building Triangles

Create a function named is_triangle_possible() that accepts three positive numbers. It should return True if it is possible to create a triangle from line segments of given lengths and False otherwise. With 3 numbers, it is sometimes, but not always, possible to create a triangle: You cannot create a triangle from a = 13, b = 2, and c = 3, but you can from a = 13, b = 9, and c = 10.

The key to solving this problem is to determine when three lines make a triangle regardless of the type of triangle. It may be helpful to start drawing triangles before you start coding anything.

Python Practice Exercises for Beginners

Notice that the sum of any two sides must be larger than the third side to form a triangle. That means we need a + b > c, c + b > a, and a + c > b. All three conditions must be met to form a triangle; hence we need the and condition in the solution. Once you have this insight, the solution is easy!

Exercise 4: Call a Function From Another Function

Create two functions: print_five_times() and speak() . The function print_five_times() should accept one parameter (called sentence) and print it five times. The function speak(sentence, repeat) should have two parameters: sentence (a string of letters), and repeat (a Boolean with a default value set to False ). If the repeat parameter is set to False , the function should just print a sentence once. If the repeat parameter is set to True, the function should call the print_five_times() function.

This is a good example of calling a function in another function. It is something you’ll do often in your programming career. It is also a nice demonstration of how to use a Boolean flag to control the flow of your program.

If the repeat parameter is True, the print_five_times() function is called, which prints the sentence parameter 5 times in a loop. Otherwise, the sentence parameter is just printed once. Note that in Python, writing if repeat is equivalent to if repeat == True .

Exercise 5: Looping and Conditional Statements

Write a function called find_greater_than() that takes two parameters: a list of numbers and an integer threshold. The function should create a new list containing all numbers in the input list greater than the given threshold. The order of numbers in the result list should be the same as in the input list. For example:

Here, we start by defining an empty list to store our results. Then, we loop through all elements in the input list and test if the element is greater than the threshold. If so, we append the element to the new list.

Notice that we do not explicitly need an else and pass to do nothing when integer is not greater than threshold . You may include this if you like.

Exercise 6: Nested Loops and Conditional Statements

Write a function called find_censored_words() that accepts a list of strings and a list of special characters as its arguments, and prints all censored words from it one by one in separate lines. A word is considered censored if it has at least one character from the special_chars list. Use the word_list variable to test your function. We've prepared the two lists for you:

This is another nice example of looping through a list and testing a condition. We start by looping through every word in word_list . Then, we loop through every character in the current word and check if the current character is in the special_chars list.

This time, however, we have a break statement. This exits the inner loop as soon as we detect one special character since it does not matter if we have one or several special characters in the word.

Exercise 7: Lists and Tuples

Create a function find_short_long_word(words_list) . The function should return a tuple of the shortest word in the list and the longest word in the list (in that order). If there are multiple words that qualify as the shortest word, return the first shortest word in the list. And if there are multiple words that qualify as the longest word, return the last longest word in the list. For example, for the following list:

the function should return

Assume the input list is non-empty.

The key to this problem is to start with a “guess” for the shortest and longest words. We do this by creating variables shortest_word and longest_word and setting both to be the first word in the input list.

We loop through the words in the input list and check if the current word is shorter than our initial “guess.” If so, we update the shortest_word variable. If not, we check to see if it is longer than or equal to our initial “guess” for the longest word, and if so, we update the longest_word variable. Having the >= condition ensures the longest word is the last longest word. Finally, we return the shortest and longest words in a tuple.

Exercise 8: Dictionaries

As you see, we've prepared the test_results variable for you. Your task is to iterate over the values of the dictionary and print all names of people who received less than 45 points.

Here, we have an example of how to iterate through a dictionary. Dictionaries are useful data structures that allow you to create a key (the names of the students) and attach a value to it (their test results). Dictionaries have the dictionary.items() method, which returns an object with each key:value pair in a tuple.

The solution shows how to loop through this object and assign a key and a value to two variables. Then, we test whether the value variable is greater than 45. If so, we print the key variable.

Exercise 9: More Dictionaries

Write a function called consonant_vowels_count(frequencies_dictionary, vowels) that takes a dictionary and a list of vowels as arguments. The keys of the dictionary are letters and the values are their frequencies. The function should print the total number of consonants and the total number of vowels in the following format:

For example, for input:

the output should be:

Working with dictionaries is an important skill. So, here’s another exercise that requires you to iterate through dictionary items.

We start by defining a list of vowels. Next, we need to define two counters, one for vowels and one for consonants, both set to zero. Then, we iterate through the input dictionary items and test whether the key is in the vowels list. If so, we increase the vowels counter by one, if not, we increase the consonants counter by one. Finally, we print out the results in the required format.

Exercise 10: String Encryption

Implement the Caesar cipher . This is a simple encryption technique that substitutes every letter in a word with another letter from some fixed number of positions down the alphabet.

For example, consider the string 'word' . If we shift every letter down one position in the alphabet, we have 'xpse' . Shifting by 2 positions gives the string 'yqtf' . Start by defining a string with every letter in the alphabet:

Name your function cipher(word, shift) , which accepts a string to encrypt, and an integer number of positions in the alphabet by which to shift every letter.

This exercise is taken from the Word Games course. We have our string containing all lowercase letters, from which we create a shifted alphabet using a clever little string-slicing technique. Next, we create an empty string to store our encrypted word. Then, we loop through every letter in the word and find its index, or position, in the alphabet. Using this index, we get the corresponding shifted letter from the shifted alphabet string. This letter is added to the end of the new_word string.

This is just one approach to solving this problem, and it only works for lowercase words. Try inputting a word with an uppercase letter; you’ll get a ValueError . When you take the Word Games course, you slowly work up to a better solution step-by-step. This better solution takes advantage of two built-in functions chr() and ord() to make it simpler and more robust. The course contains three similar games, with each game comprising several practice exercises to build up your knowledge.

Do You Want More Python Practice Exercises?

We have given you a taste of the Python practice exercises available in two of our courses, Python Basics Practice and Python Practice: Word Games . These courses are designed to develop skills important to a successful Python programmer, and the exercises above were taken directly from the courses. Sign up for our platform (it’s free!) to find more exercises like these.

We’ve discussed Different Ways to Practice Python in the past, and doing interactive exercises is just one way. Our other tips include reading books, watching videos, and taking on projects. For tips on good books for Python, check out “ The 5 Best Python Books for Beginners .” It’s important to get the basics down first and make sure your practice exercises are fun, as we discuss in “ What’s the Best Way to Practice Python? ” If you keep up with your practice exercises, you’ll become a Python master in no time!

You may also like

basic python assignments for beginners

How Do You Write a SELECT Statement in SQL?

basic python assignments for beginners

What Is a Foreign Key in SQL?

basic python assignments for beginners

Enumerate and Explain All the Basic Elements of an SQL Query

basic python assignments for beginners

Practice Python

follow us in feedly

Beginner Python exercises

  • Why Practice Python?
  • Why Chilis?
  • Resources for learners

All Exercises

basic python assignments for beginners

All Solutions

  • 1: Character Input Solutions
  • 2: Odd Or Even Solutions
  • 3: List Less Than Ten Solutions
  • 4: Divisors Solutions
  • 5: List Overlap Solutions
  • 6: String Lists Solutions
  • 7: List Comprehensions Solutions
  • 8: Rock Paper Scissors Solutions
  • 9: Guessing Game One Solutions
  • 10: List Overlap Comprehensions Solutions
  • 11: Check Primality Functions Solutions
  • 12: List Ends Solutions
  • 13: Fibonacci Solutions
  • 14: List Remove Duplicates Solutions
  • 15: Reverse Word Order Solutions
  • 16: Password Generator Solutions
  • 17: Decode A Web Page Solutions
  • 18: Cows And Bulls Solutions
  • 19: Decode A Web Page Two Solutions
  • 20: Element Search Solutions
  • 21: Write To A File Solutions
  • 22: Read From File Solutions
  • 23: File Overlap Solutions
  • 24: Draw A Game Board Solutions
  • 25: Guessing Game Two Solutions
  • 26: Check Tic Tac Toe Solutions
  • 27: Tic Tac Toe Draw Solutions
  • 28: Max Of Three Solutions
  • 29: Tic Tac Toe Game Solutions
  • 30: Pick Word Solutions
  • 31: Guess Letters Solutions
  • 32: Hangman Solutions
  • 33: Birthday Dictionaries Solutions
  • 34: Birthday Json Solutions
  • 35: Birthday Months Solutions
  • 36: Birthday Plots Solutions
  • 37: Functions Refactor Solution
  • 38: f Strings Solution
  • 39: Character Input Datetime Solution
  • 40: Error Checking Solution

Top online courses in Programming Languages

Learn Python Basics – A Guide for Beginners

chepkirui dorothy

Are you eager to dive into the world of programming but unsure where to begin? Look no further – Python is an excellent starting point for both newcomers and seasoned developers.

In this guide, I'll take you through the basics so you can get started on your Python journey.

Table of Contents

Prerequisites, why learn python, key characteristics of python, practical uses of python, how to write "hello, world" in python.

  • Characteristics of Primitive Data Types
  • Use Cases for Primitive Data Types
  • Characteristics of Non-Primitive Data Types
  • Use Cases for Non-Primitive Data Types
  • Arithmetic Operators

Comparison Operators

Assignment statements, print statement, conditional statements (if, elif, else), break and continue statements, functions in python.

Before you embark on this coding adventure, make sure you have the following:

  • Python installed .
  • A code editor like VSCode , Vim , or Sublime .

Now, let's explore the advantages of using Python.

If you're wondering why Python is an excellent choice for beginners and seasoned developers alike, here are some of the reasons:

  • Readability and Simplicity: Python's clean syntax enhances code readability, reducing development time and making it beginner-friendly.
  • Versatility: You can use Python to build a diverse range of applications, from web development to data science and AI. It also has an extensive standard library and many helpful third-party packages.
  • Community and Documentation: Python has a robust community and comprehensive documentation that provides ample support, fostering the language's popularity and growth.
  • Cross-Platform Compatibility: Ensures seamless execution across Windows, macOS, and Linux.
  • Extensive Libraries and Frameworks: A rich ecosystem simplifies complex tasks, saving time and effort for developers.

Hopefully, you're intrigued by Python's perks – so let's delve into its key characteristics.

Understanding the key characteristics of Python will give you insights into its strengths and why it's a popular choice among developers:

  • Interpreted Language: Your code is not directly translated by the target machine. Instead, a special program called the interpreter reads and executes the code, allowing for cross-platform execution of your code.
  • Dynamically Typed: Dynamic typing eliminates the need for explicit data type declarations, enhancing simplicity and flexibility.
  • Object-Oriented: Python supports object-oriented principles, promoting code modularity and reusability.
  • Indentation-based Syntax: Indentation-based syntax enforces code readability and maintains a consistent coding style.
  • Memory Management: Automatic memory management through garbage collection simplifies memory handling for developers.

Python's versatility and readability make it suitable for a wide array of applications. Here are some practical uses:

  • Web Development: Python, with frameworks like Django and Flask, powers back-end development for robust web applications.
  • Data Science and Machine Learning: Widely used in data science, Python's libraries like NumPy and Pandas support data analysis and machine learning.
  • Automation and Scripting: Python excels in automating tasks and scripting, simplifying repetitive operations.
  • AI and NLP: Python, with libraries like TensorFlow, dominates in AI and natural language processing applications.
  • Game Development: Python, combined with Pygame, facilitates 2D game development for hobbyists and indie developers.
  • Scientific Computing: Python is a valuable tool in scientific computing, chosen by scientists and researchers for its extensive libraries.

Python is pre-installed in most Linux distributions. Follow this article on how to install Python on Windows and MacOS.

This is usually the first achievement when starting to code in any language: having your code say 'Hello world'. Open any code editor of your choice, and create a file named project.py . Inside the file, type the following:

To run this code, open the command line interface (CLI). Follow this article to understand more about CLI.

Make sure to open the directory where the file is saved, and run the following:

When you run this program, you'll see the timeless greeting displayed in your command line interface.

Screenshot-from-2024-01-30-11-59-12

‌Congratulations! You've just executed your first Python script. Now that you've printed a simple message, let's dive deeper into Python.

Python Variables and Data Types

The primary purpose of computers is to process data into useful information, for that to happen, the data needs to be stored in its memory. This is achieved using a programming language's variables and data types.

Data types in Python are particular kinds of data items, as defined by the value they can take. Variables, on the other hand, are like labeled containers that store this data. They enable you to manage and modify information using specific identifiers.

Data types are generally classified into two types:

Primitive (Fundamental) Data Types:

Primitive data types represent simple values. These data types are the most basic and essential units used to store and manipulate information in a program. They translate directly into low-level machine code.

Primitive data types include:

  • String ( str ): Represents sequences of characters. Should be enclosed in quotes. Example: "Hello, Python!"
  • Integer ( int ): Represents whole numbers without decimals. Example: 42
  • Float ( float ): Represents numbers with decimals. Example: 3.14
  • Boolean ( bool ): Represents either True or False .

Characteristics of Primitive Data Types:

  • Immutability: Primitive data types are immutable, meaning their values cannot be changed after they are created. Any operation that appears to modify a primitive value creates a new value.
  • Direct Representation: Each primitive data type directly corresponds to a specific low-level machine code representation.
  • Atomic Values: Primitive data types represent individual, atomic values. They are not composed of other types or structures.

Use Cases for Primitive Data Types:

  • Strings are used for text manipulation and representation.
  • Integers and floats are essential for numerical calculations.
  • Booleans are employed in logical operations and decision-making.

Let's see how these work by continuing to write some Python code.

Modify your project.py file to include the following:

In this snippet, you've introduced variables with different data types. Run the program and observe how Python handles these data types.

Screenshot-from-2024-01-30-12-02-11

The output reveals the values assigned to the variables in the Python script. The print statements display the contents of the name , age , height , and is_student variables.

‌‌Non-Primitive (Composite) Data Types in Python

Non-primitive data types are structures that can hold multiple values and are composed of other data types, including both primitive and other composite types. Unlike primitive data types, non-primitive types allow for more complex and structured representations of data.

Non-primitive data types include:

  • List ( list ): Represents an ordered and mutable collection of values. Example: fruits = ["apple", "banana", "cherry"]
  • Tuple ( tuple ): Represents an ordered and immutable collection of values. Example: coordinates = (3, 7)
  • Dictionary ( dict ): Represents an unordered collection of key-value pairs. Example: person = {"name": "Alice", "age": 25, "is_student": True}

Characteristics of Non-Primitive Data Types:

  • Mutability: Lists are mutable, meaning their elements can be modified after creation. Tuples, on the other hand, are immutable – their elements cannot be changed. Dictionaries are mutable – you can add, modify, or remove key-value pairs.
  • Collection of Values: Non-primitive data types allow the grouping of multiple values into a single structure, enabling the creation of more sophisticated data representations.
  • Ordered (Lists and Tuples): Lists and tuples maintain the order of elements, allowing for predictable indexing.
  • Key-Value Mapping (Dictionary): Dictionaries map keys to values, providing a way to organize and retrieve data based on specific identifiers.

Use Cases for Non-Primitive Data Types:

  • Lists: Useful when you need a collection that can be altered during the program's execution, such as maintaining a list of items that may change over time.
  • Tuples: Suitable when you want to ensure that the data remains constant and cannot be accidentally modified. Often used for representing fixed sets of values.
  • Dictionaries: Ideal for scenarios where data needs to be associated with specific labels or keys. They offer efficient data retrieval based on these identifiers.

Alright, continuing with our Python code – modify the project.py file as shown below:

‌Run the program to see how lists and tuples allow you to organize and store data. In this code snippet:

  • The fruits variable is a list containing strings representing different fruits.
  • The coordinates variable is a tuple with two integers representing coordinates.
  • The person variable is a dictionary associating keys ("name," "age," "is_student") with corresponding values.

Screenshot-from-2024-01-31-11-19-39

You can perform various operations on these structures, such as adding elements to a list or accessing individual items in a tuple.

Data types are crucial for several reasons:

  • Memory Allocation: Different data types require different amounts of memory. Knowing the data type allows the computer to allocate the appropriate amount of memory for a variable.
  • Operations: Each data type supports specific operations. For example, you can add two integer numbers, concatenate two strings , or compare two boolean values.
  • Error Prevention: Using the wrong data type in an operation can lead to errors. Data types help prevent unintended consequences by enforcing rules on how different types can interact.

Operators in Python

Operators in Python are symbols that perform operations on variables and values. An operand refers to the inputs or objects on which an operation is performed.

Let's explore some of the essential operators in Python:

Arithmetic Operators:

Arithmetic operators are fundamental components of any programming language, allowing developers to perform basic mathematical operations on numerical values.

In Python, several arithmetic operators enable you to carry out calculations efficiently. Let's explore these operators:

  • Addition (+): Adds two operands.
  • Subtraction (-): Subtracts the right operand from the left operand.
  • Multiplication (*): Multiplies two operands.
  • Division (/): Divides the left operand by the right operand (always returns a float).
  • Modulus (%): Returns the remainder of the division of the left operand by the right operand.
  • Exponentiation (**): Raises the left operand to the power of the right operand.

Modify your project.py file to include examples of these operators:

The code above initializes two variables, num1 and num2 , with the values 10 and 3 respectively, representing two numerical operands.

Then, arithmetic operations are performed using these operands:

  • add_result stores the result of adding num1 and num2 .
  • sub_result stores the result of subtracting num2 from num1 .
  • mul_result stores the result of multiplying num1 and num2 .
  • div_result stores the result of dividing num1 by num2 .
  • mod_result stores the remainder of dividing num1 by num2 .
  • exp_result stores the result of raising num1 to the power of num2 .

Finally, the results of these arithmetic operations are printed using print() statements, each labeled appropriately, such as "Addition:", "Subtraction:", and so on, followed by the corresponding result.

Here's the output:

arithmetic

Comparison operators in Python are essential tools for evaluating and comparing values. They enable you to express conditions and make decisions based on the relationship between different values.  They return either True or False based on the comparison result.

Here are the common comparison operators:

  • Equal to (==): Checks if two operands are equal.
  • Not equal to (!=): Checks if two operands are not equal.
  • Greater than (>): Checks if the left operand is greater than the right operand.
  • Less than (<): Checks if the left operand is less than the right operand.
  • Greater than or equal to (>=): Checks if the left operand is greater than or equal to the right operand.
  • Less than or equal to (<=): Checks if the left operand is less than or equal to the right operand.

Extend your project.py file to include examples of comparison operators:

The variable age is initialized with the value 25 , representing a person's age.

Then, the comparison operator >= is used to evaluate whether age is greater than or equal to 18 . The result of this comparison determines the boolean value stored in the variable is_adult . If the age is 18 or older, is_adult will be True , indicating adulthood.

Then the logical operator and is utilized to combine two comparison operations. The first comparison, age >= 13 , checks if the age is 13 or older. The second comparison, age < 18 , ensures the age is less than 18 . If both conditions are true, is_teenager will be True , signifying teenage years.

Finally, the results are printed using print() statements, indicating whether the person is classified as an adult ( True or False ) and whether they are identified as a teenager ( True or False ).

is-adult

Statements in Python

Statements instruct the interpreter to perform specific actions or operations. These actions can range from simple assignments of values to variables to more complex control flow structures and iterations.

Understanding different types of statements is essential for writing effective and expressive Python code.

Assignment statements are the most basic type of statement in Python. They are used to assign values to variables, creating a named reference to data.

Here's an example:

In this snippet, x is assigned the integer value 10 , and the name is assigned the string "Alice" . These assignments create variables that can be used throughout the program.

The print statement is used to display output in the console. It is a crucial tool for debugging and providing information to users. Example:

This code prints the string "Hello, Python!" to the console.

Conditional statements are used when you want to execute different blocks of code based on certain conditions.

Suppose you wanted to determine if a person has reached the legal age for drinking.  Modify the project.py file with the following code:

In this example:

  • The if statement checks if age is less than 18.
  • The elif statement (shorthand for else if) checks if age is between 18 (inclusive) and 21 (exclusive).
  • The else statement is executed if none of the above conditions are met.

drinking

A person aged 20 is not allowed to drink.

Loops (for and while)

Loops are used to repeat a block of code multiple times. There are two main types of loops in Python: for loops and while loops.

A for loop is used when you know the number of iterations in advance. Suppose you had a list containing the names of fruits, and you wanted to print each fruit. In this case, a for loop is an ideal choice for iterating over the elements of the list.

Here's an example using Python:

‌In this example, the for loop iterates over each element in the fruits list and prints each fruit.

apple

While Loop:

A while statement is a control flow statement that allows you to execute a block of code repeatedly as long as a specified condition is true.  

Suppose you want to simulate counting until a certain threshold is reached. Modify your project.py and add the following code:

In this scenario, the while loop continues executing as long as the count variable is less than 5. The code inside the loop increments the count and prints the current count in each iteration.

count

Break and continue statements are used within loops.

  • break : Exits the loop.
  • continue : Skips the rest of the code inside the loop for the current iteration, then continues the loop.

‌In the break example, the loop stops when i is equal to 3, and the numbers 0, 1, and 2 are printed.

In the continue example, when i is equal to 2, the continue statement skips the print(i) statement for that iteration, resulting in the omission of the number 2 from the output.

break1

Functions are reusable blocks of code, enhancing modularity by enclosing functionality into separate, organized units. This approach helps avoid code duplication and significantly improves code readability.

Inside the project.py file, write the following code:

The code above contains a simple Python function called greet() . When 'called' or 'invoked', this function prints "Hello, World!" to the console. It's a basic example illustrating how functions work in Python.

You can take this a step further by including parameters. Parameters serve as placeholders for values passed to a function during its invocation, allowing functions to accept input and perform operations based on that input.

Modify the previous example on if elif else statement to include functions:

In this example, the check_age function takes an age parameter and performs the same conditional check as the original code. The function allows you to reuse this logic for different age values by simply calling the function with the desired age.

You can call check_age function with any age value, and it will print the appropriate message based on the age provided.

Screenshot-from-2024-02-07-13-03-23

‌‌‌‌Embarking on your Python learning journey, this guide introduces the benefits of learning Python, its key characteristics, and practical use cases.

Starting with the iconic "Hello, World!" and progressing through variables, data types, statements, and functions, you've gained some hands-on experience with basic Python. We also talked about primitive and non-primitive data types, conditional statements, and loops.

As your journey progresses, delve into advanced topics like object-oriented programming, file handling, and real-world projects. Armed with foundational knowledge, you can now embrace coding challenges that come your way. Stay curious, and relish the rewarding process of coding with Python. Happy coding!

Chepkirui has expertise in Technical Writing and Back-end Development, specifically in Python, Django, and web development. Additionally, she has a passion for photography.

If you read this far, thank the author to show them you care. Say Thanks

Learn to code for free. freeCodeCamp's open source curriculum has helped more than 40,000 people get jobs as developers. Get started

Python Tutorial

File handling, python modules, python numpy, python pandas, python matplotlib, python scipy, machine learning, python mysql, python mongodb, python reference, module reference, python how to, python examples, python exercises.

You can test your Python skills with W3Schools' Exercises.

We have gathered a variety of Python exercises (with answers) for each Python Chapter.

Try to solve an exercise by filling in the missing parts of a code. If you're stuck, hit the "Show Answer" button to see what you've done wrong.

Count Your Score

You will get 1 point for each correct answer. Your score and total score will always be displayed.

Start Python Exercises

Start Python Exercises ❯

If you don't know Python, we suggest that you read our Python Tutorial from scratch.

Kickstart your career

Get certified by completing the course

Get Certified

COLOR PICKER

colorpicker

Contact Sales

If you want to use W3Schools services as an educational institution, team or enterprise, send us an e-mail: [email protected]

Report Error

If you want to report an error, or if you want to make a suggestion, send us an e-mail: [email protected]

Top Tutorials

Top references, top examples, get certified.

Home » Python Basics

Python Basics

In this section, you’ll learn basic Python. If you’re completely new to Python programming, this Python basics section is perfect for you.

After completing the tutorials, you’ll be confident in Python programming and be able to create simple programs in Python.

Section 1. Fundamentals

  • Syntax – introduce you to the basic Python programming syntax.
  • Variables – explain to you what variables are and how to create concise and meaningful variables.
  • Strings – learn about string data and some basic string operations.
  • Numbers – introduce to you the commonly-used number types including integers and floating-point numbers.
  • Booleans – explain the Boolean data type, falsy and truthy values in Python.
  • Constants – show you how to define constants in Python.
  • Comments – learn how to make notes in your code.
  • Type conversion – learn how to convert a value of one type to another e.g., converting a string to a number.

Section 2. Operators

  • Comparison operators – introduce you to the comparison operators and how to use them to compare two values.
  • Logical operators – show you how to use logical operators to combine multiple conditions.

Section 3. Control flow

  • if…else statement – learn how to execute a code block based on a condition.
  • Ternary operator – introduce you to the Python ternary operator that makes your code more concise.
  • for loop with range() – show you how to execute a code block for a fixed number of times by using the for loop with range() function.
  • while – show you how to execute a code block as long as a condition is True.
  • break – learn how to exit a loop prematurely.
  • continue – show you how to skip the current loop iteration and start the next one.
  • pass – show you how to use the pass statement as a placeholder.

Section 4. Functions

  • Python functions – introduce you to functions in Python, and how to define functions, and reuse them in the program.
  • Default parameters – show you how to specify the default values for function parameters.
  • Keyword arguments – learn how to use the keyword arguments to make the function call more obvious.
  • Recursive functions – learn how to define recursive functions in Python.
  • Lambda Expressions – show you how to define anonymous functions in Python using lambda expressions.
  • Docstrings – show you how to use docstrings to document a function.

Section 5. Lists

  • List – introduce you to the list type and how to manipulate list elements effectively.
  • Tuple – introduce you to the tuple which is a list that doesn’t change throughout the program.
  • Sort a list in place – show you how to use the sort() method to sort a list in place.
  • Sort a List – learn how to use the sorted() function to return a new sorted list from the original list.
  • Slice a List – show you how to use the list slicing technique to manipulate lists effectively.
  • Unpack a list – show you how to assign list elements to multiple variables using list unpacking.
  • Iterate over a List – learn how to use a for loop to iterate over a list.
  • Find the index of an element – show you how to find the index of the first occurrence of an element in a list.
  • Iterables – explain to you iterables, and the difference between an iterable and an iterator.
  • Transform list elements with map() – show you how to use the map() function to transform list elements.
  • Filter list elements with filter() – use the filter() function to filter list elements.
  • Reduce list elements into a value with reduce() – use the reduce() function to reduce list elements into a single value.
  • List comprehensions – show you how to create a new list based on an existing list.

Section 6. Dictionaries

  • Dictionary – introduce you to the dictionary type.
  • Dictionary comprehension – show you how to use dictionary comprehension to create a new dictionary from an existing one.

Section 7. Sets

  • Set – explain to you the Set type and show you how to manipulate set elements effectively.
  • Set comprehension – explain to you the set comprehension so that you can create a new set based on an existing set with a more concise and elegant syntax.
  • Union of Sets – show you how to union two or more sets using the union() method or set union operator ( | ).
  • Intersection of Sets – show you how to intersect two or more sets using the intersection() method or set intersection operator ( & ).
  • Difference of sets – learn how to find the difference between sets using the set difference() method or set difference operator ( - )
  • Symmetric Difference of sets – guide you on how to find the symmetric difference of sets using the symmetric_difference() method or the symmetric difference operator ( ^ ).
  • Subset – check if a set is a subset of another set.
  • Superset – check if a set is a superset of another set.
  • Disjoint sets – check if two sets are disjoint.

Section 8. Exception handling

  • try…except – show you how to handle exceptions more gracefully using the try…except statement.
  • try…except…finally – learn how to execute a code block whether an exception occurs or not.
  • try…except…else – explain to you how to use the try…except…else statement to control the follow of the program in case of exceptions.

Section 9. More on Python Loops

  • for…else – explain to you the for else statement.
  • while…else – discuss the while else statement.
  • do…while loop emulation – show you how to emulate the do…while loop in Python by using the while loop statement.

Section 10. More on Python functions

  • Unpacking tuples – show you how to unpack a tuple that assigns individual elements of a tuple to multiple variables.
  • *args Parameters – learn how to pass a variable number of arguments to a function.
  • **kwargs Parameters – show you how to pass a variable number of keyword arguments to a function.
  • Partial functions – learn how to define partial functions.
  • Type hints – show you how to add type hints to the parameters of a function and how to use the static type checker (mypy) to check the type statically.

Section 11. Modules & Packages

  • Modules – introduce you to the Python modules and show you how to write your own modules.
  • Module search path – explain to you how the Python module search path works when you import a module.
  • __name__ variable – show you how to use the __name__ variable to control the execution of a Python file as a script or as a module.
  • Packages – learn how to use packages to organize modules in more structured ways.

Section 12. Working with files

  • Read from a text file – learn how to read from a text file.
  • Write to a text file – show you how to write to a text file.
  • Create a new text file – walk you through the steps of creating a new text file.
  • Check if a file exists – show you how to check if a file exists.
  • Read CSV files – show you how to read data from a CSV file using the csv module.
  • Write CSV files – learn how to write data to a CSV file using the csv module.
  • Rename a file – guide you on how to rename a file.
  • Delete a file – show you how to delete a file.

Section 13. Working Directories

  • Working with directories – show you commonly used functions to work with directories.
  • List files in a Directory – list files in a directory.

Section 14. Third-party Packages, PIP, and Virtual Environments

  • Python Package Index (PyPI) and pip – introduce you to the Python package index and how to install third-party packages using pip.
  • Virtual Environments – understand Python virtual environments and more importantly, why you need them.
  • Install pipenv on Windows – show you how to install the pipenv tool on Windows.

Section 15. Strings

  • F-strings – learn how to use the f-strings to format text strings in a clear syntax.
  • Raw strings – use raw strings to handle strings that contain the backslashes.
  • Backslash – explain how Python uses the backslashes ( \ ) in string literals.
  • Google for Education
  • Español – América Latina
  • Português – Brasil
  • Tiếng Việt

Basic Python Exercises

These exercise files are located under the basic subdirectory under google-python-exercises .

With all the exercises, you can take a look at our solution code inside the solution subdirectory.

Except as otherwise noted, the content of this page is licensed under the Creative Commons Attribution 4.0 License , and code samples are licensed under the Apache 2.0 License . For details, see the Google Developers Site Policies . Java is a registered trademark of Oracle and/or its affiliates.

Last updated 2022-06-14 UTC.

Learn Python practically and Get Certified .

Popular Tutorials

Popular examples, reference materials, learn python interactively.

Python Examples

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.

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.

  • Python Program to Check Prime Number
  • Python Program to Add Two Numbers
  • Python Program to Find the Factorial of a Number
  • Python Program to Make a Simple Calculator
  • Python Program to Print Hello world!
  • Python Program to Find the Square Root
  • Python Program to Calculate the Area of a Triangle
  • Python Program to Solve Quadratic Equation
  • Python Program to Swap Two Variables
  • Python Program to Generate a Random Number
  • Python Program to Convert Kilometers to Miles
  • Python Program to Convert Celsius To Fahrenheit
  • Python Program to Check if a Number is Positive, Negative or 0
  • Python Program to Check if a Number is Odd or Even
  • Python Program to Check Leap Year
  • Python Program to Find the Largest Among Three Numbers
  • Python Program to Print all Prime Numbers in an Interval
  • Python Program to Display the multiplication Table
  • Python Program to Print the Fibonacci sequence
  • Python Program to Check Armstrong Number
  • Python Program to Find Armstrong Number in an Interval
  • Python Program to Find the Sum of Natural Numbers
  • Python Program to Display Powers of 2 Using Anonymous Function
  • Python Program to Find Numbers Divisible by Another Number
  • Python Program to Convert Decimal to Binary, Octal and Hexadecimal
  • Python Program to Find ASCII Value of Character
  • Python Program to Find HCF or GCD
  • Python Program to Find LCM
  • Python Program to Find the Factors of a Number
  • Python Program to Shuffle Deck of Cards
  • Python Program to Display Calendar
  • Python Program to Display Fibonacci Sequence Using Recursion
  • Python Program to Find Sum of Natural Numbers Using Recursion
  • Python Program to Find Factorial of Number Using Recursion
  • Python Program to Convert Decimal to Binary Using Recursion
  • Python Program to Add Two Matrices
  • Python Program to Transpose a Matrix
  • Python Program to Multiply Two Matrices
  • Python Program to Check Whether a String is Palindrome or Not
  • Python Program to Remove Punctuations From a String
  • Python Program to Sort Words in Alphabetic Order
  • Python Program to Illustrate Different Set Operations
  • Python Program to Count the Number of Each Vowel
  • Python Program to Merge Mails
  • Python Program to Find the Size (Resolution) of an Image
  • Python Program to Find Hash of File
  • Python Program to Create Pyramid Patterns
  • Python Program to Merge Two Dictionaries
  • Python Program to Safely Create a Nested Directory
  • Python Program to Access Index of a List Using for Loop
  • Python Program to Flatten a Nested List
  • Python Program to Slice Lists
  • Python Program to Iterate Over Dictionaries Using for Loop
  • Python Program to Sort a Dictionary by Value
  • Python Program to Check If a List is Empty
  • Python Program to Catch Multiple Exceptions in One Line
  • Python Program to Copy a File
  • Python Program to Concatenate Two Lists
  • Python Program to Check if a Key is Already Present in a Dictionary
  • Python Program to Split a List Into Evenly Sized Chunks
  • Python Program to Parse a String to a Float or Int
  • Python Program to Print Colored Text to the Terminal
  • Python Program to Convert String to Datetime
  • Python Program to Get the Last Element of the List
  • Python Program to Get a Substring of a String
  • Python Program to Print Output Without a Newline
  • Python Program Read a File Line by Line Into a List
  • Python Program to Randomly Select an Element From the List
  • Python Program to Check If a String Is a Number (Float)
  • Python Program to Count the Occurrence of an Item in a List
  • Python Program to Append to a File
  • Python Program to Delete an Element From a Dictionary
  • Python Program to Create a Long Multiline String
  • Python Program to Extract Extension From the File Name
  • Python Program to Measure the Elapsed Time in Python
  • Python Program to Get the Class Name of an Instance
  • Python Program to Convert Two Lists Into a Dictionary
  • Python Program to Differentiate Between type() and isinstance()
  • Python Program to Trim Whitespace From a String
  • Python Program to Get the File Name From the File Path
  • Python Program to Represent enum
  • Python Program to Return Multiple Values From a Function
  • Python Program to Get Line Count of a File
  • Python Program to Find All File with .txt Extension Present Inside a Directory
  • Python Program to Get File Creation and Modification Date
  • Python Program to Get the Full Path of the Current Working Directory
  • Python Program to Iterate Through Two Lists in Parallel
  • Python Program to Check the File Size
  • Python Program to Reverse a Number
  • Python Program to Compute the Power of a Number
  • Python Program to Count the Number of Digits Present In a Number
  • Python Program to Check If Two Strings are Anagram
  • Python Program to Capitalize the First Character of a String
  • Python Program to Compute all the Permutation of the String
  • Python Program to Create a Countdown Timer
  • Python Program to Count the Number of Occurrence of a Character in String
  • Python Program to Remove Duplicate Element From a List
  • Python Program to Convert Bytes to a String

Notice: While JavaScript is not essential for this website, your interaction with the content will be limited. Please turn JavaScript on for the full experience.

Notice: Your browser is ancient . Please upgrade to a different browser to experience a better web.

  • Chat on IRC
  • Python >>>
  • About >>>
  • Getting Started

Python For Beginners

Welcome! Are you completely new to programming ? If not then we presume you will be looking for information about why and how to get started with Python. Fortunately an experienced programmer in any programming language (whatever it may be) can pick up Python very quickly. It's also easy for beginners to use and learn, so jump in !

Installing Python is generally easy, and nowadays many Linux and UNIX distributions include a recent Python. Even some Windows computers (notably those from HP) now come with Python already installed. If you do need to install Python and aren't confident about the task you can find a few notes on the BeginnersGuide/Download wiki page, but installation is unremarkable on most platforms.

Before getting started, you may want to find out which IDEs and text editors are tailored to make Python editing easy, browse the list of introductory books , or look at code samples that you might find helpful.

There is a list of tutorials suitable for experienced programmers on the BeginnersGuide/Tutorials page. There is also a list of resources in other languages which might be useful if English is not your first language.

The online documentation is your first port of call for definitive information. There is a fairly brief tutorial that gives you basic information about the language and gets you started. You can follow this by looking at the library reference for a full description of Python's many libraries and the language reference for a complete (though somewhat dry) explanation of Python's syntax. If you are looking for common Python recipes and patterns, you can browse the ActiveState Python Cookbook

Looking for Something Specific?

If you want to know whether a particular application, or a library with particular functionality, is available in Python there are a number of possible sources of information. The Python web site provides a Python Package Index (also known as the Cheese Shop , a reference to the Monty Python script of that name). There is also a search page for a number of sources of Python-related information. Failing that, just Google for a phrase including the word ''python'' and you may well get the result you need. If all else fails, ask on the python newsgroup and there's a good chance someone will put you on the right track.

Frequently Asked Questions

If you have a question, it's a good idea to try the FAQ , which answers the most commonly asked questions about Python.

Looking to Help?

If you want to help to develop Python, take a look at the developer area for further information. Please note that you don't have to be an expert programmer to help. The documentation is just as important as the compiler, and still needs plenty of work!

Python Lab Assignments

You can not learn a programming language by only reading the language construct. It also requires programming - writing your own code and studying those of others. Solve these assignments, then study the solutions presented here.

  • Python Basics
  • Interview Questions
  • Python Quiz
  • Popular Packages
  • Python Projects
  • Practice Python
  • AI With Python
  • Learn Python3
  • Python Automation
  • Python Web Dev
  • DSA with Python
  • Python OOPs
  • Dictionaries

Python Operators

Precedence and associativity of operators in python.

  • Python Arithmetic Operators
  • Difference between / vs. // operator in Python
  • Python - Star or Asterisk operator ( * )
  • What does the Double Star operator mean in Python?
  • Division Operators in Python
  • Modulo operator (%) in Python
  • Python Logical Operators
  • Python OR Operator
  • Difference between 'and' and '&' in Python
  • not Operator in Python | Boolean Logic

Ternary Operator in Python

  • Python Bitwise Operators

Python Assignment Operators

Assignment operators in python.

  • Walrus Operator in Python 3.8
  • Increment += and Decrement -= Assignment Operators in Python
  • Merging and Updating Dictionary Operators in Python 3.9
  • New '=' Operator in Python3.8 f-string

Python Relational Operators

  • Comparison Operators in Python
  • Python NOT EQUAL operator
  • Difference between == and is operator in Python
  • Chaining comparison operators in Python
  • Python Membership and Identity Operators
  • Difference between != and is not operator in Python

In Python programming, Operators in general are used to perform operations on values and variables. These are standard symbols used for logical and arithmetic operations. In this article, we will look into different types of Python operators. 

  • OPERATORS: These are the special symbols. Eg- + , * , /, etc.
  • OPERAND: It is the value on which the operator is applied.

Types of Operators in Python

  • Arithmetic Operators
  • Comparison Operators
  • Logical Operators
  • Bitwise Operators
  • Assignment Operators
  • Identity Operators and Membership Operators

Python Operators

Arithmetic Operators in Python

Python Arithmetic operators are used to perform basic mathematical operations like addition, subtraction, multiplication , and division .

In Python 3.x the result of division is a floating-point while in Python 2.x division of 2 integers was an integer. To obtain an integer result in Python 3.x floored (// integer) is used.

Example of Arithmetic Operators in Python

Division operators.

In Python programming language Division Operators allow you to divide two numbers and return a quotient, i.e., the first number or number at the left is divided by the second number or number at the right and returns the quotient. 

There are two types of division operators: 

Float division

  • Floor division

The quotient returned by this operator is always a float number, no matter if two numbers are integers. For example:

Example: The code performs division operations and prints the results. It demonstrates that both integer and floating-point divisions return accurate results. For example, ’10/2′ results in ‘5.0’ , and ‘-10/2’ results in ‘-5.0’ .

Integer division( Floor division)

The quotient returned by this operator is dependent on the argument being passed. If any of the numbers is float, it returns output in float. It is also known as Floor division because, if any number is negative, then the output will be floored. For example:

Example: The code demonstrates integer (floor) division operations using the // in Python operators . It provides results as follows: ’10//3′ equals ‘3’ , ‘-5//2’ equals ‘-3’ , ‘ 5.0//2′ equals ‘2.0’ , and ‘-5.0//2’ equals ‘-3.0’ . Integer division returns the largest integer less than or equal to the division result.

Precedence of Arithmetic Operators in Python

The precedence of Arithmetic Operators in Python is as follows:

  • P – Parentheses
  • E – Exponentiation
  • M – Multiplication (Multiplication and division have the same precedence)
  • D – Division
  • A – Addition (Addition and subtraction have the same precedence)
  • S – Subtraction

The modulus of Python operators helps us extract the last digit/s of a number. For example:

  • x % 10 -> yields the last digit
  • x % 100 -> yield last two digits

Arithmetic Operators With Addition, Subtraction, Multiplication, Modulo and Power

Here is an example showing how different Arithmetic Operators in Python work:

Example: The code performs basic arithmetic operations with the values of ‘a’ and ‘b’ . It adds (‘+’) , subtracts (‘-‘) , multiplies (‘*’) , computes the remainder (‘%’) , and raises a to the power of ‘b (**)’ . The results of these operations are printed.

Note: Refer to Differences between / and // for some interesting facts about these two Python operators.

Comparison of Python Operators

In Python Comparison of Relational operators compares the values. It either returns True or False according to the condition.

= is an assignment operator and == comparison operator.

Precedence of Comparison Operators in Python

In Python, the comparison operators have lower precedence than the arithmetic operators. All the operators within comparison operators have the same precedence order.

Example of Comparison Operators in Python

Let’s see an example of Comparison Operators in Python.

Example: The code compares the values of ‘a’ and ‘b’ using various comparison Python operators and prints the results. It checks if ‘a’ is greater than, less than, equal to, not equal to, greater than, or equal to, and less than or equal to ‘b’ .

Logical Operators in Python

Python Logical operators perform Logical AND , Logical OR , and Logical NOT operations. It is used to combine conditional statements.

Precedence of Logical Operators in Python

The precedence of Logical Operators in Python is as follows:

  • Logical not
  • logical and

Example of Logical Operators in Python

The following code shows how to implement Logical Operators in Python:

Example: The code performs logical operations with Boolean values. It checks if both ‘a’ and ‘b’ are true ( ‘and’ ), if at least one of them is true ( ‘or’ ), and negates the value of ‘a’ using ‘not’ . The results are printed accordingly.

Bitwise Operators in Python

Python Bitwise operators act on bits and perform bit-by-bit operations. These are used to operate on binary numbers.

Precedence of Bitwise Operators in Python

The precedence of Bitwise Operators in Python is as follows:

  • Bitwise NOT
  • Bitwise Shift
  • Bitwise AND
  • Bitwise XOR

Here is an example showing how Bitwise Operators in Python work:

Example: The code demonstrates various bitwise operations with the values of ‘a’ and ‘b’ . It performs bitwise AND (&) , OR (|) , NOT (~) , XOR (^) , right shift (>>) , and left shift (<<) operations and prints the results. These operations manipulate the binary representations of the numbers.

Python Assignment operators are used to assign values to the variables.

Let’s see an example of Assignment Operators in Python.

Example: The code starts with ‘a’ and ‘b’ both having the value 10. It then performs a series of operations: addition, subtraction, multiplication, and a left shift operation on ‘b’ . The results of each operation are printed, showing the impact of these operations on the value of ‘b’ .

Identity Operators in Python

In Python, is and is not are the identity operators both are used to check if two values are located on the same part of the memory. Two variables that are equal do not imply that they are identical. 

Example Identity Operators in Python

Let’s see an example of Identity Operators in Python.

Example: The code uses identity operators to compare variables in Python. It checks if ‘a’ is not the same object as ‘b’ (which is true because they have different values) and if ‘a’ is the same object as ‘c’ (which is true because ‘c’ was assigned the value of ‘a’ ).

Membership Operators in Python

In Python, in and not in are the membership operators that are used to test whether a value or variable is in a sequence.

Examples of Membership Operators in Python

The following code shows how to implement Membership Operators in Python:

Example: The code checks for the presence of values ‘x’ and ‘y’ in the list. It prints whether or not each value is present in the list. ‘x’ is not in the list, and ‘y’ is present, as indicated by the printed messages. The code uses the ‘in’ and ‘not in’ Python operators to perform these checks.

in Python, Ternary operators also known as conditional expressions are operators that evaluate something based on a condition being true or false. It was added to Python in version 2.5. 

It simply allows testing a condition in a single line replacing the multiline if-else making the code compact.

Syntax :   [on_true] if [expression] else [on_false] 

Examples of Ternary Operator in Python

The code assigns values to variables ‘a’ and ‘b’ (10 and 20, respectively). It then uses a conditional assignment to determine the smaller of the two values and assigns it to the variable ‘min’ . Finally, it prints the value of ‘min’ , which is 10 in this case.

In Python, Operator precedence and associativity determine the priorities of the operator.

Operator Precedence in Python

This is used in an expression with more than one operator with different precedence to determine which operation to perform first.

Let’s see an example of how Operator Precedence in Python works:

Example: The code first calculates and prints the value of the expression 10 + 20 * 30 , which is 610. Then, it checks a condition based on the values of the ‘name’ and ‘age’ variables. Since the name is “ Alex” and the condition is satisfied using the or operator, it prints “Hello! Welcome.”

Operator Associativity in Python

If an expression contains two or more operators with the same precedence then Operator Associativity is used to determine. It can either be Left to Right or from Right to Left.

The following code shows how Operator Associativity in Python works:

Example: The code showcases various mathematical operations. It calculates and prints the results of division and multiplication, addition and subtraction, subtraction within parentheses, and exponentiation. The code illustrates different mathematical calculations and their outcomes.

To try your knowledge of Python Operators, you can take out the quiz on Operators in Python . 

Python Operator Exercise Questions

Below are two Exercise Questions on Python Operators. We have covered arithmetic operators and comparison operators in these exercise questions. For more exercises on Python Operators visit the page mentioned below.

Q1. Code to implement basic arithmetic operations on integers

Q2. Code to implement Comparison operations on integers

Explore more Exercises: Practice Exercise on Operators in Python

Please Login to comment...

Similar reads.

  • python-basics
  • Python-Operators

Improve your Coding Skills with Practice

 alt=

What kind of Experience do you want to share?

Beginner Strategy Checklist

Discover the basics of trading. From learning the differences between stock and options, all the way through to complex options strategies, Dr. Jim and E simplify the trading world every step of the way, every weekday!

More like this

tasty live content is created, produced, and provided solely by tastylive, Inc. (“tasty live ”) and is for informational and educational purposes only. It is not, nor is it intended to be, trading or investment advice or a recommendation that any security, futures contract, digital asset, other product, transaction, or investment strategy is suitable for any person. Trading securities, futures products, and digital assets involve risk and may result in a loss greater than the original amount invested. tasty live , through its content, financial programming or otherwise, does not provide investment or financial advice or make investment recommendations. Investment information provided may not be appropriate for all investors and is provided without respect to individual investor financial sophistication, financial situation, investing time horizon or risk tolerance. tasty live is not in the business of transacting securities trades, nor does it direct client commodity accounts or give commodity trading advice tailored to any particular client’s situation or investment objectives. Supporting documentation for any claims (including claims made on behalf of options programs), comparisons, statistics, or other technical data, if applicable, will be supplied upon request. tasty live is not a licensed financial adviser, registered investment adviser, or a registered broker-dealer.  Options, futures, and futures options are not suitable for all investors.  Prior to trading securities, options, futures, or futures options, please read the applicable risk disclosures, including, but not limited to, the Characteristics and Risks of Standardized Options Disclosure and the Futures and Exchange-Traded Options Risk Disclosure found on tastytrade.com/disclosures .

tastytrade, Inc. ("tastytrade”) is a registered broker-dealer and member of FINRA, NFA, and SIPC. tastytrade was previously known as tastyworks, Inc. (“tastyworks”). tastytrade offers self-directed brokerage accounts to its customers. tastytrade does not give financial or trading advice, nor does it make investment recommendations. You alone are responsible for making your investment and trading decisions and for evaluating the merits and risks associated with the use of tastytrade’s systems, services or products. tastytrade is a wholly-owned subsidiary of tastylive, Inc.

tastytrade has entered into a Marketing Agreement with tasty live (“Marketing Agent”) whereby tastytrade pays compensation to Marketing Agent to recommend tastytrade’s brokerage services. The existence of this Marketing Agreement should not be deemed as an endorsement or recommendation of Marketing Agent by tastytrade. tastytrade and Marketing Agent are separate entities with their own products and services. tasty live is the parent company of tastytrade.

tastycrypto is provided solely by tasty Software Solutions, LLC. tasty Software Solutions, LLC is a separate but affiliate company of tastylive, Inc. Neither tasty live nor any of its affiliates are responsible for the products or services provided by tasty Software Solutions, LLC. Cryptocurrency trading is not suitable for all investors due to the number of risks involved. The value of any cryptocurrency, including digital assets pegged to fiat currency, commodities, or any other asset, may go to zero.

© copyright 2013 - 2024 tastylive, Inc. All Rights Reserved.  Applicable portions of the Terms of Use on tastylive.com apply.  Reproduction, adaptation, distribution, public display, exhibition for profit, or storage in any electronic storage media in whole or in part is prohibited under penalty of law, provided that you may download tasty live ’s podcasts as necessary to view for personal use. tasty live was previously known as tastytrade, Inc. tasty live is a trademark/servicemark owned by tastylive, Inc.

Navigation Menu

Search code, repositories, users, issues, pull requests..., provide feedback.

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly.

To see all available qualifiers, see our documentation .

  • Notifications

Here is the inclusion of codes for very beginner biologist in Python.

biopython2023/Basic-python-for-biologist

Folders and files, repository files navigation, basic-python-for-biologist.

  • Jupyter Notebook 100.0%

IMAGES

  1. Python Code for a Simple Calculator Program

    basic python assignments for beginners

  2. Python tutorials for beginners

    basic python assignments for beginners

  3. Python Cheat Sheet For Beginners

    basic python assignments for beginners

  4. Basic Concepts of Python for Beginners

    basic python assignments for beginners

  5. Python practice series for absolute beginners

    basic python assignments for beginners

  6. Python Basics Tutorial For Beginners Codeloop

    basic python assignments for beginners

VIDEO

  1. 1.Python Programming: An Introduction for Beginners

  2. Start here for programming in Python (English university lectures)

  3. introduction to python

  4. Learn to do Python Assignments

  5. Python Basics Tutorial Picking Our Data Set || Machine Learning Journey

  6. Python for Beginners

COMMENTS

  1. Python Basic Exercise for Beginners with Solutions

    This Python essential exercise is to help Python beginners to learn necessary Python skills quickly. Immerse yourself in the practice of Python's foundational concepts, such as loops, control flow, data types, operators, list, strings, input-output, and built-in functions.

  2. Python Practice for Beginners: 15 Hands-On Problems

    Python Practice Problem 1: Average Expenses for Each Semester. John has a list of his monthly expenses from last year: He wants to know his average expenses for each semester. Using a for loop, calculate John's average expenses for the first semester (January to June) and the second semester (July to December).

  3. Welcome to 101 Exercises for Python Fundamentals

    To run a cell of code, click the "play button" icon to the left of the cell or click on the cell and press "Shift+Enter" on your keyboard. This will execute the Python code contained in the cell. Executing a cell that defines a variable is important before executing or authoring a cell that depends on that previously created variable assignment.

  4. Beginner Python Exercises w/ Solutions

    Exercise 1: print () function | (3) : Get your feet wet and have some fun with the universal first step of programming. Exercise 2: Variables | (2) : Practice assigning data to variables with these Python exercises. Exercise 3: Data Types | (4) : Integer (int), string (str) and float are the most basic and fundamental building blocks of data in ...

  5. 10 Python Practice Exercises for Beginners with Solutions

    Exercise 1: User Input and Conditional Statements. Write a program that asks the user for a number then prints the following sentence that number of times: 'I am back to check on my skills!'. If the number is greater than 10, print this sentence instead: 'Python conditions and loops are a piece of cake.'.

  6. Exercises and Solutions

    Beginner Python exercises. Home; Why Practice Python? Why Chilis? Resources for learners; All Exercises. 1: Character Input 2: Odd Or Even 3: List Less Than Ten 4: Divisors 5: List Overlap 6: String Lists 7: List Comprehensions 8: Rock Paper Scissors 9: Guessing Game One 10: List Overlap Comprehensions 11: Check Primality Functions 12: List Ends 13: Fibonacci 14: List Remove Duplicates

  7. How to Use Python: Your First Steps

    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.

  8. Python Basics

    Python Basics. Get a jump-start on your Python career with our tutorials designed for beginners. On this page you'll find fundamental concepts for Python beginners that will help you get started on your journey to learn Python. These tutorials focus on the absolutely essential things you need to know about Python.

  9. 25 Python Projects for Beginners

    25 Python Projects for Beginners - Easy Ideas to Get Started Coding Python. Jessica Wilkins. The best way to learn a new programming language is to build projects with it. I have created a list of 25 beginner friendly project tutorials in Python. My advice for tutorials would be to watch the video, build the project, break it apart and ...

  10. Learn Python Basics

    These actions can range from simple assignments of values to variables to more complex control flow structures and iterations. Understanding different types of statements is essential for writing effective and expressive Python code. Assignment Statements. Assignment statements are the most basic type of statement in Python.

  11. Python Exercises

    We have gathered a variety of Python exercises (with answers) for each Python Chapter. Try to solve an exercise by filling in the missing parts of a code. If you're stuck, hit the "Show Answer" button to see what you've done wrong. Count Your Score. You will get 1 point for each correct answer. Your score and total score will always be displayed.

  12. Python Basics

    Section 3. Control flow. if…else statement - learn how to execute a code block based on a condition.; Ternary operator - introduce you to the Python ternary operator that makes your code more concise.; for loop with range() - show you how to execute a code block for a fixed number of times by using the for loop with range() function. while- show you how to execute a code block as ...

  13. Python Exercise with Practice Questions and Solutions

    The best way to learn is by practising it more and more. The best thing about this Python practice exercise is that it helps you learn Python using sets of detailed programming questions from basic to advanced. It covers questions on core Python concepts as well as applications of Python in various domains.

  14. Basic Python Exercises

    Basic Python Exercises. There are 3 exercises that go with the first sections of Google's Python class. They are located in the "basic" directory within the google-python-exercises directory. Download the google-python-exercises.zip if you have not already (see the Set-Up page for details). These exercise files are located under the basic ...

  15. Python Examples

    All Examples. Files. Python Program to Print Hello world! Python Program to Add Two Numbers. Python Program to Find the Square Root. Python Program to Calculate the Area of a Triangle. Python Program to Solve Quadratic Equation. Python Program to Swap Two Variables. Python Program to Generate a Random Number.

  16. Python For Beginners (Full Course)

    Learn the basics of Python coding in this 12 part series. All the videos are free, and will cover everything you need to know to get started with Python. Thi...

  17. 60+ Python Project Ideas

    Rock, Paper, Scissors — Learn Python with a simple-but-fun game that everybody knows. Build a Text Adventure Game — This is a classic Python beginner project (it also pops up in this book) that'll teach you many basic game setup concepts that are useful for more advanced games. Guessing Game — This is another beginner-level project that ...

  18. Python For Beginners

    Learning. Before getting started, you may want to find out which IDEs and text editors are tailored to make Python editing easy, browse the list of introductory books, or look at code samples that you might find helpful.. There is a list of tutorials suitable for experienced programmers on the BeginnersGuide/Tutorials page. There is also a list of resources in other languages which might be ...

  19. 2,500+ Python Practice Challenges // Edabit

    Practice Python coding with fun, bite-sized exercises. Earn XP, unlock achievements and level up. It's like Duolingo for learning to code. ... (230, 10) 2300 circuit_power(110, 3) 330 circuit_power(480, 20) 9600 Notes Requires basic calculation of electrical circuits (see Resources for info). math. numbers. Very Easy. Add to bookmarks. Add to ...

  20. Python Exercises, Practice, Solution

    Python is a widely used high-level, general-purpose, interpreted, dynamic programming language. Its design philosophy emphasizes code readability, and its syntax allows programmers to express concepts in fewer lines of code than possible in languages such as C++ or Java. Python supports multiple programming paradigms, including object-oriented ...

  21. Python Lab Assignments

    python programs with output for class 12 and 11 students. Simple Assignements are for beginners starting from basics hello world program to game development using class and object concepts. A list of assignment solutions with source code are provided to learn concept by examples in an easy way.

  22. Learn Python for Data Science : Beginner to Advance

    Designed for beginners and seasoned programmers alike, this course serves as your gateway to mastering Python's capabilities in the realm of AI and ML. Through a carefully crafted curriculum, you'll first establish a solid foundation in Python programming, mastering its syntax, data structures, and control flow.

  23. Python Operators

    Assignment Operators in Python. Let's see an example of Assignment Operators in Python. Example: The code starts with 'a' and 'b' both having the value 10. It then performs a series of operations: addition, subtraction, multiplication, and a left shift operation on 'b'.

  24. Python and Pandas for Data Engineering

    There are 4 modules in this course. In this first course of the Python, Bash and SQL Essentials for Data Engineering Specialization, you will learn how to set up a version-controlled Python working environment which can utilize third party libraries. You will learn to use Python and the powerful Pandas library for data analysis and manipulation.

  25. Calculator to perform 10 basic operations in python for beginners

    This is the basic code in python which performs basic 10 calculations. So, beginners should give it a try for their practice purposes. This calculator performs these basic 10 operations:

  26. Python IDE Debugging Tools: Beginner's Guide

    An interactive console within a Python IDE is a powerful ally for a beginner. It allows you to execute Python code line by line or run small snippets independently of your main program.

  27. Beginner Strategy Checklist

    Beginner Strategy Checklist. May 15, 2024. Discover the basics of trading. From learning the differences between stock and options, all the way through to complex options strategies, Dr. Jim and E simplify the trading world every step of the way, every weekday!

  28. GitHub

    You signed in with another tab or window. Reload to refresh your session. You signed out in another tab or window. Reload to refresh your session. You switched accounts on another tab or window.