• Python Home
  • ▼Python Exercises
  • Exercises Home
  • ▼Python Basic
  • Basic - Part-I
  • Basic - Part-II
  • Python Programming Puzzles
  • Mastering Python
  • ▼Python Advanced
  • Python Advanced Exercises
  • ▼Python Control Flow
  • Condition Statements and Loops
  • ▼Python Data Types
  • List Advanced
  • Collections
  • ▼Python Class
  • ▼Python Concepts
  • Python Unit test
  • Python Exception Handling
  • Python Object-Oriented Programming
  • ▼Functional Programming
  • Filter Function
  • ▼Date and Time
  • Pendulum Module
  • ▼File Handling
  • CSV Read, Write
  • ▼Regular Expressions
  • Regular Expression
  • ▼Data Structures and Algorithms
  • Search and Sorting
  • Linked List
  • Binary Search Tree
  • Heap queue algorithm
  • ▼Advanced Python Data Types
  • Boolean Data Type
  • None Data Type
  • Bytes and Byte Arrays
  • Memory Views exercises
  • Frozenset Views exercises
  • NamedTuple exercises
  • OrderedDict exercises
  • Counter exercises
  • Ellipsis exercises
  • ▼Concurrency and Threading
  • Asynchronous
  • ▼Python Modules
  • Operating System Services
  • SQLite Database
  • ▼Miscellaneous
  • Cyber Security
  • Generators Yield
  • ▼Python GUI Tkinter, PyQt
  • Tkinter Home
  • Tkinter Basic
  • Tkinter Layout Management
  • Tkinter Widgets
  • Tkinter Dialogs and File Handling
  • Tkinter Canvas and Graphics
  • Tkinter Events and Event Handling
  • Tkinter Custom Widgets and Themes
  • Tkinter File Operations and Integration
  • PyQt Widgets
  • PyQt Connecting Signals to Slots
  • PyQt Event Handling
  • ▼Python NumPy
  • Python NumPy Home
  • ▼Python urllib3
  • Python urllib3 Home
  • ▼Python Metaprogramming
  • Python Metaprogramming Home
  • ▼Python GeoPy
  • Python GeoPy Home
  • ▼BeautifulSoup
  • BeautifulSoup Home
  • ▼Arrow Module
  • ▼Python Pandas
  • Python Pandas Home
  • ▼Pandas and NumPy Exercises
  • Pandas and NumPy Home
  • ▼Python Machine Learning
  • Machine Learning Home
  • TensorFlow Basic
  • ▼Python Web Scraping
  • Web Scraping
  • ▼Python Challenges
  • Challenges-1
  • ▼Python Mini Project
  • Python Projects
  • ▼Python Natural Language Toolkit
  • Python NLTK
  • ▼Python Project
  • Novel Coronavirus (COVID-19)
  • ..More to come..
  • Python Exercises, Practice, Solution

What is Python language?

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, imperative and functional programming or procedural styles. It features a dynamic type system and automatic memory management and has a large and comprehensive standard library

Python Exercises Practice Solutions

The best way we learn anything is by practice and exercise questions. We have started this section for those (beginner to intermediate) who are familiar with Python.

Hope, these exercises help you to improve your Python coding skills. Currently, following sections are available, we are working hard to add more exercises .... Happy Coding!

You may read our Python tutorial before solving the following exercises.

Latest Articles : Python Interview Questions and Answers      Python PyQt

List of Python Exercises :

  • Python Basic (Part -I) [ 150 Exercises with Solution ]
  • Python Basic (Part -II) [ 150 Exercises with Solution ]
  • Python Programming Puzzles [ 100 Exercises with Solution ]
  • Mastering Python [ 150 Exercises with Solution ]
  • Python Advanced [ 15 Exercises with Solution ]
  • Python Conditional statements and loops [ 44 Exercises with Solution]
  • Recursion [ 11 Exercises with Solution ]
  • Python Data Types - String [ 113 Exercises with Solution ]
  • Python JSON [ 9 Exercises with Solution ]
  • Python Data Types - List [ 281 Exercises with Solution ]
  • Python Data Types - List Advanced [ 15 Exercises with Solution ]
  • Python Data Types - Dictionary [ 80 Exercises with Solution ]
  • Python Data Types - Tuple [ 33 Exercises with Solution ]
  • Python Data Types - Sets [ 30 Exercises with Solution ]
  • Python Data Types - Collections [ 36 Exercises with Solution ]
  • Python Array [ 24 Exercises with Solution ]
  • Python Enum [ 5 Exercises with Solution ]
  • Python Class [ 28 Exercises with Solution ]
  • Python Unit test [ 10 Exercises with Solution ]
  • Python Exception Handling [ 10 exercises with solution ]
  • Python Object-Oriented Programming [ 11 Exercises with Solution ]
  • Python Decorator [ 12 Exercises with Solution ]
  • Python functions [ 21 Exercises with Solution ]
  • Python Lambda [ 52 Exercises with Solution ]
  • Python Map [ 17 Exercises with Solution ]
  • Python Itertools [ 44 exercises with solution ]
  • Python - Filter Function [ 11 Exercises with Solution ]
  • Python Date Time [ 63 Exercises with Solution ]
  • Python Pendulum (DATETIMES made easy) Module [34 Exercises with Solution]
  • Python File Input Output [ 21 Exercises with Solution ]
  • Python CSV File Reading and Writing [ 11 exercises with solution ]
  • Python Regular Expression [ 58 Exercises with Solution ]
  • Search and Sorting [ 39 Exercises with Solution ]
  • Linked List [ 14 Exercises with Solution ]
  • Binary Search Tree [ 6 Exercises with Solution ]
  • Python heap queue algorithm [ 29 exercises with solution ]
  • Python Bisect [ 9 Exercises with Solution ]
  • Python Boolean Data Type [ 10 Exercises with Solution ]
  • Python None Data Type [ 10 Exercises with Solution ]
  • Python Bytes and Byte Arrays Data Type [ 10 Exercises with Solution ]
  • Python Memory Views Data Type [ 10 Exercises with Solution ]
  • Python frozenset Views [ 10 Exercises with Solution ]
  • Python NamedTuple [ 9 Exercises with Solution ]
  • Python OrderedDict [ 10 Exercises with Solution ]
  • Python Counter [ 10 Exercises with Solution ]
  • Python Ellipsis (...) [ 9 Exercises with Solution ]
  • Python Multi-threading and Concurrency [ 7 exercises with solution ]
  • Python Asynchronous [ 8 Exercises with Solution ]
  • Python built-in Modules [ 31 Exercises with Solution ]
  • Python Operating System Services [ 18 Exercises with Solution ]
  • Python Math [ 94 Exercises with Solution ]
  • Python Requests [ 9 exercises with solution ]
  • Python SQLite Database [ 13 Exercises with Solution ]
  • Python SQLAlchemy [ 14 exercises with solution ]
  • Python - PPrint [ 6 Exercises with Solution ]
  • Python - Cyber Security [ 10 Exercises with Solution ]
  • Python Generators Yield [ 17 exercises with solution ]
  • More to come

Python GUI Tkinter, PyQt

  • Python Tkinter Home
  • Python Tkinter Basic [ 16 Exercises with Solution ]
  • Python Tkinter layout management [ 11 Exercises with Solution ]
  • Python Tkinter widgets [ 22 Exercises with Solution ]
  • Python Tkinter Dialogs and File Handling [ 13 Exercises with Solution ]
  • Python Tkinter Canvas and Graphics [ 14 Exercises with Solution ]
  • Python Tkinter Events and Event Handling [ 13 Exercises with Solution ]
  • Python Tkinter Customs Widgets and Themes [ 12 Exercises with Solution ]
  • Python Tkinter - File Operations and Integration [12 exercises with solution]
  • Python PyQt Basic [10 exercises with solution]
  • Python PyQt Widgets[12 exercises with solution]
  • Python PyQt Connecting Signals to Slots [15 exercises with solution]
  • Python PyQt Event Handling [10 exercises with solution]

Python Challenges :

  • Python Challenges: Part -1 [ 1- 64 ]

Python Projects :

  • Python Numbers : [ 11 Mini Projects with solution ]
  • Python Web Programming: [ 12 Mini Projects with solution ]
  • 100 Python Projects for Beginners with solution.
  • Python Projects: Novel Coronavirus (COVID-19) [ 14 Exercises with Solution ]

Learn Python packages using Exercises, Practice, Solution and explanation

Python urllib3 :

  • Python urllib3 [ 26 exercises with solution ]

Python Metaprogramming :

  • Python Metaprogramming [ 12 exercises with solution ]

Python GeoPy Package :

  • Python GeoPy Package [ 7 exercises with solution ]

Python BeautifulSoup :

  • Python BeautifulSoup [ 36 exercises with solution ]

Python Arrow Module :

  • Python Arrow Module [ 27 exercises with solution ]

Python Web Scraping :

  • Python Web Scraping [ 27 Exercises with solution ]

Python Natural Language Toolkit :

  • Python NLTK [ 22 Exercises with solution ]

Python NumPy :

  • Mastering NumPy [ 100 Exercises with Solutions ]
  • Python NumPy Basic [ 59 Exercises with Solution ]
  • Python NumPy arrays [ 205 Exercises with Solution ]
  • Python NumPy Linear Algebra [ 19 Exercises with Solution ]
  • Python NumPy Random [ 17 Exercises with Solution ]
  • Python NumPy Sorting and Searching [ 9 Exercises with Solution ]
  • Python NumPy Mathematics [ 41 Exercises with Solution ]
  • Python NumPy Statistics [ 14 Exercises with Solution ]
  • Python NumPy DateTime [ 7 Exercises with Solution ]
  • Python NumPy String [ 22 Exercises with Solution ]
  • NumPy Broadcasting [ 20 exercises with solution ]
  • NumPy Memory Layout [ 19 exercises with solution ]
  • NumPy Performance Optimization [ 20 exercises with solution ]
  • NumPy Interoperability [ 20 exercises with solution ]
  • NumPy I/O Operations [ 20 exercises with solution ]
  • NumPy Advanced Indexing [ 20 exercises with solution ]
  • NumPy Universal Functions [ 20 exercises with solution ]
  • NumPy Masked Arrays [ 20 exercises with solution ]
  • NumPy Structured Arrays [ 20 exercises with solution ]
  • NumPy Integration with SciPy [ 19 exercises with solution ]
  • Advanced NumPy [ 33 exercises with solution ]

Python Pandas :

  • Pandas Data Series [ 40 exercises with solution ]
  • Pandas DataFrame [ 81 exercises with solution ]
  • Pandas Index [ 26 exercises with solution ]
  • Pandas String and Regular Expression [ 41 exercises with solution ]
  • Pandas Joining and merging DataFrame [ 15 exercises with solution ]
  • Pandas Grouping and Aggregating [ 32 exercises with solution ]
  • Pandas Time Series [ 32 exercises with solution ]
  • Pandas Filter [ 27 exercises with solution ]
  • Pandas GroupBy [ 32 exercises with solution ]
  • Pandas Handling Missing Values [ 20 exercises with solution ]
  • Pandas Style [ 15 exercises with solution ]
  • Pandas Excel Data Analysis [ 25 exercises with solution ]
  • Pandas Pivot Table [ 32 exercises with solution ]
  • Pandas Datetime [ 25 exercises with solution ]
  • Pandas Plotting [ 19 exercises with solution ]
  • Pandas Performance Optimization [ 20 exercises with solution ]
  • Pandas Advanced Indexing and Slicing [ 15 exercises with solution ]
  • Pandas SQL database Queries [ 24 exercises with solution ]
  • Pandas Resampling and Frequency Conversion [ 15 exercises with solution ]
  • Pandas Advanced Grouping and Aggregation [ 15 exercises with solution ]
  • Pandas IMDb Movies Queries [ 17 exercises with solution ]
  • Mastering NumPy: 100 Exercises with solutions for Python numerical computing
  • Pandas Practice Set-1 [ 65 exercises with solution ]

Pandas and NumPy Exercises :

  • Pandas and NumPy for Data Analysis [ 37 Exercises ]

Python Machine Learning :

  • Python Machine learning Iris flower data set [38 exercises with solution]

Note : Download Python from https://www.python.org/ftp/python/3.2/ and install in your system to execute the Python programs. You can read our Python Installation on Fedora Linux and Windows 7, if you are unfamiliar to Python installation. You may accomplish the same task (solution of the exercises) in various ways, therefore the ways described here are not the only ways to do stuff. Rather, it would be great, if this helps you anyway to choose your own methods.

List of Exercises with Solutions :

  • HTML CSS Exercises, Practice, Solution
  • JavaScript Exercises, Practice, Solution
  • jQuery Exercises, Practice, Solution
  • jQuery-UI Exercises, Practice, Solution
  • CoffeeScript Exercises, Practice, Solution
  • Twitter Bootstrap Exercises, Practice, Solution
  • C Programming Exercises, Practice, Solution
  • C# Sharp Programming Exercises, Practice, Solution
  • PHP Exercises, Practice, Solution
  • R Programming Exercises, Practice, Solution
  • Java Exercises, Practice, Solution
  • SQL Exercises, Practice, Solution
  • MySQL Exercises, Practice, Solution
  • PostgreSQL Exercises, Practice, Solution
  • SQLite Exercises, Practice, Solution
  • MongoDB Exercises, Practice, Solution

More to Come !

Do not submit any solution of the above exercises at here, if you want to contribute go to the appropriate exercise page.

[ Want to contribute to Python exercises? Send your code (attached with a .zip file) to us at w3resource[at]yahoo[dot]com. Please avoid copyrighted materials.]

Test your Python skills with w3resource's quiz

Follow us on Facebook and Twitter for latest update.

  • Weekly Trends and Language Statistics
  • Subscription

Python Practice: 93 Unique Online Coding Exercises

Whether you're just starting your learning journey or looking to brush up before a job interview, getting the right kind of Python practice can make a big difference.

Research shows that hands-on practice is the most effective way to learn, * and luckily there are so many different ways to practice that you're bound to find one that works best for you.

In this post, we'll share 93 ways to practice Python online by writing actual code, broken down into different practice methods.

Table of Contents

Core python programming (great for beginners), intermediate python programming, data handling and manipulation with numpy, data handling and manipulation with pandas, data analysis, complexity and algorithms, python introduction (great for beginners), data analysis and visualization, data cleaning.

  • Machine Learning

AI and Deep Learning

Probability and statistics, beginner projects, data analysis projects, data engineering projects, machine learning and ai projects, core python concepts (great for beginners), intermediate techniques, data analysis and data science, frequently asked questions, where can i practice python programming.

  • How can I practice Python programming?

Can I learn Python in 30 days?

Can i practice python on mobile, how quickly can i learn python, ai is advancing so quickly - should i still learn python, practice with free python coding exercises.

Exercises are a great way to practice a specific topic with targeted efficiency. For example, do you have an upcoming job interview where you know you'll be asked about Python dictionaries? Completing exercises about dictionaries will help refresh your skills and ensure you can confidently speak to this Pythonic datatype.

  • Basic Mathematical Operators (free) — Use Python to perform calculations and printing results to the screen.
  • Variables and data types (free) — Work with variables and doing calculations with variables.
  • Lists and loops (free) — Practice using Python lists and for loops.
  • Dictionaries 1 (free) — Use dictionaries in Python.
  • Dictionaries 2 (free) — More practice with dictionaries and frequency tables.
  • Lists (free) — Practice using lists in Python.
  • Conditional statements (if-else) — Use conditional statements in Python.
  • Sets — Practice using sets in Python.
  • Python functions — Define and call functions.
  • Intermediate Python functions — Practice more advanced usage of functions like returning multiple values.
  • Object oriented programming (OOP) — Define classes, methods, and attributes.
  • NumPy index selection (free) — Select values from ndarrays.
  • NumPy creating ndarrays — Create ndarrays with specific values and shapes.
  • NumPy ndarray methods — Use ndarray methods to perform calculations.
  • NumPy broadcasting — Work with ndarrays with different shapes and using broadcasting to create ndarrays.
  • NumPy boolean masks — Select data from ndarrays use boolean masks
  • NumPy datatypes — Work with NumPy datatypes
  • NumPy sorting — Practice sorting ndarrays
  • NumPy stacking and splitting — Stack and split ndarrays
  • Pandas series (free) — Use and build pandas series.
  • Creating and manipulating dataframes — Create and manipulate pandas dataframes.
  • Selecting data with Pandas — Select data from dataframes.
  • Loading and exploring data — Load data into dataframes and explore it.
  • Pandas boolean masks — Use boolean masks to select data from dataframes.
  • Pandas Data Cleaning — Clean data in a dataframe.
  • Cleaning and preparing data (free) — Write functions to remove incorrect characters and fill missing values.
  • Data analysis basics — Manipulate data from CSV files using Python dictionaries and functions.
  • Working with dates and times — Practice with the datetime module in Python.
  • Time complexity of algorithms (free) — Identify the type of time complexity of Python functions.
  • Constant time complexity — Find the constant time complexity of functions.
  • Logarithmic complexity — Practice finding the logarithmic time complexity of functions.
  • Sorting algorithms — Create and work with sorting algorithms in Python.
  • Space complexity — Practice space complexity by writing Python functions.

Explore our full library of Python practice problems to continue improving your skills.

Practice with Online Python Courses

If you're looking for more structure, then practicing with Python courses online may resonate with you. Courses guide you through a topic, so if you want to gain a new skill or you're rusty on an old one, completing a course is an excellent way to go.

Throughout these courses, you'll be given questions and assignments to test your skills. Additionally, some of these courses contain a guided project that allows you to apply everything you've learned.

See below for some recommended courses.

  • Introduction to Python — Write code using Python syntax; work with different types of data; and perform basic Python operations such as working with variables, processing numerical and text data, and manipulating lists.
  • Basic Operators and Data Structures in Python — Learn the fundamentals of Python for loops, dictionaries, and conditional logic (if-else).
  • Python Functions and Jupyter Notebook — Write Python functions, build functions that employ multiple return statements and return multiple variables, and install and use Jupyter Notebook.
  • Python for Data Science: Intermediate — Manipulate text, clean messy data, work with object-oriented programming concepts, and use dates and times in Python.
  • Pandas and NumPy Fundamentals — Use NumPy and pandas for data exploration, preparation, and analysis.
  • Data Visualization Fundamentals — Balance graph creation and statistics in your visualizations using tools such as Matplotlib and Seaborn.
  • Storytelling Data Visualization and Information Design — Use information design and data visualization to tell compelling stories.
  • Data Cleaning and Analysis — Manipulate, combine, transform, and merge data; manipulate strings; and work with missing values in Python.
  • Data Cleaning in Python: Advanced — Clean and manipulate text data using basic and advanced regular expressions, how to resolve missing data, and how to employ lambda functions and list comprehension with pandas.
  • Data Cleaning Project Walkthrough — Combine multiple datasets and prepare them for analysis.
  • Intro to Supervised Machine Learning — Build a supervised machine learning model in Python, and train and improve it for better performance and accuracy.
  • Intro to Unsupervised Machine Learning — Learn about unsupervised machine learning models in Python, when to apply them, and what differentiates them from supervised machine learning models.
  • Linear Regression Modeling — Build, evaluate, and interpret the results of a linear regression model, as well as using linear regression models for inference and prediction.
  • Gradient Descent Modeling — Learn the fundamentals of gradient descent and how to implement this algorithm in Python.
  • Logistic Regression Modeling — Build and evaluate logistic regression models, both from scratch and using scikit-learn.
  • Decision Tree and Random Forest Modeling — Learn the foundations of Decision Trees including identifying the key components of trees, interpreting them, classifying new observations using decision trees and calculating optimal thresholds for both classification and regression trees.
  • Optimizing Machine Learning Models — Explore the most common methods and techniques that will enable you to optimize your machine learning models for better efficiency.
  • APIs for AI Applications — Use Python for retrieving, analyzing, and manipulating real-world data from various sources including the World Development Indicators database.
  • Prompting Large Language Models (LLMs) — Create an AI-powered chatbot using Python, that incorporates key concepts like prompt engineering, managing conversation histories, and efficiently regulating token usage within an AI framework.
  • Intro to Deep Learning in Tensorflow — Learn the fundamentals of deep learning, as well as how to build, train, and evaluate models using the TensorFlow framework.
  • Introduction to Statistics in Python — Work with techniques for sampling data, concepts such as discrete variables and random variables, and the different types of charts and graphs you might use to visualize frequency distributions.
  • Intermediate Statistics in Python — Summarize distributions using mean, median, and mode. You’ll also learn to measure variability using variance or standard deviation and how to locate and compare values using z-scores.
  • Introduction to Probability in Python — Estimate probabilities, work with the addition and multiplication rules, and define permutations and combinations.
  • Introduction to Conditional Probability in Python — Assign probabilities to events based on certain conditions, evaluate whether they are in a relationship of statistical independence or not, and on prior knowledge by using Bayes’s theorem.
  • Hypothesis Testing in Python — Learn advanced statistical concepts like significance testing and multi-category chi-square testing,

These courses are a great way to practice Python online, and they're all free to start. If you're looking for more courses, you can find them on Dataquest's course page .

Practice with Python Projects

One of the most effective ways to practice Python online is with projects. When I was learning Python, it was easy to forget newly acquired skills. When I discovered that I could do projects to practice my newfound knowledge, it helped me remember new syntax. Additionally, I built a great portfolio of work to show potential employers.

Here are a few projects you can use to start practicing right now.

  • Profitable App Profiles for the App Store and Google Play Markets (free) — Assume the role of a data analyst at a company that builds apps for Android and iOS. Since the company’s revenue depends on in-app ads, your task is analyzing historical data from app markets to determine which apps attract the most users.
  • Learn and Install Jupyter Notebook (free) — Run Python code in a Jupyter Notebook and learn how to install Jupyter locally.
  • Build a Word Guessing Game (free) — Have some fun, and create a functional and interactive word-guessing game using Python.
  • Build a Garden Simulator Text Based Game (free) — Create an interactive text-based “Garden Simulator” using object-oriented programming, error handling, and randomness.
  • Build a Food Ordering App — Create a functional and interactive food ordering application using Python.
  • Investigating Fandango Movie Ratings (free) — Step into the role of a data journalist to analyze movie ratings data and determine if there’s evidence of bias in Fandango’s rating system.
  • Exploring Hacker News Posts (free) — Analyze a dataset from Hacker News and apply your Python skills in string handling, object-oriented programming, and data management to uncover trends in user submissions.
  • Exploring eBay Car Sales Data — Use Python to work with a scraped dataset of used cars from eBay Kleinanzeigen, a classifieds section of the German eBay website.
  • Finding Heavy Traffic Indicators on I-94 — Explore how using the pandas plotting functionality along with the Jupyter Notebook interface allows us to explore data quickly using visualizations.
  • Storytelling Data Visualization on Exchange Rates — Quickly create multiple subsetted plots using one or more conditions.
  • Clean and Analyze Employee Exit Surveys — Work with exit surveys from employees of the Department of Education in Queensland, Australia. Play the role of a data analyst and pretend the stakeholders want answers to important data questions.
  • Analyzing NYC High School Data — Discover the SAT performance of different demographics using scatter plots and maps.
  • Building Fast Queries on a CSV (free) — Act as a Python developer to build an inventory system for a laptop store. You’ll apply efficient data structures and algorithms to enable fast queries.
  • Analyzing Wikipedia Pages (free) — Process over 54 MB of Wikipedia articles to find specific text matches. Using Python and MapReduce, you’ll build a parallel solution to search the dataset and return match details efficiently.
  • Building a database for crime reports — Use PostgreSQL to build a database with proper schemas, tables, and user roles to store and manage crime report data efficiently.
  • Predicting Heart Disease (free) — Act as a data scientist at a healthcare solutions company to build a model that predicts a patient’s risk of developing heart disease based on their medical data.
  • Predicting Insurance Costs — Use linear regession modeling to predict insurance costs.
  • Developing a Dynamic AI Chatbot — Create an AI chatbot that can take on different personas and keep track of conversation history.

If these didn't spark your interest, here are plenty of other online Python projects you can try.

Practice with Online Python Tutorials

If online practice exercises, courses, and projects don't appeal to you, here are a few blog-style tutorials to help you learn Python. I like to use this type of resource when I'm on my phone to get some productive reading done, even when I can't code on my computer!

  • Python strings — See how to declare the string data type, the relationship between the string data type and the ASCII table, the properties of the string data type, and some important string methods and operations.
  • Python dictionaries — Learn how to create a Python dictionary, how to use its methods, and dictionary comprehension.
  • Python data structures — Read about what data structures exist in Python, when to apply them, and their pros and cons.
  • Python classes — Learn how to create and work with Python classes. See what Python classes are, why we use them, what types of classes exist, how to define a class in Python and declare/adjust class objects,
  • Python lists — Read how to define, create, and slice lists, as well as how to add/remove items and use a for loop to iterate over a list.
  • If statements — Use conditional logic with if, elif, and else to streamline your code's efficiency.
  • Python datetime — Learn the uses of the datetime module, extract dates, and work with timestamps.
  • Python ternary — Understand what a Python ternary operator is and when it's useful.
  • Python subprocess — See how to use the subprocess module in Python to run different subprocesses during the course of a regular python script.
  • Python math module — Read about the common constants and functions implemented in the math module — and how to use them.
  • Read files in Python — Learn how to open files, use the with context manager, read text, CSV, and JSON files, and understand different file modes.
  • Lambda functions — Define lambda functions in Python and explore the advantages and limitations of employing them.
  • Reset index in pandas — Discusses the reset_index() pandas method, why we may need to reset the index of a DataFrame in pandas, and how we can apply and tune this method.
  • GroupBy in pandas — Explore how to create a GroupBy object in pandas library of Python and how this object works.
  • Getting Started with APIs — Understand how to retrieve data for AI and data science projects using APIs (Application Programming Interfaces).
  • Introduction to Keras — Learn how to install and start using Keras; the Sequential API; and the steps for building, compiling, and training a model..
  • Implement Support Vector Machines (SVMs) — Read about support vector machines, one of the most popular classification algorithms. Learn how to implement SVMs for a classification task in Python.

The web is also full of thousands of other beginner Python tutorials. As long as you've got a solid foundation in the Python basics, you can find great practice through many of them.

Dataquest.io has dozens of free interactive practice questions, as well as free interactive lessons, project ideas and walkthroughs, tutorials, and more.

HackerRank is a great site for practice that’s also interactive.

CodingGame is a fun platform for practice that supports Python.

Edabit has Python challenges that can be good for practicing or self-testing.

You can also practice Python using all of the interactive lessons listed above

How can I practice Python at home?

Install Python on your machine. You can download it directly here , or download a program like Anaconda Individual Edition that makes the process easier. Or you can find an interactive online platform like Dataquest and write code in your browser without installing anything.

Find a good Python project or some practice problems to work on.

Make detailed plans. Scheduling your practice sessions will make you more likely to follow through.

Join an online community. It's always great to get help from a real person. Reddit has great Python communities, and Dataquest's community is great if you're learning Python data skills.

In 30 days, you can definitely learn enough Python to be able to build some cool things. You won't be able to master Python that quickly, but you could learn to complete a specific project or do things like automate some aspects of your job.

Read more about how long it takes to learn Python .

Yes, there are many apps that allow you to practice Python on both iOS and Android. However, this shouldn't be your primary form of practice if you aspire to use Python in your career— it's good to practice installing and working with Python on desktops and laptops since that's how most professional programming work is done.

You can learn the fundamentals of Python in a weekend. If you're diligent, you can learn enough to complete small projects and genuinely impact your work within a month or so. Mastering Python takes much longer, but you don't need to become a master to get things done!

Absolutely, Python remains essential in the AI field. It's foundational for developing AI technologies and continuously updated to integrate with the latest AI advancements. Python libraries like TensorFlow and Keras facilitate efficient building and training of complex AI models. Learning Python also ensures you understand the underlying mechanisms of AI tools, making you a more proficient developer.

More learning resources

Python list tutorial: lists, loops, and more, how to use python data classes in 2023 (a beginner’s guide).

Learn data skills 10x faster

Headshot

Join 1M+ learners

Enroll for free

  • Data Analyst (Python)
  • Gen AI (Python)
  • Business Analyst (Power BI)
  • Business Analyst (Tableau)
  • Data Analyst (R)

assignment questions in python

Practice Python

follow us in feedly

Beginner Python exercises

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

All Exercises

assignment questions in python

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

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.

Test your Python skills with exercises from all categories:

Get Started

Variable names, multiple variable values, output variable, global variable, slicing strings, modify strings, concatenate strings, format strings, access lists, change lists, add list items, remove list items, list comprehension, access tuples, update tuples, unpack tuples, loop tuples, join tuples, access sets, add set items, remove set items, dictionaries, access dictionaries, change dictionaries, add dictionary items, remove dictionary items, loop dictionaries, copy dictionaries, nested dictionaries, while loops, inheritance, polymorphism, string formatting, write to file, remove file, log in to track your progress.

If you haven't already, sign up to become a W3Schooler, and get points for every exercise you complete.

As a logged on W3Schools user you will have access to many features like having your own web page , track your learning progress , receive personal guided paths , and more .

The Exercise

The exercises are a mix of "multiple choice" and "fill in the blanks" questions. There are between 3 and 9 questions in each catergory. The answer can be found in the corresponding tutorial chapter. If you're stuck, or answer wrong, you can try again or hit the "Show Answer" button to see the correct answer.

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.

CS-IP-Learning-Hub

CS-IP-Learning-Hub

Important Questions and Notes

70+ Python if else Statement Important Practice Questions

assignment questions in python

Table of Content

Python if else statement practice – test 1.

  • Python if else Statement Practice – Test 2
  • Python if else Statement Practice – Test 3
  • Python if else Statement Practice – Test 4
  • Python if else Statement Practice – Test 5
  • Python if else Statement Practice – Test 6
  • Python if else Statement Practice – Test 7

Python if else Statement Pract ice Test 2

assignment questions in python

Python if else Statement Practice Test 3

Q1. Write a program to check whether a number entered is three digit number or not.

Q2. Write a program to check whether a person is eligible for voting or not.(voting age >=18)

Q3. Write a program to check whether a person is senior citizen or not.

Q4. Write a program to find the lowest number out of two numbers excepted from user.

Q5. Write a program to find the largest number out of two numbers excepted from user.

Q6. Write a program to check whether a number (accepted from user) is positive or negative.

Q7. Write a program to check whether a number is even or odd.

Q8. Write a program to display the spell of a digit accepted from user (like user input 0 and display ZERO and so on)

Q8. Write a program to whether a number (accepted from user) is divisible by 2 and 3 both.

Q9. Write a program to find the largest number out of three numbers excepted from user.

Python if else Statement Practice Test 4

Q1. Accept the temperature in degree Celsius of water and check whether it is boiling or not (boiling point of water in 100  o C.

Q2. _________ is a graphical representation of steps (algorithm/flow chart)

Q3. Python has _________ statement as empty statement (Pass/Fail)

Q4. In python, a block is a group of _______statement having same indentation level.(consecutive/alternate)

Q5. Out of “elif” and “else if”, which is the correct statement in python?

Q6. Accept the age of 4 people and display the youngest one ?

Q7. What is the purpose of else in if elif ladder?

Q8. Accept the age of 4 people and display the oldest one.

Q9. Write a program to check whether a number  is prime or not.

Q10. Write a program to check a character is vowel or not.

Python if else Statement Practice Test 5

Q1. Accept the following from the user and calculate the percentage of class attended:

a.     Total number of working days

b.     Total number of days for absent

    After calculating percentage show that, If the percentage is less than 75, than student will not be able to sit in exam.

Q2. Accept the percentage from the user and display the  grade according to the following criteria:

  •      Below 25 —- D
  •     25 to 45 —- C
  •     45 to 50 —- B
  •     50 to 60 –– B+
  •     60 to 80 — A
  •     Above 80 –- A+

Q3. A company decided to give bonus to employee according to following criteria:

    Time period of Service                Bonus

    More than 10 years             10%

    >=6 and <=10                   8%

    Less than 6 years              5%

    Ask user for their salary and years of service and print the net bonus amount.

Q4. Accept the marked price from the user and  calculate the Net amount as(Marked Price –    Discount) to pay according to following criteria:

0

Q5. Write a program to accept percentage and display the Category according to the  following criteria :

Q6. Accept three sides of a triangle and check whether it is an equilateral, isosceles or scalene triangle.

An equilateral triangle is a triangle in which all three sides are equal.

A scalene triangle is a triangle that has three unequal sides.

An isosceles triangle is a triangle with (at least) two equal sides.

Q7. Write a program to accept two numbers and mathematical operators and perform operation accordingly.

Enter First Number: 7

Enter Second Number : 9

Enter operator : +

Your Answer is : 16

Q8. Accept the age, sex (‘M’, ‘F’), number of days and display the wages accordingly

Age

If age does not fall in any range then display the following message: “Enter appropriate age”

Python if else Statement Practice Test 6

Q1. Accept three numbers from the user and display the second largest number.

Q2. Accept three sides of triangle and check whether the triangle is possible or not.

(triangle is possible only when sum of any two sides is greater than 3 rd  side)

Q3. Consider the following code

python conditional statement practice

What will the above code print if the variables i, j, and k have the following values?

(a)    i = 3, j = 5, k = 7

(b)    i = -2, j = -5, k = 9

(c)    i = 8, j = 15, k = 12

(d)    i = 13, j = 15, k = 13

(e)    i = 3, j = 5, k = 17

(f)    i = 25, j = 15, k = 17

Q4. Accept the electric units from user and calculate the bill according to the following rates.

First 100 Units     :  Free

Next 200 Units      :  Rs 2 per day.

Above 300 Units    :  Rs 5 per day.

if number of unit is 500 then total bill = 0 +400 + 1000 = 1400

Q5. Accept the number of days from the user and calculate the charge for library according to following :

Till five days : Rs 2/day.

Six to ten days  : Rs 3/day.

11 to 15 days  : Rs 4/day

After 15 days    : Rs 5/day

Q6. Accept the kilometers covered and calculate the bill according to the following criteria:

First 10 Km              Rs11/km

Next 90Km               Rs 10/km

After that               Rs9/km

Q7. Accept the marks of English, Math and Science, Social Studies Subject and display the stream allotted according to following

All Subjects more than 80 marks —       Science Stream

English >80 and Math, Science above 50 –Commerce Stream

English > 80 and Social studies > 80    —   Humanities

Python if else Statement Practice Test 7

Q1. Evaluate the following statements:

  • d=True        

The idea of giving above assignment of python if else is to give students a lot of practice of python if else concept and he/she would be able to do all types of question related to “python if else”

Disclaimer : I tried to give correct code of all the answers of above python if else assignments. The code is not copied from any other site or any other assignment of python if else. Please share feedback of above python if else assignment to [email protected] so that i can improve and give better content to you.

Class 12 Computer Science Sample Paper 2020-2021 .

Class 12 Computer Science Sample Paper Marking Scheme

Class 12 Computer Science Test Series

32 thoughts on “70+ Python if else Statement Important Practice Questions”

This is really use full. Please can you provide the answer for this one.

# Accept the marks of English, Math and Science, Social Studies Subject and display the stream allotted according to following

# All Subjects more than 80 marks — Science Stream # English >80 and Math, Science above 50 –Commerce Stream # English > 80 and Social studies > 80 — Humanities

Thankyou Ram babu.

eng = int(input(“ENGLISH : “)) sst = int(input(“SOCIAL STUDIES : “)) mth = int(input(“MATHS : “)) sci = int(input(“SCIENCE : “))

if eng > 80 and mth > 80 and sci > 80 and sst > 80: print(“Science Stream”) elif eng > 80 and (80 > mth and sci > 50): print(“Commerce Stream”) elif (eng and sst > 80) and (mth and sci < 80): print("Humanities")

if mar > 80: print(english,social,) print(science stream,humanities) elif mar >50 and mar <80: print(math , science) print("commerce stream")

m,e,s,so=map(int,input().split()) if m>80 and e>80: if s>80 and so>80: print(“alloted science stream”) if e>80: if m>50 and s>50: print(“alloted commers”) elif so>80: print(“alloted humanites”)

Sir it is so easy question

eng = int(input(“Enter your English marks : “)) math = int(input(“Enter your Math marks : “)) science = int(input(“Enter your Science marks : “)) ss = int(input(“Enter your Social Studies : “))

if eng >= 80 and math >= 80 and science >= 80 and ss >= 80: print (“Science Stream”) elif eng >= 80 and (50>=math and science >= 50): print (“Commerce Stream”) elif eng >= 80 and (ss >=80): print (“Humanities”)

a=int(input(“Please enter your English marks: “)) b=int(input(“Please enter your Maths marks: “)) c=int(input(“Please enter your Social Science marks: “)) d=int(input(“Please enter your Science marks: “)) if a>80 and b>80 and c>80 and d>80: print(“The stream alloted to you is Science.”) elif(a>80 and b>50 and d>50): print(“The stream alloted to you is Commerce.”) elif(a>80 and c>80): print(“The stream alloted to you is Humanities.”) else: print(“Sorry! But no stream is alloted to you.”)

Hello, can you please tell me why the we need to have 500 for calculations nu>200 in Q8 Test1 ?

Q8. Write a program to calculate the electricity bill […] if nu>200: amt=500+(nu-200)*10 print(“Amount to pay :”,amt)

I don’t get it!

Hi Actually first 100 units are free and next 100 units are charged @ 5/unit so for next 100 unit amount is 5*100=500

of course!!! thank you so much

Write a program to calculate the electricity bill (accept number of unit from user) according to the following criteria : Unit Price First 100 units no charge Next 100 units Rs 5 per unit After 200 units Rs 10 per unit (For example if input unit is 350 than total bill amount is Rs2000)

if any one help on this.

I have a problem is Test 6, Ques no 3.??? Can anyone solve this by explaining in detail??

Firstly, the given code is written in 11 lines. a) i=3, j=5, k=7 (consider these values for i, j and k)

As first line is true as it satisfies the condition for (i<j) i.e., 3<5, it ignores else block which is at line 6 and enters into the "if" block which is at line 1. After entering inside the first "if" block which is at line 1. As again the condition is true at line 2, it enters into 3rd line thereafter "i" gets the value of "j" which means "i" value is 5 now. And ignores the "else" block which is at line 4. So, it it directly goes to line 11 and prints the values for i,j and k…here i value becomes 5. 'J' and 'K' values don't change as they are not being affected like i.

unit= int(input(“enter unit”)) if unit<=100: print("their is no charges") elif unit in range(101,201): price=100*0+(unit-100)*5 print("your electricity bill is",price) else: price=100*0+500+(unit-200)*10 print(price)

amount=0 n=int(input(“Enter the units”) if n>=100: amount=0 if n>100 and n200 amount= 500 +(n-200)*10 // 100 units is rs 5 per unit (100*5=500) print(“amount to be paid:”,amount)

x=int(input(“Enter the number of units: “)) amt=0 if x100 and x200: amt=500+(x-200)*5 print(amt)

km = int(input(‘Enter kms = ‘))

if (km 10 and km <= 100): charge = 110 + ((km- 10) * 10)

else: charge = 1010 + (km – 100) * 9 print('total bill amount is ',charge)

units = float(input(“Enter electricity unit charges: “)) if units <= 50: bill = units * 0.50 elif units <= 150: bill = 50 * 0.50 + (units – 50) * 0.75 elif units <=250: bill = 50 * 0.50 + 100 * 0.75 + (units – 100) * 1.20 else: bill = 50 * 0.50 + 100 * 0.75 + 100 * 1.20 + (units – 100) * 1.50 surcharge = bill * 0.20 total_bill = bill + surcharge print("Electricity bill: ", bill) print("Surcharge: ", surcharge) print("Total bill: ", total_bill)

For example Enter unit is 450 100 = free 450-100= 350 350 __ 100 Ra 5 =500 250 ___ 250*10=2500 2500+500= 3000

bro in the question it said that for first 100 units its for free , then next 100 units you have to pay 5 ruppes per unit that means 100*5=500 ruppes and after 200 unit u have to pay 10 ruppes per unit that means previous 100*5=500 and after 200 units the formula is (num-200)*10 ruppes and also u have to pay the prevoius unit i.e. 500 thats why it written amt = 500+(num-200)*10

That’s amazing and please tell me that it’s enough for learn and practice the code in condition programs?

ME= int(input(‘Enter English Marks out of 100: ‘)) MM= int(input(‘Enter Maths Marks out of 100: ‘)) MS= int(input(‘Enter Science Marks out of 100: ‘)) MSS= int(input(‘Enter SST Marks out of 100: ‘)) SF = float(ME+MM+MS+MSS) CF = float(ME+MM+MS+MSS) Hm = float(MS+MSS) if SF>=320: print (‘You are eligible for Science Faculty’) elif CF>=260 and CF=50 and Hm <200: print ('You are eligible for Humanities') (Its a junior and just a beginner Python programmer from Pakistan. I just tried this whole code on my own. Sb may find it a bit pathetic. Mee too. But it somehow ran. But not with accurate demanded Output. But to some extent. Need your guidance dear all. Thanks

science=int(input(“Enter Your Science Marks:”)) english=int(input(“Enter Your english marks:”)) math=int(input(“Enter your maths marks:”)) socialstu=int(input(“Enter Your marks Socialstudies:”)) allsubject = (science+english+math+socialstu)/400*100 if allsubject>80: print(“You go for Science Stream”) elif english>=80 and math>50 and science>50: print(“You go for commerce stream”) elif english>=80 and socialstu>80: print(“You go for Humanities”) else: print(“You entered wrong subject”)

# last digit print

num=int(input(‘enter the any number—>’)) b=num%10 print(b) if b: print(b) else: print(“0”)

Wowwwwwwww!!!! really helped me alot… studied it before my practical.

e= int(input(“Enter marks of English: “)) m= int(input(“Enter marks of Maths: “)) s= int(input(“Enter marks of Science: “)) ss= int(input(“Enter marks of Social Science: “)) if e>80 and m>80 and s>80 and ss>80: print(“Science Stream allotted”) elif e>80 and m>50 and s>50: print(“Commerce Stream allotted”) elif e>80 and ss>80: print(“Humanities Stream allotted”)

english_marks = int(input(“Enter marks in English: “)) math_marks = int(input(“Enter marks in Mathematics: “)) science_marks = int(input(“Enter marks in Science: “)) computers_marks = int(input(“Enter marks in Computers: “))

average_percentage = (english_marks + math_marks + science_marks + computers_marks) / 4

if average_percentage > 80: print(‘You got Science Stream’) elif 60 <= average_percentage <= 80: print('You got Commerce Stream') elif 50 <= average_percentage < 60: print('You got Arts Stream') else: print('Sorry! No stream is allotted to you')

a=int(input(“enter the umit:”)) if a<=100: print("no charge") elif 100<a<=200: print("bonus is",5*a) elif 200<a<350: print("bonus is",10*a) else: print("bonus: if unit is 350 is",2000)

How do I get to while-loop?

eng_marks=int(input(“Enter the marks in eng subject: “)) math_marks=int(input(“Enter the marks in math subject: “)) science_marks=int(input(“Enter the marks in science subject: “)) social_marks=int(input(“Enter the marks in social subject: “)) total_marks=eng_marks+math_marks+science_marks+social_marks if eng_marks>80 and math_marks > 80 and science_marks > 80 and social_marks > 80: print(“You are eligible for Science Stream”) elif (eng_marks >80 and math_marks>80 )and science_marks >50 : print(“You are eligible for the Commerce Stream”) elif eng_marks > 80 and social_marks > 80: print(“You are eligible for the Humanities”)

Leave a Reply Cancel reply

Python's Assignment Operator: Write Robust Assignments

Python's Assignment Operator: Write Robust Assignments

Table of Contents

The Assignment Statement Syntax

The assignment operator, assignments and variables, other assignment syntax, initializing and updating variables, making multiple variables refer to the same object, updating lists through indices and slices, adding and updating dictionary keys, doing parallel assignments, unpacking iterables, providing default argument values, augmented mathematical assignment operators, augmented assignments for concatenation and repetition, augmented bitwise assignment operators, annotated assignment statements, assignment expressions with the walrus operator, managed attribute assignments, define or call a function, work with classes, import modules and objects, use a decorator, access the control variable in a for loop or a comprehension, use the as keyword, access the _ special variable in an interactive session, built-in objects, named constants.

Python’s assignment operators allow you to define assignment statements . This type of statement lets you create, initialize, and update variables throughout your code. Variables are a fundamental cornerstone in every piece of code, and assignment statements give you complete control over variable creation and mutation.

Learning about the Python assignment operator and its use for writing assignment statements will arm you with powerful tools for writing better and more robust Python code.

In this tutorial, you’ll:

  • Use Python’s assignment operator to write assignment statements
  • Take advantage of augmented assignments in Python
  • Explore assignment variants, like assignment expressions and managed attributes
  • Become aware of illegal and dangerous assignments in Python

You’ll dive deep into Python’s assignment statements. To get the most out of this tutorial, you should be comfortable with several basic topics, including variables , built-in data types , comprehensions , functions , and Python keywords . Before diving into some of the later sections, you should also be familiar with intermediate topics, such as object-oriented programming , constants , imports , type hints , properties , descriptors , and decorators .

Free Source Code: Click here to download the free assignment operator source code that you’ll use to write assignment statements that allow you to create, initialize, and update variables in your code.

Assignment Statements and the Assignment Operator

One of the most powerful programming language features is the ability to create, access, and mutate variables . In Python, a variable is a name that refers to a concrete value or object, allowing you to reuse that value or object throughout your code.

To create a new variable or to update the value of an existing one in Python, you’ll use an assignment statement . This statement has the following three components:

  • A left operand, which must be a variable
  • The assignment operator ( = )
  • A right operand, which can be a concrete value , an object , or an expression

Here’s how an assignment statement will generally look in Python:

Here, variable represents a generic Python variable, while expression represents any Python object that you can provide as a concrete value—also known as a literal —or an expression that evaluates to a value.

To execute an assignment statement like the above, Python runs the following steps:

  • Evaluate the right-hand expression to produce a concrete value or object . This value will live at a specific memory address in your computer.
  • Store the object’s memory address in the left-hand variable . This step creates a new variable if the current one doesn’t already exist or updates the value of an existing variable.

The second step shows that variables work differently in Python than in other programming languages. In Python, variables aren’t containers for objects. Python variables point to a value or object through its memory address. They store memory addresses rather than objects.

This behavior difference directly impacts how data moves around in Python, which is always by reference . In most cases, this difference is irrelevant in your day-to-day coding, but it’s still good to know.

The central component of an assignment statement is the assignment operator . This operator is represented by the = symbol, which separates two operands:

  • A value or an expression that evaluates to a concrete value

Operators are special symbols that perform mathematical , logical , and bitwise operations in a programming language. The objects (or object) on which an operator operates are called operands .

Unary operators, like the not Boolean operator, operate on a single object or operand, while binary operators act on two. That means the assignment operator is a binary operator.

Note: Like C , Python uses == for equality comparisons and = for assignments. Unlike C, Python doesn’t allow you to accidentally use the assignment operator ( = ) in an equality comparison.

Equality is a symmetrical relationship, and assignment is not. For example, the expression a == 42 is equivalent to 42 == a . In contrast, the statement a = 42 is correct and legal, while 42 = a isn’t allowed. You’ll learn more about illegal assignments later on.

The right-hand operand in an assignment statement can be any Python object, such as a number , list , string , dictionary , or even a user-defined object. It can also be an expression. In the end, expressions always evaluate to concrete objects, which is their return value.

Here are a few examples of assignments in Python:

The first two sample assignments in this code snippet use concrete values, also known as literals , to create and initialize number and greeting . The third example assigns the result of a math expression to the total variable, while the last example uses a Boolean expression.

Note: You can use the built-in id() function to inspect the memory address stored in a given variable.

Here’s a short example of how this function works:

The number in your output represents the memory address stored in number . Through this address, Python can access the content of number , which is the integer 42 in this example.

If you run this code on your computer, then you’ll get a different memory address because this value varies from execution to execution and computer to computer.

Unlike expressions, assignment statements don’t have a return value because their purpose is to make the association between the variable and its value. That’s why the Python interpreter doesn’t issue any output in the above examples.

Now that you know the basics of how to write an assignment statement, it’s time to tackle why you would want to use one.

The assignment statement is the explicit way for you to associate a name with an object in Python. You can use this statement for two main purposes:

  • Creating and initializing new variables
  • Updating the values of existing variables

When you use a variable name as the left operand in an assignment statement for the first time, you’re creating a new variable. At the same time, you’re initializing the variable to point to the value of the right operand.

On the other hand, when you use an existing variable in a new assignment, you’re updating or mutating the variable’s value. Strictly speaking, every new assignment will make the variable refer to a new value and stop referring to the old one. Python will garbage-collect all the values that are no longer referenced by any existing variable.

Assignment statements not only assign a value to a variable but also determine the data type of the variable at hand. This additional behavior is another important detail to consider in this kind of statement.

Because Python is a dynamically typed language, successive assignments to a given variable can change the variable’s data type. Changing the data type of a variable during a program’s execution is considered bad practice and highly discouraged. It can lead to subtle bugs that can be difficult to track down.

Unlike in math equations, in Python assignments, the left operand must be a variable rather than an expression or a value. For example, the following construct is illegal, and Python flags it as invalid syntax:

In this example, you have expressions on both sides of the = sign, and this isn’t allowed in Python code. The error message suggests that you may be confusing the equality operator with the assignment one, but that’s not the case. You’re really running an invalid assignment.

To correct this construct and convert it into a valid assignment, you’ll have to do something like the following:

In this code snippet, you first import the sqrt() function from the math module. Then you isolate the hypotenuse variable in the original equation by using the sqrt() function. Now your code works correctly.

Now you know what kind of syntax is invalid. But don’t get the idea that assignment statements are rigid and inflexible. In fact, they offer lots of room for customization, as you’ll learn next.

Python’s assignment statements are pretty flexible and versatile. You can write them in several ways, depending on your specific needs and preferences. Here’s a quick summary of the main ways to write assignments in Python:

Up to this point, you’ve mostly learned about the base assignment syntax in the above code snippet. In the following sections, you’ll learn about multiple, parallel, and augmented assignments. You’ll also learn about assignments with iterable unpacking.

Read on to see the assignment statements in action!

Assignment Statements in Action

You’ll find and use assignment statements everywhere in your Python code. They’re a fundamental part of the language, providing an explicit way to create, initialize, and mutate variables.

You can use assignment statements with plain names, like number or counter . You can also use assignments in more complicated scenarios, such as with:

  • Qualified attribute names , like user.name
  • Indices and slices of mutable sequences, like a_list[i] and a_list[i:j]
  • Dictionary keys , like a_dict[key]

This list isn’t exhaustive. However, it gives you some idea of how flexible these statements are. You can even assign multiple values to an equal number of variables in a single line, commonly known as parallel assignment . Additionally, you can simultaneously assign the values in an iterable to a comma-separated group of variables in what’s known as an iterable unpacking operation.

In the following sections, you’ll dive deeper into all these topics and a few other exciting things that you can do with assignment statements in Python.

The most elementary use case of an assignment statement is to create a new variable and initialize it using a particular value or expression:

All these statements create new variables, assigning them initial values or expressions. For an initial value, you should always use the most sensible and least surprising value that you can think of. For example, initializing a counter to something different from 0 may be confusing and unexpected because counters almost always start having counted no objects.

Updating a variable’s current value or state is another common use case of assignment statements. In Python, assigning a new value to an existing variable doesn’t modify the variable’s current value. Instead, it causes the variable to refer to a different value. The previous value will be garbage-collected if no other variable refers to it.

Consider the following examples:

These examples run two consecutive assignments on the same variable. The first one assigns the string "Hello, World!" to a new variable named greeting .

The second assignment updates the value of greeting by reassigning it the "Hi, Pythonistas!" string. In this example, the original value of greeting —the "Hello, World!" string— is lost and garbage-collected. From this point on, you can’t access the old "Hello, World!" string.

Even though running multiple assignments on the same variable during a program’s execution is common practice, you should use this feature with caution. Changing the value of a variable can make your code difficult to read, understand, and debug. To comprehend the code fully, you’ll have to remember all the places where the variable was changed and the sequential order of those changes.

Because assignments also define the data type of their target variables, it’s also possible for your code to accidentally change the type of a given variable at runtime. A change like this can lead to breaking errors, like AttributeError exceptions. Remember that strings don’t have the same methods and attributes as lists or dictionaries, for example.

In Python, you can make several variables reference the same object in a multiple-assignment line. This can be useful when you want to initialize several similar variables using the same initial value:

In this example, you chain two assignment operators in a single line. This way, your two variables refer to the same initial value of 0 . Note how both variables hold the same memory address, so they point to the same instance of 0 .

When it comes to integer variables, Python exhibits a curious behavior. It provides a numeric interval where multiple assignments behave the same as independent assignments. Consider the following examples:

To create n and m , you use independent assignments. Therefore, they should point to different instances of the number 42 . However, both variables hold the same object, which you confirm by comparing their corresponding memory addresses.

Now check what happens when you use a greater initial value:

Now n and m hold different memory addresses, which means they point to different instances of the integer number 300 . In contrast, when you use multiple assignments, both variables refer to the same object. This tiny difference can save you small bits of memory if you frequently initialize integer variables in your code.

The implicit behavior of making independent assignments point to the same integer number is actually an optimization called interning . It consists of globally caching the most commonly used integer values in day-to-day programming.

Under the hood, Python defines a numeric interval in which interning takes place. That’s the interning interval for integer numbers. You can determine this interval using a small script like the following:

This script helps you determine the interning interval by comparing integer numbers from -10 to 500 . If you run the script from your command line, then you’ll get an output like the following:

This output means that if you use a single number between -5 and 256 to initialize several variables in independent statements, then all these variables will point to the same object, which will help you save small bits of memory in your code.

In contrast, if you use a number that falls outside of the interning interval, then your variables will point to different objects instead. Each of these objects will occupy a different memory spot.

You can use the assignment operator to mutate the value stored at a given index in a Python list. The operator also works with list slices . The syntax to write these types of assignment statements is the following:

In the first construct, expression can return any Python object, including another list. In the second construct, expression must return a series of values as a list, tuple, or any other sequence. You’ll get a TypeError if expression returns a single value.

Note: When creating slice objects, you can use up to three arguments. These arguments are start , stop , and step . They define the number that starts the slice, the number at which the slicing must stop retrieving values, and the step between values.

Here’s an example of updating an individual value in a list:

In this example, you update the value at index 2 using an assignment statement. The original number at that index was 7 , and after the assignment, the number is 3 .

Note: Using indices and the assignment operator to update a value in a tuple or a character in a string isn’t possible because tuples and strings are immutable data types in Python.

Their immutability means that you can’t change their items in place :

You can’t use the assignment operator to change individual items in tuples or strings. These data types are immutable and don’t support item assignments.

It’s important to note that you can’t add new values to a list by using indices that don’t exist in the target list:

In this example, you try to add a new value to the end of numbers by using an index that doesn’t exist. This assignment isn’t allowed because there’s no way to guarantee that new indices will be consecutive. If you ever want to add a single value to the end of a list, then use the .append() method.

If you want to update several consecutive values in a list, then you can use slicing and an assignment statement:

In the first example, you update the letters between indices 1 and 3 without including the letter at 3 . The second example updates the letters from index 3 until the end of the list. Note that this slicing appends a new value to the list because the target slice is shorter than the assigned values.

Also note that the new values were provided through a tuple, which means that this type of assignment allows you to use other types of sequences to update your target list.

The third example updates a single value using a slice where both indices are equal. In this example, the assignment inserts a new item into your target list.

In the final example, you use a step of 2 to replace alternating letters with their lowercase counterparts. This slicing starts at index 1 and runs through the whole list, stepping by two items each time.

Updating the value of an existing key or adding new key-value pairs to a dictionary is another common use case of assignment statements. To do these operations, you can use the following syntax:

The first construct helps you update the current value of an existing key, while the second construct allows you to add a new key-value pair to the dictionary.

For example, to update an existing key, you can do something like this:

In this example, you update the current inventory of oranges in your store using an assignment. The left operand is the existing dictionary key, and the right operand is the desired new value.

While you can’t add new values to a list by assignment, dictionaries do allow you to add new key-value pairs using the assignment operator. In the example below, you add a lemon key to inventory :

In this example, you successfully add a new key-value pair to your inventory with 100 units. This addition is possible because dictionaries don’t have consecutive indices but unique keys, which are safe to add by assignment.

The assignment statement does more than assign the result of a single expression to a single variable. It can also cope nicely with assigning multiple values to multiple variables simultaneously in what’s known as a parallel assignment .

Here’s the general syntax for parallel assignments in Python:

Note that the left side of the statement can be either a tuple or a list of variables. Remember that to create a tuple, you just need a series of comma-separated elements. In this case, these elements must be variables.

The right side of the statement must be a sequence or iterable of values or expressions. In any case, the number of elements in the right operand must match the number of variables on the left. Otherwise, you’ll get a ValueError exception.

In the following example, you compute the two solutions of a quadratic equation using a parallel assignment:

In this example, you first import sqrt() from the math module. Then you initialize the equation’s coefficients in a parallel assignment.

The equation’s solution is computed in another parallel assignment. The left operand contains a tuple of two variables, x1 and x2 . The right operand consists of a tuple of expressions that compute the solutions for the equation. Note how each result is assigned to each variable by position.

A classical use case of parallel assignment is to swap values between variables:

The highlighted line does the magic and swaps the values of previous_value and next_value at the same time. Note that in a programming language that doesn’t support this kind of assignment, you’d have to use a temporary variable to produce the same effect:

In this example, instead of using parallel assignment to swap values between variables, you use a new variable to temporarily store the value of previous_value to avoid losing its reference.

For a concrete example of when you’d need to swap values between variables, say you’re learning how to implement the bubble sort algorithm , and you come up with the following function:

In the highlighted line, you use a parallel assignment to swap values in place if the current value is less than the next value in the input list. To dive deeper into the bubble sort algorithm and into sorting algorithms in general, check out Sorting Algorithms in Python .

You can use assignment statements for iterable unpacking in Python. Unpacking an iterable means assigning its values to a series of variables one by one. The iterable must be the right operand in the assignment, while the variables must be the left operand.

Like in parallel assignments, the variables must come as a tuple or list. The number of variables must match the number of values in the iterable. Alternatively, you can use the unpacking operator ( * ) to grab several values in a variable if the number of variables doesn’t match the iterable length.

Here’s the general syntax for iterable unpacking in Python:

Iterable unpacking is a powerful feature that you can use all around your code. It can help you write more readable and concise code. For example, you may find yourself doing something like this:

Whenever you do something like this in your code, go ahead and replace it with a more readable iterable unpacking using a single and elegant assignment, like in the following code snippet:

The numbers list on the right side contains four values. The assignment operator unpacks these values into the four variables on the left side of the statement. The values in numbers get assigned to variables in the same order that they appear in the iterable. The assignment is done by position.

Note: Because Python sets are also iterables, you can use them in an iterable unpacking operation. However, it won’t be clear which value goes to which variable because sets are unordered data structures.

The above example shows the most common form of iterable unpacking in Python. The main condition for the example to work is that the number of variables matches the number of values in the iterable.

What if you don’t know the iterable length upfront? Will the unpacking work? It’ll work if you use the * operator to pack several values into one of your target variables.

For example, say that you want to unpack the first and second values in numbers into two different variables. Additionally, you would like to pack the rest of the values in a single variable conveniently called rest . In this case, you can use the unpacking operator like in the following code:

In this example, first and second hold the first and second values in numbers , respectively. These values are assigned by position. The * operator packs all the remaining values in the input iterable into rest .

The unpacking operator ( * ) can appear at any position in your series of target variables. However, you can only use one instance of the operator:

The iterable unpacking operator works in any position in your list of variables. Note that you can only use one unpacking operator per assignment. Using more than one unpacking operator isn’t allowed and raises a SyntaxError .

Dropping away unwanted values from the iterable is a common use case for the iterable unpacking operator. Consider the following example:

In Python, if you want to signal that a variable won’t be used, then you use an underscore ( _ ) as the variable’s name. In this example, useful holds the only value that you need to use from the input iterable. The _ variable is a placeholder that guarantees that the unpacking works correctly. You won’t use the values that end up in this disposable variable.

Note: In the example above, if your target iterable is a sequence data type, such as a list or tuple, then it’s best to access its last item directly.

To do this, you can use the -1 index:

Using -1 gives you access to the last item of any sequence data type. In contrast, if you’re dealing with iterators , then you won’t be able to use indices. That’s when the *_ syntax comes to your rescue.

The pattern used in the above example comes in handy when you have a function that returns multiple values, and you only need a few of these values in your code. The os.walk() function may provide a good example of this situation.

This function allows you to iterate over the content of a directory recursively. The function returns a generator object that yields three-item tuples. Each tuple contains the following items:

  • The path to the current directory as a string
  • The names of all the immediate subdirectories as a list of strings
  • The names of all the files in the current directory as a list of strings

Now say that you want to iterate over your home directory and list only the files. You can do something like this:

This code will issue a long output depending on the current content of your home directory. Note that you need to provide a string with the path to your user folder for the example to work. The _ placeholder variable will hold the unwanted data.

In contrast, the filenames variable will hold the list of files in the current directory, which is the data that you need. The code will print the list of filenames. Go ahead and give it a try!

The assignment operator also comes in handy when you need to provide default argument values in your functions and methods. Default argument values allow you to define functions that take arguments with sensible defaults. These defaults allow you to call the function with specific values or to simply rely on the defaults.

As an example, consider the following function:

This function takes one argument, called name . This argument has a sensible default value that’ll be used when you call the function without arguments. To provide this sensible default value, you use an assignment.

Note: According to PEP 8 , the style guide for Python code, you shouldn’t use spaces around the assignment operator when providing default argument values in function definitions.

Here’s how the function works:

If you don’t provide a name during the call to greet() , then the function uses the default value provided in the definition. If you provide a name, then the function uses it instead of the default one.

Up to this point, you’ve learned a lot about the Python assignment operator and how to use it for writing different types of assignment statements. In the following sections, you’ll dive into a great feature of assignment statements in Python. You’ll learn about augmented assignments .

Augmented Assignment Operators in Python

Python supports what are known as augmented assignments . An augmented assignment combines the assignment operator with another operator to make the statement more concise. Most Python math and bitwise operators have an augmented assignment variation that looks something like this:

Note that $ isn’t a valid Python operator. In this example, it’s a placeholder for a generic operator. This statement works as follows:

  • Evaluate expression to produce a value.
  • Run the operation defined by the operator that prefixes the = sign, using the previous value of variable and the return value of expression as operands.
  • Assign the resulting value back to variable .

In practice, an augmented assignment like the above is equivalent to the following statement:

As you can conclude, augmented assignments are syntactic sugar . They provide a shorthand notation for a specific and popular kind of assignment.

For example, say that you need to define a counter variable to count some stuff in your code. You can use the += operator to increment counter by 1 using the following code:

In this example, the += operator, known as augmented addition , adds 1 to the previous value in counter each time you run the statement counter += 1 .

It’s important to note that unlike regular assignments, augmented assignments don’t create new variables. They only allow you to update existing variables. If you use an augmented assignment with an undefined variable, then you get a NameError :

Python evaluates the right side of the statement before assigning the resulting value back to the target variable. In this specific example, when Python tries to compute x + 1 , it finds that x isn’t defined.

Great! You now know that an augmented assignment consists of combining the assignment operator with another operator, like a math or bitwise operator. To continue this discussion, you’ll learn which math operators have an augmented variation in Python.

An equation like x = x + b doesn’t make sense in math. But in programming, a statement like x = x + b is perfectly valid and can be extremely useful. It adds b to x and reassigns the result back to x .

As you already learned, Python provides an operator to shorten x = x + b . Yes, the += operator allows you to write x += b instead. Python also offers augmented assignment operators for most math operators. Here’s a summary:

Operator Description Example Equivalent
Adds the right operand to the left operand and stores the result in the left operand
Subtracts the right operand from the left operand and stores the result in the left operand
Multiplies the right operand with the left operand and stores the result in the left operand
Divides the left operand by the right operand and stores the result in the left operand
Performs of the left operand by the right operand and stores the result in the left operand
Finds the remainder of dividing the left operand by the right operand and stores the result in the left operand
Raises the left operand to the power of the right operand and stores the result in the left operand

The Example column provides generic examples of how to use the operators in actual code. Note that x must be previously defined for the operators to work correctly. On the other hand, y can be either a concrete value or an expression that returns a value.

Note: The matrix multiplication operator ( @ ) doesn’t support augmented assignments yet.

Consider the following example of matrix multiplication using NumPy arrays:

Note that the exception traceback indicates that the operation isn’t supported yet.

To illustrate how augmented assignment operators work, say that you need to create a function that takes an iterable of numeric values and returns their sum. You can write this function like in the code below:

In this function, you first initialize total to 0 . In each iteration, the loop adds a new number to total using the augmented addition operator ( += ). When the loop terminates, total holds the sum of all the input numbers. Variables like total are known as accumulators . The += operator is typically used to update accumulators.

Note: Computing the sum of a series of numeric values is a common operation in programming. Python provides the built-in sum() function for this specific computation.

Another interesting example of using an augmented assignment is when you need to implement a countdown while loop to reverse an iterable. In this case, you can use the -= operator:

In this example, custom_reversed() is a generator function because it uses yield . Calling the function creates an iterator that yields items from the input iterable in reverse order. To decrement the control variable, index , you use an augmented subtraction statement that subtracts 1 from the variable in every iteration.

Note: Similar to summing the values in an iterable, reversing an iterable is also a common requirement. Python provides the built-in reversed() function for this specific computation, so you don’t have to implement your own. The above example only intends to show the -= operator in action.

Finally, counters are a special type of accumulators that allow you to count objects. Here’s an example of a letter counter:

To create this counter, you use a Python dictionary. The keys store the letters. The values store the counts. Again, to increment the counter, you use an augmented addition.

Counters are so common in programming that Python provides a tool specially designed to facilitate the task of counting. Check out Python’s Counter: The Pythonic Way to Count Objects for a complete guide on how to use this tool.

The += and *= augmented assignment operators also work with sequences , such as lists, tuples, and strings. The += operator performs augmented concatenations , while the *= operator performs augmented repetition .

These operators behave differently with mutable and immutable data types:

Operator Description Example
Runs an augmented concatenation operation on the target sequence. Mutable sequences are updated in place. If the sequence is immutable, then a new sequence is created and assigned back to the target name.
Adds to itself times. Mutable sequences are updated in place. If the sequence is immutable, then a new sequence is created and assigned back to the target name.

Note that the augmented concatenation operator operates on two sequences, while the augmented repetition operator works on a sequence and an integer number.

Consider the following examples and pay attention to the result of calling the id() function:

Mutable sequences like lists support the += augmented assignment operator through the .__iadd__() method, which performs an in-place addition. This method mutates the underlying list, appending new values to its end.

Note: If the left operand is mutable, then x += y may not be completely equivalent to x = x + y . For example, if you do list_1 = list_1 + list_2 instead of list_1 += list_2 above, then you’ll create a new list instead of mutating the existing one. This may be important if other variables refer to the same list.

Immutable sequences, such as tuples and strings, don’t provide an .__iadd__() method. Therefore, augmented concatenations fall back to the .__add__() method, which doesn’t modify the sequence in place but returns a new sequence.

There’s another difference between mutable and immutable sequences when you use them in an augmented concatenation. Consider the following examples:

With mutable sequences, the data to be concatenated can come as a list, tuple, string, or any other iterable. In contrast, with immutable sequences, the data can only come as objects of the same type. You can concatenate tuples to tuples and strings to strings, for example.

Again, the augmented repetition operator works with a sequence on the left side of the operator and an integer on the right side. This integer value represents the number of repetitions to get in the resulting sequence:

When the *= operator operates on a mutable sequence, it falls back to the .__imul__() method, which performs the operation in place, modifying the underlying sequence. In contrast, if *= operates on an immutable sequence, then .__mul__() is called, returning a new sequence of the same type.

Note: Values of n less than 0 are treated as 0 , which returns an empty sequence of the same data type as the target sequence on the left side of the *= operand.

Note that a_list[0] is a_list[3] returns True . This is because the *= operator doesn’t make a copy of the repeated data. It only reflects the data. This behavior can be a source of issues when you use the operator with mutable values.

For example, say that you want to create a list of lists to represent a matrix, and you need to initialize the list with n empty lists, like in the following code:

In this example, you use the *= operator to populate matrix with three empty lists. Now check out what happens when you try to populate the first sublist in matrix :

The appended values are reflected in the three sublists. This happens because the *= operator doesn’t make copies of the data that you want to repeat. It only reflects the data. Therefore, every sublist in matrix points to the same object and memory address.

If you ever need to initialize a list with a bunch of empty sublists, then use a list comprehension :

This time, when you populate the first sublist of matrix , your changes aren’t propagated to the other sublists. This is because all the sublists are different objects that live in different memory addresses.

Bitwise operators also have their augmented versions. The logic behind them is similar to that of the math operators. The following table summarizes the augmented bitwise operators that Python provides:

Operator Operation Example Equivalent
Augmented bitwise AND ( )
Augmented bitwise OR ( )
Augmented bitwise XOR ( )
Augmented bitwise right shift
Augmented bitwise left shift

The augmented bitwise assignment operators perform the intended operation by taking the current value of the left operand as a starting point for the computation. Consider the following example, which uses the & and &= operators:

Programmers who work with high-level languages like Python rarely use bitwise operations in day-to-day coding. However, these types of operations can be useful in some situations.

For example, say that you’re implementing a Unix-style permission system for your users to access a given resource. In this case, you can use the characters "r" for reading, "w" for writing, and "x" for execution permissions, respectively. However, using bit-based permissions could be more memory efficient:

You can assign permissions to your users with the OR bitwise operator or the augmented OR bitwise operator. Finally, you can use the bitwise AND operator to check if a user has a certain permission, as you did in the final two examples.

You’ve learned a lot about augmented assignment operators and statements in this and the previous sections. These operators apply to math, concatenation, repetition, and bitwise operations. Now you’re ready to look at other assignment variants that you can use in your code or find in other developers’ code.

Other Assignment Variants

So far, you’ve learned that Python’s assignment statements and the assignment operator are present in many different scenarios and use cases. Those use cases include variable creation and initialization, parallel assignments, iterable unpacking, augmented assignments, and more.

In the following sections, you’ll learn about a few variants of assignment statements that can be useful in your future coding. You can also find these assignment variants in other developers’ code. So, you should be aware of them and know how they work in practice.

In short, you’ll learn about:

  • Annotated assignment statements with type hints
  • Assignment expressions with the walrus operator
  • Managed attribute assignments with properties and descriptors
  • Implicit assignments in Python

These topics will take you through several interesting and useful examples that showcase the power of Python’s assignment statements.

PEP 526 introduced a dedicated syntax for variable annotation back in Python 3.6 . The syntax consists of the variable name followed by a colon ( : ) and the variable type:

Even though these statements declare three variables with their corresponding data types, the variables aren’t actually created or initialized. So, for example, you can’t use any of these variables in an augmented assignment statement:

If you try to use one of the previously declared variables in an augmented assignment, then you get a NameError because the annotation syntax doesn’t define the variable. To actually define it, you need to use an assignment.

The good news is that you can use the variable annotation syntax in an assignment statement with the = operator:

The first statement in this example is what you can call an annotated assignment statement in Python. You may ask yourself why you should use type annotations in this type of assignment if everybody can see that counter holds an integer number. You’re right. In this example, the variable type is unambiguous.

However, imagine what would happen if you found a variable initialization like the following:

What would be the data type of each user in users ? If the initialization of users is far away from the definition of the User class, then there’s no quick way to answer this question. To clarify this ambiguity, you can provide the appropriate type hint for users :

Now you’re clearly communicating that users will hold a list of User instances. Using type hints in assignment statements that initialize variables to empty collection data types—such as lists, tuples, or dictionaries—allows you to provide more context about how your code works. This practice will make your code more explicit and less error-prone.

Up to this point, you’ve learned that regular assignment statements with the = operator don’t have a return value. They just create or update variables. Therefore, you can’t use a regular assignment to assign a value to a variable within the context of an expression.

Python 3.8 changed this by introducing a new type of assignment statement through PEP 572 . This new statement is known as an assignment expression or named expression .

Note: Expressions are a special type of statement in Python. Their distinguishing characteristic is that expressions always have a return value, which isn’t the case with all types of statements.

Unlike regular assignments, assignment expressions have a return value, which is why they’re called expressions in the first place. This return value is automatically assigned to a variable. To write an assignment expression, you must use the walrus operator ( := ), which was named for its resemblance to the eyes and tusks of a walrus lying on its side.

The general syntax of an assignment statement is as follows:

This expression looks like a regular assignment. However, instead of using the assignment operator ( = ), it uses the walrus operator ( := ). For the expression to work correctly, the enclosing parentheses are required in most use cases. However, there are certain situations in which these parentheses are superfluous. Either way, they won’t hurt you.

Assignment expressions come in handy when you want to reuse the result of an expression or part of an expression without using a dedicated assignment to grab this value beforehand.

Note: Assignment expressions with the walrus operator have several practical use cases. They also have a few restrictions. For example, they’re illegal in certain contexts, such as lambda functions, parallel assignments, and augmented assignments.

For a deep dive into this special type of assignment, check out The Walrus Operator: Python’s Assignment Expressions .

A particularly handy use case for assignment expressions is when you need to grab the result of an expression used in the context of a conditional statement. For example, say that you need to write a function to compute the mean of a sample of numeric values. Without the walrus operator, you could do something like this:

In this example, the sample size ( n ) is a value that you need to reuse in two different computations. First, you need to check whether the sample has data points or not. Then you need to use the sample size to compute the mean. To be able to reuse n , you wrote a dedicated assignment statement at the beginning of your function to grab the sample size.

You can avoid this extra step by combining it with the first use of the target value, len(sample) , using an assignment expression like the following:

The assignment expression introduced in the conditional computes the sample size and assigns it to n . This way, you guarantee that you have a reference to the sample size to use in further computations.

Because the assignment expression returns the sample size anyway, the conditional can check whether that size equals 0 or not and then take a certain course of action depending on the result of this check. The return statement computes the sample’s mean and sends the result back to the function caller.

Python provides a few tools that allow you to fine-tune the operations behind the assignment of attributes. The attributes that run implicit operations on assignments are commonly referred to as managed attributes .

Properties are the most commonly used tool for providing managed attributes in your classes. However, you can also use descriptors and, in some cases, the .__setitem__() special method.

To understand what fine-tuning the operation behind an assignment means, say that you need a Point class that only allows numeric values for its coordinates, x and y . To write this class, you must set up a validation mechanism to reject non-numeric values. You can use properties to attach the validation functionality on top of x and y .

Here’s how you can write your class:

In Point , you use properties for the .x and .y coordinates. Each property has a getter and a setter method . The getter method returns the attribute at hand. The setter method runs the input validation using a try … except block and the built-in float() function. Then the method assigns the result to the actual attribute.

Here’s how your class works in practice:

When you use a property-based attribute as the left operand in an assignment statement, Python automatically calls the property’s setter method, running any computation from it.

Because both .x and .y are properties, the input validation runs whenever you assign a value to either attribute. In the first example, the input values are valid numbers and the validation passes. In the final example, "one" isn’t a valid numeric value, so the validation fails.

If you look at your Point class, you’ll note that it follows a repetitive pattern, with the getter and setter methods looking quite similar. To avoid this repetition, you can use a descriptor instead of a property.

A descriptor is a class that implements the descriptor protocol , which consists of four special methods :

  • .__get__() runs when you access the attribute represented by the descriptor.
  • .__set__() runs when you use the attribute in an assignment statement.
  • .__delete__() runs when you use the attribute in a del statement.
  • .__set_name__() sets the attribute’s name, creating a name-aware attribute.

Here’s how your code may look if you use a descriptor to represent the coordinates of your Point class:

You’ve removed repetitive code by defining Coordinate as a descriptor that manages the input validation in a single place. Go ahead and run the following code to try out the new implementation of Point :

Great! The class works as expected. Thanks to the Coordinate descriptor, you now have a more concise and non-repetitive version of your original code.

Another way to fine-tune the operations behind an assignment statement is to provide a custom implementation of .__setitem__() in your class. You’ll use this method in classes representing mutable data collections, such as custom list-like or dictionary-like classes.

As an example, say that you need to create a dictionary-like class that stores its keys in lowercase letters:

In this example, you create a dictionary-like class by subclassing UserDict from collections . Your class implements a .__setitem__() method, which takes key and value as arguments. The method uses str.lower() to convert key into lowercase letters before storing it in the underlying dictionary.

Python implicitly calls .__setitem__() every time you use a key as the left operand in an assignment statement. This behavior allows you to tweak how you process the assignment of keys in your custom dictionary.

Implicit Assignments in Python

Python implicitly runs assignments in many different contexts. In most cases, these implicit assignments are part of the language syntax. In other cases, they support specific behaviors.

Whenever you complete an action in the following list, Python runs an implicit assignment for you:

  • Define or call a function
  • Define or instantiate a class
  • Use the current instance , self
  • Import modules and objects
  • Use a decorator
  • Use the control variable in a for loop or a comprehension
  • Use the as qualifier in with statements , imports, and try … except blocks
  • Access the _ special variable in an interactive session

Behind the scenes, Python performs an assignment in every one of the above situations. In the following subsections, you’ll take a tour of all these situations.

When you define a function, the def keyword implicitly assigns a function object to your function’s name. Here’s an example:

From this point on, the name greet refers to a function object that lives at a given memory address in your computer. You can call the function using its name and a pair of parentheses with appropriate arguments. This way, you can reuse greet() wherever you need it.

If you call your greet() function with fellow as an argument, then Python implicitly assigns the input argument value to the name parameter on the function’s definition. The parameter will hold a reference to the input arguments.

When you define a class with the class keyword, you’re assigning a specific name to a class object . You can later use this name to create instances of that class. Consider the following example:

In this example, the name User holds a reference to a class object, which was defined in __main__.User . Like with a function, when you call the class’s constructor with the appropriate arguments to create an instance, Python assigns the arguments to the parameters defined in the class initializer .

Another example of implicit assignments is the current instance of a class, which in Python is called self by convention. This name implicitly gets a reference to the current object whenever you instantiate a class. Thanks to this implicit assignment, you can access .name and .job from within the class without getting a NameError in your code.

Import statements are another variant of implicit assignments in Python. Through an import statement, you assign a name to a module object, class, function, or any other imported object. This name is then created in your current namespace so that you can access it later in your code:

In this example, you import the sys module object from the standard library and assign it to the sys name, which is now available in your namespace, as you can conclude from the second call to the built-in dir() function.

You also run an implicit assignment when you use a decorator in your code. The decorator syntax is just a shortcut for a formal assignment like the following:

Here, you call decorator() with a function object as an argument. This call will typically add functionality on top of the existing function, func() , and return a function object, which is then reassigned to the func name.

The decorator syntax is syntactic sugar for replacing the previous assignment, which you can now write as follows:

Even though this new code looks pretty different from the above assignment, the code implicitly runs the same steps.

Another situation in which Python automatically runs an implicit assignment is when you use a for loop or a comprehension. In both cases, you can have one or more control variables that you then use in the loop or comprehension body:

The memory address of control_variable changes on each iteration of the loop. This is because Python internally reassigns a new value from the loop iterable to the loop control variable on each cycle.

The same behavior appears in comprehensions:

In the end, comprehensions work like for loops but use a more concise syntax. This comprehension creates a new list of strings that mimic the output from the previous example.

The as keyword in with statements, except clauses, and import statements is another example of an implicit assignment in Python. This time, the assignment isn’t completely implicit because the as keyword provides an explicit way to define the target variable.

In a with statement, the target variable that follows the as keyword will hold a reference to the context manager that you’re working with. As an example, say that you have a hello.txt file with the following content:

You want to open this file and print each of its lines on your screen. In this case, you can use the with statement to open the file using the built-in open() function.

In the example below, you accomplish this. You also add some calls to print() that display information about the target variable defined by the as keyword:

This with statement uses the open() function to open hello.txt . The open() function is a context manager that returns a text file object represented by an io.TextIOWrapper instance.

Since you’ve defined a hello target variable with the as keyword, now that variable holds a reference to the file object itself. You confirm this by printing the object and its memory address. Finally, the for loop iterates over the lines and prints this content to the screen.

When it comes to using the as keyword in the context of an except clause, the target variable will contain an exception object if any exception occurs:

In this example, you run a division that raises a ZeroDivisionError . The as keyword assigns the raised exception to error . Note that when you print the exception object, you get only the message because exceptions have a custom .__str__() method that supports this behavior.

There’s a final detail to remember when using the as specifier in a try … except block like the one in the above example. Once you leave the except block, the target variable goes out of scope , and you can’t use it anymore.

Finally, Python’s import statements also support the as keyword. In this context, you can use as to import objects with a different name:

In these examples, you use the as keyword to import the numpy package with the np name and pandas with the name pd . If you call dir() , then you’ll realize that np and pd are now in your namespace. However, the numpy and pandas names are not.

Using the as keyword in your imports comes in handy when you want to use shorter names for your objects or when you need to use different objects that originally had the same name in your code. It’s also useful when you want to make your imported names non-public using a leading underscore, like in import sys as _sys .

The final implicit assignment that you’ll learn about in this tutorial only occurs when you’re using Python in an interactive session. Every time you run a statement that returns a value, the interpreter stores the result in a special variable denoted by a single underscore character ( _ ).

You can access this special variable as you’d access any other variable:

These examples cover several situations in which Python internally uses the _ variable. The first two examples evaluate expressions. Expressions always have a return value, which is automatically assigned to the _ variable every time.

When it comes to function calls, note that if your function returns a fruitful value, then _ will hold it. In contrast, if your function returns None , then the _ variable will remain untouched.

The next example consists of a regular assignment statement. As you already know, regular assignments don’t return any value, so the _ variable isn’t updated after these statements run. Finally, note that accessing a variable in an interactive session returns the value stored in the target variable. This value is then assigned to the _ variable.

Note that since _ is a regular variable, you can use it in other expressions:

In this example, you first create a list of values. Then you call len() to get the number of values in the list. Python automatically stores this value in the _ variable. Finally, you use _ to compute the mean of your list of values.

Now that you’ve learned about some of the implicit assignments that Python runs under the hood, it’s time to dig into a final assignment-related topic. In the following few sections, you’ll learn about some illegal and dangerous assignments that you should be aware of and avoid in your code.

Illegal and Dangerous Assignments in Python

In Python, you’ll find a few situations in which using assignments is either forbidden or dangerous. You must be aware of these special situations and try to avoid them in your code.

In the following sections, you’ll learn when using assignment statements isn’t allowed in Python. You’ll also learn about some situations in which using assignments should be avoided if you want to keep your code consistent and robust.

You can’t use Python keywords as variable names in assignment statements. This kind of assignment is explicitly forbidden. If you try to use a keyword as a variable name in an assignment, then you get a SyntaxError :

Whenever you try to use a keyword as the left operand in an assignment statement, you get a SyntaxError . Keywords are an intrinsic part of the language and can’t be overridden.

If you ever feel the need to name one of your variables using a Python keyword, then you can append an underscore to the name of your variable:

In this example, you’re using the desired name for your variables. Because you added a final underscore to the names, Python doesn’t recognize them as keywords, so it doesn’t raise an error.

Note: Even though adding an underscore at the end of a name is an officially recommended practice , it can be confusing sometimes. Therefore, try to find an alternative name or use a synonym whenever you find yourself using this convention.

For example, you can write something like this:

In this example, using the name booking_class for your variable is way clearer and more descriptive than using class_ .

You’ll also find that you can use only a few keywords as part of the right operand in an assignment statement. Those keywords will generally define simple statements that return a value or object. These include lambda , and , or , not , True , False , None , in , and is . You can also use the for keyword when it’s part of a comprehension and the if keyword when it’s used as part of a ternary operator .

In an assignment, you can never use a compound statement as the right operand. Compound statements are those that require an indented block, such as for and while loops, conditionals, with statements, try … except blocks, and class or function definitions.

Sometimes, you need to name variables, but the desired or ideal name is already taken and used as a built-in name. If this is your case, think harder and find another name. Don’t shadow the built-in.

Shadowing built-in names can cause hard-to-identify problems in your code. A common example of this issue is using list or dict to name user-defined variables. In this case, you override the corresponding built-in names, which won’t work as expected if you use them later in your code.

Consider the following example:

The exception in this example may sound surprising. How come you can’t use list() to build a list from a call to map() that returns a generator of square numbers?

By using the name list to identify your list of numbers, you shadowed the built-in list name. Now that name points to a list object rather than the built-in class. List objects aren’t callable, so your code no longer works.

In Python, you’ll have nothing that warns against using built-in, standard-library, or even relevant third-party names to identify your own variables. Therefore, you should keep an eye out for this practice. It can be a source of hard-to-debug errors.

In programming, a constant refers to a name associated with a value that never changes during a program’s execution. Unlike other programming languages, Python doesn’t have a dedicated syntax for defining constants. This fact implies that Python doesn’t have constants in the strict sense of the word.

Python only has variables. If you need a constant in Python, then you’ll have to define a variable and guarantee that it won’t change during your code’s execution. To do that, you must avoid using that variable as the left operand in an assignment statement.

To tell other Python programmers that a given variable should be treated as a constant, you must write your variable’s name in capital letters with underscores separating the words. This naming convention has been adopted by the Python community and is a recommendation that you’ll find in the Constants section of PEP 8 .

In the following examples, you define some constants in Python:

The problem with these constants is that they’re actually variables. Nothing prevents you from changing their value during your code’s execution. So, at any time, you can do something like the following:

These assignments modify the value of two of your original constants. Python doesn’t complain about these changes, which can cause issues later in your code. As a Python developer, you must guarantee that named constants in your code remain constant.

The only way to do that is never to use named constants in an assignment statement other than the constant definition.

You’ve learned a lot about Python’s assignment operators and how to use them for writing assignment statements . With this type of statement, you can create, initialize, and update variables according to your needs. Now you have the required skills to fully manage the creation and mutation of variables in your Python code.

In this tutorial, you’ve learned how to:

  • Write assignment statements using Python’s assignment operators
  • Work with augmented assignments in Python
  • Explore assignment variants, like assignment expression and managed attributes
  • Identify illegal and dangerous assignments in Python

Learning about the Python assignment operator and how to use it in assignment statements is a fundamental skill in Python. It empowers you to write reliable and effective Python code.

🐍 Python Tricks 💌

Get a short & sweet Python Trick delivered to your inbox every couple of days. No spam ever. Unsubscribe any time. Curated by the Real Python team.

Python Tricks Dictionary Merge

About Leodanis Pozo Ramos

Leodanis Pozo Ramos

Leodanis is an industrial engineer who loves Python and software development. He's a self-taught Python developer with 6+ years of experience. He's an avid technical writer with a growing number of articles published on Real Python and other sites.

Each tutorial at Real Python is created by a team of developers so that it meets our high quality standards. The team members who worked on this tutorial are:

Aldren Santos

Master Real-World Python Skills With Unlimited Access to Real Python

Join us and get access to thousands of tutorials, hands-on video courses, and a community of expert Pythonistas:

Join us and get access to thousands of tutorials, hands-on video courses, and a community of expert Pythonistas:

What Do You Think?

What’s your #1 takeaway or favorite thing you learned? How are you going to put your newfound skills to use? Leave a comment below and let us know.

Commenting Tips: The most useful comments are those written with the goal of learning from or helping out other students. Get tips for asking good questions and get answers to common questions in our support portal . Looking for a real-time conversation? Visit the Real Python Community Chat or join the next “Office Hours” Live Q&A Session . Happy Pythoning!

Keep Learning

Related Topics: intermediate best-practices python

Keep reading Real Python by creating a free account or signing in:

Already have an account? Sign-In

Almost there! Complete this form and click the button below to gain instant access:

Python's Assignment Operator: Write Robust Assignments (Source Code)

🔒 No spam. We take your privacy seriously.

assignment questions in python

21 Python for Loop Exercises and Examples

In Python programming, we use for loops  to repeat some code a certain number of times. It allows us to execute a statement or a group of statements multiple times by reducing the burden of writing several lines of code.

1. Python for loop to iterate through the letters in a word

2. python for loop using the range() function, 3. python for loop to iterate through a list, 4. python for loop to iterate through a dictionary, 5. python for loop using the zip() function for parallel iteration, 6. using else statement inside a for loop in python, 7. nested for loops in python (one loop inside another loop), 8. using break statement inside a for loop in python, 9. using continue statement inside a for loop in python, 10. python for loop to count the number of elements in a list, 11. python for loop to find the sum of all numbers in a list, 12. python for loop to find the multiples of 5 in a list, 13. python for loop to print a triangle of stars, 14. python for loop to copy elements from one list to another, 15. python for loop to find the maximum element in a list, 16. python for loop to find the minimum element in a list, 17. python for loop to sort the numbers in a list in ascending order, 18. python for loop to sort the numbers in a list in descending order, 19. python for loop to print the multiples of 3 using range() function, 20. python for loop to print the multiples of 5 using range() function, 21. python for loop to print the numbers in reverse order using range() function.

I hope this article was helpful. Check out my post on  18 Python while Loop Examples .

3 thoughts on “ 21 Python for Loop Exercises and Examples ”

we need some more difficult problems. please give some different questions.

myfamily = { “child1” : { “name” : “Emil”, “year” : 2004 }, “child2” : { “name” : “Tobias”, “year” : 2007 }, “child3” : { “name” : “Linus”, “year” : 2011 } }

Leave a Reply Cancel reply

Save my name and email in this browser for the next time I comment.

Recent Posts

Say "Hello, World!" With Python Easy Max Score: 5 Success Rate: 96.19%

Python if-else easy python (basic) max score: 10 success rate: 89.61%, arithmetic operators easy python (basic) max score: 10 success rate: 97.34%, python: division easy python (basic) max score: 10 success rate: 98.67%, loops easy python (basic) max score: 10 success rate: 98.07%, write a function medium python (basic) max score: 10 success rate: 90.28%, print function easy python (basic) max score: 20 success rate: 97.30%, list comprehensions easy python (basic) max score: 10 success rate: 97.64%, find the runner-up score easy python (basic) max score: 10 success rate: 94.21%, nested lists easy python (basic) max score: 10 success rate: 91.80%, cookie support is required to access hackerrank.

Seems like cookies are disabled on this browser, please enable them to open this website

  • Python Course
  • 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

Assignment Operators in Python

The Python Operators are used to perform operations on values and variables. These are the special symbols that carry out arithmetic, logical, and bitwise computations. The value the operator operates on is known as the Operand. Here, we will cover Different Assignment operators in Python .

Operators

=

Assign the value of the right side of the expression to the left side operandc = a + b 


+=

Add right side operand with left side operand and then assign the result to left operanda += b   

-=

Subtract right side operand from left side operand and then assign the result to left operanda -= b  


*=

Multiply right operand with left operand and then assign the result to the left operanda *= b     


/=

Divide left operand with right operand and then assign the result to the left operanda /= b


%=

Divides the left operand with the right operand and then assign the remainder to the left operanda %= b  


//=

Divide left operand with right operand and then assign the value(floor) to left operanda //= b   


**=

Calculate exponent(raise power) value using operands and then assign the result to left operanda **= b     


&=

Performs Bitwise AND on operands and assign the result to left operanda &= b   


|=

Performs Bitwise OR on operands and assign the value to left operanda |= b    


^=

Performs Bitwise XOR on operands and assign the value to left operanda ^= b    


>>=

Performs Bitwise right shift on operands and assign the result to left operanda >>= b     


<<=

Performs Bitwise left shift on operands and assign the result to left operanda <<= b 


:=

Assign a value to a variable within an expression

a := exp

Here are the Assignment Operators in Python with examples.

Assignment Operator

Assignment Operators are used to assign values to variables. This operator is used to assign the value of the right side of the expression to the left side operand.

Addition Assignment Operator

The Addition Assignment Operator is used to add the right-hand side operand with the left-hand side operand and then assigning the result to the left operand.

Example: In this code we have two variables ‘a’ and ‘b’ and assigned them with some integer value. Then we have used the addition assignment operator which will first perform the addition operation and then assign the result to the variable on the left-hand side.

S ubtraction Assignment Operator

The Subtraction Assignment Operator is used to subtract the right-hand side operand from the left-hand side operand and then assigning the result to the left-hand side operand.

Example: In this code we have two variables ‘a’ and ‘b’ and assigned them with some integer value. Then we have used the subtraction assignment operator which will first perform the subtraction operation and then assign the result to the variable on the left-hand side.

M ultiplication Assignment Operator

The Multiplication Assignment Operator is used to multiply the right-hand side operand with the left-hand side operand and then assigning the result to the left-hand side operand.

Example: In this code we have two variables ‘a’ and ‘b’ and assigned them with some integer value. Then we have used the multiplication assignment operator which will first perform the multiplication operation and then assign the result to the variable on the left-hand side.

D ivision Assignment Operator

The Division Assignment Operator is used to divide the left-hand side operand with the right-hand side operand and then assigning the result to the left operand.

Example: In this code we have two variables ‘a’ and ‘b’ and assigned them with some integer value. Then we have used the division assignment operator which will first perform the division operation and then assign the result to the variable on the left-hand side.

M odulus Assignment Operator

The Modulus Assignment Operator is used to take the modulus, that is, it first divides the operands and then takes the remainder and assigns it to the left operand.

Example: In this code we have two variables ‘a’ and ‘b’ and assigned them with some integer value. Then we have used the modulus assignment operator which will first perform the modulus operation and then assign the result to the variable on the left-hand side.

F loor Division Assignment Operator

The Floor Division Assignment Operator is used to divide the left operand with the right operand and then assigs the result(floor value) to the left operand.

Example: In this code we have two variables ‘a’ and ‘b’ and assigned them with some integer value. Then we have used the floor division assignment operator which will first perform the floor division operation and then assign the result to the variable on the left-hand side.

Exponentiation Assignment Operator

The Exponentiation Assignment Operator is used to calculate the exponent(raise power) value using operands and then assigning the result to the left operand.

Example: In this code we have two variables ‘a’ and ‘b’ and assigned them with some integer value. Then we have used the exponentiation assignment operator which will first perform exponent operation and then assign the result to the variable on the left-hand side.

Bitwise AND Assignment Operator

The Bitwise AND Assignment Operator is used to perform Bitwise AND operation on both operands and then assigning the result to the left operand.

Example: In this code we have two variables ‘a’ and ‘b’ and assigned them with some integer value. Then we have used the bitwise AND assignment operator which will first perform Bitwise AND operation and then assign the result to the variable on the left-hand side.

Bitwise OR Assignment Operator

The Bitwise OR Assignment Operator is used to perform Bitwise OR operation on the operands and then assigning result to the left operand.

Example: In this code we have two variables ‘a’ and ‘b’ and assigned them with some integer value. Then we have used the bitwise OR assignment operator which will first perform bitwise OR operation and then assign the result to the variable on the left-hand side.

Bitwise XOR Assignment Operator 

The Bitwise XOR Assignment Operator is used to perform Bitwise XOR operation on the operands and then assigning result to the left operand.

Example: In this code we have two variables ‘a’ and ‘b’ and assigned them with some integer value. Then we have used the bitwise XOR assignment operator which will first perform bitwise XOR operation and then assign the result to the variable on the left-hand side.

Bitwise Right Shift Assignment Operator

The Bitwise Right Shift Assignment Operator is used to perform Bitwise Right Shift Operation on the operands and then assign result to the left operand.

Example: In this code we have two variables ‘a’ and ‘b’ and assigned them with some integer value. Then we have used the bitwise right shift assignment operator which will first perform bitwise right shift operation and then assign the result to the variable on the left-hand side.

Bitwise Left Shift Assignment Operator

The Bitwise Left Shift Assignment Operator is used to perform Bitwise Left Shift Opertator on the operands and then assign result to the left operand.

Example: In this code we have two variables ‘a’ and ‘b’ and assigned them with some integer value. Then we have used the bitwise left shift assignment operator which will first perform bitwise left shift operation and then assign the result to the variable on the left-hand side.

Walrus Operator

The Walrus Operator in Python is a new assignment operator which is introduced in Python version 3.8 and higher. This operator is used to assign a value to a variable within an expression.

Example: In this code, we have a Python list of integers. We have used Python Walrus assignment operator within the Python while loop . The operator will solve the expression on the right-hand side and assign the value to the left-hand side operand ‘x’ and then execute the remaining code.

Assignment Operators in Python – FAQs

What are assignment operators in python.

Assignment operators in Python are used to assign values to variables. These operators can also perform additional operations during the assignment. The basic assignment operator is = , which simply assigns the value of the right-hand operand to the left-hand operand. Other common assignment operators include += , -= , *= , /= , %= , and more, which perform an operation on the variable and then assign the result back to the variable.

What is the := Operator in Python?

The := operator, introduced in Python 3.8, is known as the “walrus operator”. It is an assignment expression, which means that it assigns values to variables as part of a larger expression. Its main benefit is that it allows you to assign values to variables within expressions, including within conditions of loops and if statements, thereby reducing the need for additional lines of code. Here’s an example: # Example of using the walrus operator in a while loop while (n := int(input("Enter a number (0 to stop): "))) != 0: print(f"You entered: {n}") This loop continues to prompt the user for input and immediately uses that input in both the condition check and the loop body.

What is the Assignment Operator in Structure?

In programming languages that use structures (like C or C++), the assignment operator = is used to copy values from one structure variable to another. Each member of the structure is copied from the source structure to the destination structure. Python, however, does not have a built-in concept of ‘structures’ as in C or C++; instead, similar functionality is achieved through classes or dictionaries.

What is the Assignment Operator in Python Dictionary?

In Python dictionaries, the assignment operator = is used to assign a new key-value pair to the dictionary or update the value of an existing key. Here’s how you might use it: my_dict = {} # Create an empty dictionary my_dict['key1'] = 'value1' # Assign a new key-value pair my_dict['key1'] = 'updated value' # Update the value of an existing key print(my_dict) # Output: {'key1': 'updated value'}

What is += and -= in Python?

The += and -= operators in Python are compound assignment operators. += adds the right-hand operand to the left-hand operand and assigns the result to the left-hand operand. Conversely, -= subtracts the right-hand operand from the left-hand operand and assigns the result to the left-hand operand. Here are examples of both: # Example of using += a = 5 a += 3 # Equivalent to a = a + 3 print(a) # Output: 8 # Example of using -= b = 10 b -= 4 # Equivalent to b = b - 4 print(b) # Output: 6 These operators make code more concise and are commonly used in loops and iterative data processing.

author

Please Login to comment...

Similar reads.

  • Python-Operators
  • Best Twitch Extensions for 2024: Top Tools for Viewers and Streamers
  • Discord Emojis List 2024: Copy and Paste
  • Best Adblockers for Twitch TV: Enjoy Ad-Free Streaming in 2024
  • PS4 vs. PS5: Which PlayStation Should You Buy in 2024?
  • 10 Best Free VPN Services in 2024

Improve your Coding Skills with Practice

 alt=

What kind of Experience do you want to share?

Python Programming

Python if else, for loop, and range() Exercises with Solutions

Updated on:  September 3, 2024 | 298 Comments

Branching and looping techniques are used in Python to decide and control the flow of a program. A good understanding of loops and if-else statements is necessary to write efficient code in Python .

This Python loop exercise contains 18 different loop programs and challenges to solve if-else conditions, for loops, range() functions, and while loops.

  • Solutions are provided for all questions and tested on Python 3.
  • Use Online Code Editor to solve exercise questions.

Refer to the following tutorials to solve this exercise

  • Control flow statements : Use the if-else statements in Python for conditional decision-making.
  • for loop : To iterate over a sequence of elements such as a list or string.
  • range() function : Using a for loop with range(), we can repeat an action a specific number of times.
  • while loop : To execute a code block repeatedly, as long as the condition is True.
  • Break and Continue : To alter the loop’s execution in a particular manner.
  • Nested loop : A loop inside a loop is known as a nested loop.

Also Read : Python Loop Quiz

Let us know if you have any alternative solutions. It will help other developers.

Table of contents

Exercise 1: print first 10 natural numbers using while loop, exercise 2: print the following pattern, exercise 3: calculate sum of all numbers from 1 to a given number.

Exercise 4: Print multiplication table of a given number

Exercise 5: Display numbers from a list using a loop

Exercise 6: count the total number of digits in a number, exercise 7: print the following pattern, exercise 8: print list in reverse order using a loop, exercise 9: display numbers from -10 to -1 using for loop, exercise 10: display a message “done” after the successful execution of the for loop, exercise 11: print all prime numbers within a range, exercise 12: display fibonacci series up to 10 terms, exercise 13: find the factorial of a given number, exercise 14: reverse a integer number, exercise 15: print elements from a given list present at odd index positions, exercise 16: calculate the cube of all numbers from 1 to a given number, exercise 17: find the sum of the series up to n terms, exercise 18: print the following pattern.

Help : while loop in Python

Expected output:

Write a Python code to print the following number pattern using a loop.

  • Print Patterns In Python
  • Nested loops in Python
  • Decide the row count, i.e., 5, because the pattern contains five rows
  • Run the outer loop 5 times using for loop and range() function
  • Run inner loop i+1 times using for loop and range() function
  • In the first iteration of the outer loop, the inner loop will execute one time
  • In the second iteration of the outer loop, the inner loop will execute 2 time
  • In the third iteration of the outer loop, the inner loop will execute 3 times, and so on, till row 5
  • print the value of j in each iteration of the inner loop ( j is the inner loop iterator variable)
  • Display an empty line at the end of each iteration of the outer loop (empty line after each row)

Write a Python program to accept a number from a user and calculate the sum of all numbers from 1 to a given number

For example, if the user entered 10 , the output should be 55 ( 1+2+3+4+5+6+7+8+9+10 )

Expected Output :

  • Accept input from user in Python
  • Calculate sum and average in Python

Approach 1 : Use for loop and range() function

  • Create variable s = 0 to store the sum of all numbers
  • Use Python 3’s built-in function input() to take input from a user
  • Convert user input to the integer type using the int() constructor and save it to a variable n
  • Run loop n times using for loop and range() function
  • In each iteration of a loop, add a current number ( i ) to variable s
  • Use the print() function to display the variable s on screen

Approach 2 : Use the built-in function sum() . The sum() function calculates the addition of all numbers from 1 to a given number.

Solution 1 : Using for loop and range() function

Solution 2 : Using the built-in function sum()

Expected output is:

You can use a simple for loop to generate the multiplication table for a specific number.

  • Set n = 2 .
  • Use for loop to iterate the first 10 numbers.
  • In each iteration, multiply the current number by 2 ( p = n*i ). Now print p

Write a Python program to display only those numbers from a list that satisfy the following conditions

  • The number must be divisible by five
  • If the number is greater than 150, then skip it and move to the following number
  • If the number is greater than 500, then stop the loop

Refer : break and continue in Python

  • Use for loop to iterate each item of a list
  • Use a break statement to break the loop if the current number is greater than 500
  • use the continue statement to move to the following number if the current number is greater than 150
  • Use the number % 5 == 0 condition to check if the number is divisible by 5

Write a Python program to count the total number of digits in a number using a while loop .

For example, the number is 75869 , so the output should be 5 .

  • Set counter = 0
  • Run while loop till number != 0
  • Reduce the last digit from the number using floor division ( number = number // 10 )
  • Increment counter by 1
  • print counter

Write a Python program to print the reverse number pattern using a for loop.

Refer : Print patterns in Python

  • Setting the row value to 5 is crucial, as the pattern we’re working with has five rows. Using the for loop and range() function, create an outer loop that iterates numbers from 1 to 5.
  • The outer loop controls the number of iterations of the inner loop. For each outer loop iteration, the inner loop iteration is reduced by i , the outer loop’s current number.
  • In each iteration of the inner loop, print the iterator variable of the inner loop ( j )
  • In the first iteration of the outer loop, the inner loop executes five times.
  • In the second iteration of the outer loop, the inner loop executes four times.
  • In the last iteration of the outer loop, the inner loop will execute only once.

Approach 1 : Use the built-in function reversed() to reverse the list

Approach 2 : Use for loop and the len() function

  • Get the size of a list using the len(list1) function
  • Use for loop and reverse range() to iterate index numbers in reverse order, starting from length-1 to 0. In each iteration, i will be reduced by 1
  • In each iteration, print list items using list1[i] . i is the current value of the index

Solution 1 : Using a reversed() function and for loop

Solution 2 : Using for loop and the len() function

See: Reverse range

For example, the following loop will execute without any error.

Python allows us to use an else block with a for loop like the if statement. The loop can have the else block, which will be executed when it terminates normally. See else block in for loop .

Note : A Prime Number is a number that cannot be made by multiplying other whole numbers. A prime number is a natural number greater than 1 that is not a product of two smaller natural numbers.

  • 6 is not a prime number because it can be made by 2×3 = 6
  • 37 is a prime number because no other whole numbers multiply to make it.

Have you ever wondered about the Fibonacci Sequence? It’s a series of numbers in which the next number is found by adding up the two numbers before it. The first two numbers are 0 and 1.

For example, 0, 1, 1, 2, 3, 5, 8, 13, 21. The next number in this series is 13 + 21 = 34.

  • Set num1 = 0 and num2 = 1 (first two numbers of the sequence)
  • Run the loop 10 times
  • print num1 as the current number of the sequence
  • Add the last two numbers to get the following number result = num1 + num2
  • update values of num1 and num2 . Set num1 = num2 and num2 = res ult

Write a Python program to use for loop to find the factorial of a given number.

The factorial (symbol: ! ) means multiplying all numbers from the chosen number down to 1.

For example , a factorial of 5! is 5 × 4 × 3 × 2 × 1 = 120

  • Set variable factorial = 1 to store the factorial of a given number
  • Iterate numbers starting from 1 to the given number n using for loop and range() function. (here, the loop will run five times because n is 5)
  • In each iteration, multiply the factorial by the current number and assign it again to a factorial variable ( factorial = factorial *i )
  • After the loop completes, print factorial

Note : The list index always starts at 0

Use list slicing. We can access a list of elements from a list using list slicing.

Write a Python program to print the cube of all numbers from 1 to a given number

input_number = 6

  • Iterate numbers from 1 to n using for loop and range() function
  • In each iteration of a loop, calculate the cube of a current number ( i ) by multiplying itself three times ( cube = i * i* i)

Write a program to calculate the sum of series up to n terms. For example, if n = 5 the series will become 2 + 22 + 222 + 2222 + 22222 = 24690

Write a program to print the following start pattern using the for loop

Refer : Print Patterns In Python

Use two for loops. The first loop will print the upper pattern, and the second loop will print the lower pattern.

First Pattern :

Second Pattern :

Did you find this page helpful? Let others know about it. Sharing helps me continue to create free Python resources.

About Vishal

assignment questions in python

I’m  Vishal Hule , the Founder of PYnative.com. As a Python developer, I enjoy assisting students, developers, and learners. Follow me on  Twitter .

Related Tutorial Topics:

Python exercises and quizzes.

Free coding exercises and quizzes cover Python basics, data structure, data analytics, and more.

  • 15+ Topic-specific Exercises and Quizzes
  • Each Exercise contains 10 questions
  • Each Quiz contains 12-15 MCQ

assignment questions in python

June 28, 2024 at 4:53 pm

lol nice job author really good resourses

assignment questions in python

June 22, 2024 at 8:13 pm

This is my code:

numbers = [12, 75, 150, 180, 145, 525, 50] lst = []

for i in numbers: if i > 150: continue elif i > 500: break elif i%5 ==0: print(i)

But the result show: 75 150 145 50

Why does 50 appear?

June 28, 2024 at 4:51 pm

elif i > 500: break

shoud be above the first if statement

assignment questions in python

August 13, 2024 at 11:45 pm

Break will stop the execution so it wont read the 50 in the list

assignment questions in python

June 12, 2024 at 8:17 am

Ex 7 could be as simple as

for x in range(5,0,-1): for y in range(x): print(x-y,end=” “) print(“”)

assignment questions in python

March 12, 2024 at 2:37 am

Found a shorter answer to Example 18:

rows = 5 for x in range(0, rows + 1): print(x * ‘*’)

for x in range(rows – 1, 0, -1): print(x * ‘*’)

assignment questions in python

August 28, 2024 at 10:37 am

rows = 5 for x in range(0, rows + 2): if x == 6: for x in range(rows-1, 0, -1):

print(x * ‘*’)

assignment questions in python

December 22, 2023 at 8:07 pm

Exercise 15, this is an alternative way to solve this question

list1 = [10, 20, 30, 40, 50, 60, 70, 80, 90, 100] for i in range(len(list1)): if i > 0: if i % 2 != 0 : print(list1[i],end = ” “)

December 22, 2023 at 6:57 pm

for Q14 i dont feel there would be any need to loop through the given number you can always just convert it into a string the reverse it back in to an int, if there is any benefit of using a loop in this case , maybe the time complexity can be affected please do comment below:

num = 76542 newnum = str(num) newnum = newnum[::-1] intnum = int(newnum) print(intnum)

December 16, 2023 at 2:23 pm

fun little use of lists for i in range(10,0,-1): print(i*-1) #or list1 = [] for i in range(1,11): i = i*-1 list1.append(i) for i in reversed(list1): print(i)

December 16, 2023 at 2:17 pm

list1 = [10,20,30,40,50] for i in reversed(list1): print(i) print(” “) #or for i in list1[::-1]: print(i)

December 16, 2023 at 1:39 pm

exercise 2 would recommend using the variables for readability but this is an alternative way to use the outer loop

for i in range(6,1,-1): for j in range(i-1,0,-1): print(j, end = “”) print()

December 16, 2023 at 11:58 am

Q5 i feel like the output should include 50 , because all the conditions agree to that user = int(input(“enter the number you want to calculate the sum for: “)) for i in range(1,11): print(user*i)

December 16, 2023 at 11:24 am

for i in range(1,7): for j in range(1,i): print(j , end = ” “) print()

assignment questions in python

December 3, 2023 at 6:52 am

Another solution for exercise 18

rows = 5 middle_row = rows // 2 + 1

decrement = 0 for i in range(1, rows + 1): if i > middle_row: decrement += 2 print(“* ” * (i – decrement))

In my personal opinion, I’m not really a huge fan of nested for loops unless absolutely necessary. In my experience working on independent projects, nested for loops tend to hurt the overall performance of the program, because scaling the operation gets overwhelming for the program to handle. In a small example like this, it doesn’t really matter.

I remember one time I was building a game in pygame, and I had a nested for loop to iterate over all the enemy objects on screen. I started running into issues when the program couldn’t iterate over every enemy fast enough, and it was causing a lot of weird bugs.

My solution has the same benefits of scalability as the provided solution but is able to execute more efficiently being in a single for loop, rather than having to use 2 nested for loops to achieve the same thing.

assignment questions in python

December 2, 2023 at 11:35 pm

Exercise 17:

n = 5 x = str(2) total = 0 for i in range(1, n+1) : z = x * i total = int(z) + total print(total)

assignment questions in python

November 4, 2023 at 12:40 pm

exercise 10

for i in range(1, 5+1): if i == 5: print(“done!”) break print(i)

assignment questions in python

October 11, 2023 at 11:22 am

x = 75869 print(len(str(x)))

assignment questions in python

November 14, 2023 at 4:53 am

while(Num!=0)

October 11, 2023 at 11:19 am

Exercise 6:

for i in range(5, 0, -1): for j in range(i, 0, -1): print(j, end = ” “) print()

assignment questions in python

October 26, 2023 at 9:30 pm

excelent very good

assignment questions in python

October 6, 2023 at 12:38 am

my solution to exercize 17 n = 5 sum = 0 num = 0 for i in range(n): for j in range(i+1): sum += 2*10**j num += sum sum = 0 print(num)

October 6, 2023 at 12:36 am

n = 5 sum = 0 num = 0 for i in range(n): for j in range(i+1): sum += 2*10**j num += sum sum = 0 print(num)

October 26, 2023 at 9:32 pm

PLISSS in SPANISHH. PLISSS. I NO SABER ENGLISH, TEN KIU

assignment questions in python

January 18, 2024 at 4:13 pm

assignment questions in python

October 1, 2023 at 11:40 am

question 4 print(“table”) for i in range(2,22,2): print(i)

assignment questions in python

September 29, 2023 at 4:47 am

#1 num =1 while num > 0: print(num) num += 1

if num == 11: break

assignment questions in python

September 26, 2023 at 5:08 pm

Exercise 18

for i in range(1,10): z=0 if i<=5: while z<i: print('*',end=" ") z+=1 print("\n") else: while z<10-i: print('*',end=" ") z+=1 print("\n")

assignment questions in python

September 20, 2023 at 10:57 am

Thank you so so so much for these exercises. i learned a lot! godbless you

assignment questions in python

September 19, 2023 at 4:45 pm

for Exercise 18:

max=int(input(“Enter max number of * in one line: “)) for i in range(-max,max): n=max-abs(i) [print(“*”,end=” “) for x in range(n)] print(“”)

assignment questions in python

September 14, 2023 at 2:28 am

x = input(“Enter number : “) z = str(x) count = 0

while count < len(z): count += 1

print(f"total digits are {count}")

assignment questions in python

August 26, 2023 at 10:22 pm

Thank you, this is very helpful

assignment questions in python

August 21, 2023 at 10:31 am

hello,I hope you are good. exersices were so great and useful! really thank you so much and i wish the best things in world for you good luck

assignment questions in python

July 30, 2023 at 1:45 pm

# mlist = [0,1] # for i in range(0,8): # sum = mlist[i]+mlist[i+1] # mlist.append(sum) # print(f’the mlist is {mlist}’)

July 30, 2023 at 1:43 pm

# mlist = [0,1] # for i in range(0,8): # sum = mlist[i]+mlist[i+1] # mlist.append(sum) # print(mlist)

assignment questions in python

July 17, 2023 at 5:01 pm

num=int(input("please give the number to find the cubes")) for i in range(num+1): cube=i**3 print(f"the cube of {i} is:",cube)

July 12, 2023 at 9:57 pm

nu=int(input("enter the number tp print the table ")) for i in range(1,11): print(f"{nu} * {i}={i*nu}")

assignment questions in python

June 11, 2023 at 8:47 pm

# Exercise 3: Calculate the sum of all numbers from 1 to a given number

Correction sum =0

for i in range(5): x = int(input("Enter a Number: ")) sum += x print("\n") print(sum)

assignment questions in python

May 27, 2023 at 1:28 am

I would just like to thank you for the great job you’ve done here. Very helpful.

assignment questions in python

May 4, 2023 at 10:11 am

for ques 6, i solved like the below prog. I want to know is that correct

def count_n(n): a=list(enumerate(str(n))) print(len(a))

assignment questions in python

March 19, 2023 at 11:45 pm

Exercise 5: Display numbers from a list using loop

Why the solution exclude 50?

I wrote this and the result was: 75 150 145 50

for it in numbers: if it % 5 != 0: continue if it > 150: continue if it > 500: break print(it)

assignment questions in python

March 20, 2023 at 9:45 am

because 525 continued the loop instead of ending it.

assignment questions in python

March 2, 2023 at 3:40 pm

rng = list(range(1, n)) + list(range(n, 0, -1)) for i in rng: print('* ' * i)

assignment questions in python

January 14, 2023 at 10:56 am

n=int(input("enter number: ")) sum=0 for i in range(1,n+1): sum=int(start*i)+sum if i==n: print(start*i,"=",sum) else: print(start*i,"+",end=" ")

January 14, 2023 at 10:55 am

Qn 18: str="*" for i in range(1,5): print(str*i) for j in range(5,-1,-1): print(str*j)

assignment questions in python

January 12, 2023 at 10:31 am

list1 = [10, 20, 30, 40, 50] for i in list1[::-1]: print(i)

assignment questions in python

December 31, 2022 at 1:58 pm

USING RECURSION

def fact(num): if num > 1: return (num*fact(num-1)) return num num=int(input("Enter the number")) ans=fact(num) print(ans)

assignment questions in python

November 27, 2022 at 11:11 pm

# pattern 18

end = 6 for i in range (0,end+1): if i=(end/2): for z in range (end-i,0,-1): print("*",end=" ") print()

assignment questions in python

November 12, 2022 at 7:41 pm

Print the list in reverse order using a loop

l = [10, 20, 30, 40, 50] n = l[::-1] for i in n: print(i)

assignment questions in python

May 27, 2023 at 7:33 pm

l = [10, 20, 30, 40, 50] New list=reversed(I) print( New list)

November 12, 2022 at 7:20 pm

n = [12, 75, 150, 180, 145, 525, 50] for i in n: if i % 5 == 0 and i 500: break

assignment questions in python

December 20, 2022 at 3:38 pm

#18 Pattern:(my code)

for i in range(0,6): for j in range(1,i+1): print("*",end=" ") print("") for i in range(0,6): for j in range(1,5-i): print("*",end=" ") print("")

assignment questions in python

June 20, 2023 at 8:23 am

That’s the wrong code it does nothing other than breaking loop

assignment questions in python

November 9, 2022 at 7:00 pm

Exercise 14:

Reverse an integer number

The solution not entirely correct if your number ends with 0

assignment questions in python

June 14, 2023 at 2:04 am

Most integer types in virtually every programming language do not show leading zeroes. If you want to reverse it with zeroes, convert to a string first. If you want leading zeroes you need to specify how many places you want to show.

Internally 11120 is stored as 00000000000000000010101101110000, it’s just shown as 11120 for readability.

assignment questions in python

November 3, 2022 at 1:21 pm

Question no.15 : Use a loop to display elements from a given list present at odd index positions.

nums = [24,18,6,13,16,7,69] i = 1 while i < len(nums): print(nums[i]) i = i + 2

assignment questions in python

November 3, 2022 at 5:03 am

Exercise 7: number = int(input('Number: '))

for i in range(number): for j in range(number - i): print(number - i - j, end = ' ') print()

assignment questions in python

October 27, 2022 at 5:30 am

Exercise 18, with user input:

maxnum = int(input("enter the maximum number of stars: ")) start_range = maxnum * -1 + 1 for i in range(start_range,maxnum,1): print ("\n") num_of_stars = maxnum - abs(i) for x in range(num_of_stars): print ("* ", end="")

assignment questions in python

September 25, 2022 at 10:49 pm

for the number 2 problem, u really don’t need any nested loop

assignment questions in python

October 31, 2022 at 3:14 am

For i in range(0,6,1): Print(i*"*") For j in range(6,0,-1): Print(j*"*")

assignment questions in python

September 10, 2022 at 6:53 pm

Exe 18 (my idea)

why my pre tag doesn’t work

assignment questions in python

September 19, 2022 at 6:21 pm

September 19, 2022 at 6:22 pm

******** Q13*********

assignment questions in python

March 21, 2023 at 2:16 pm

It can be dome without an else statement

factorial = 1 n = int(input("number: "))

for i in range(1 , n+1): factorial = factorial * i print(factorial)

assignment questions in python

September 4, 2022 at 10:55 pm

Question Number 18:

assignment questions in python

September 1, 2022 at 6:30 pm

EXERCISE 15

September 1, 2022 at 2:57 pm

Exercise 14 I converted the num to str to apply a list reversed function. I think I understood this better

September 19, 2022 at 6:46 pm

Did 14 like this

assignment questions in python

August 27, 2024 at 11:44 am

I DID LIKE THIS :

num = 76542 string = str(num) txt = string[::-1] rnum = int(txt) print(rnum)

assignment questions in python

August 29, 2022 at 11:40 pm

for exercise 18, scalable answer:

assignment questions in python

October 3, 2022 at 3:19 pm

October 3, 2022 at 3:22 pm

assignment questions in python

August 26, 2022 at 11:08 pm

For Exercise 8, Solution 3

August 26, 2022 at 8:59 pm

For exercise 4 :

assignment questions in python

August 24, 2022 at 11:06 am

Exercis2 my solution:

assignment questions in python

August 21, 2022 at 11:50 pm

Exercise 5:

It seems your solution is a mistake. The break should be a nested loop so that the loop will continue to all the list:

assignment questions in python

September 27, 2022 at 8:31 pm

The exercise specifically says to end the loop if the number is greater than 500. Not continue evaluating the remaining numbers. His “expected output” shows this. > 500 ends the loop/script. >150 skips and continues

assignment questions in python

February 26, 2023 at 10:01 pm

How come 180 is missing the out of this program?

numbers = [12, 75, 150, 180, 145, 525, 50] # iterate each item of a list for item in numbers: if item > 500: break elif item > 150: continue # check if number is divisible by 5 elif item % 5 == 0: print(item)

assignment questions in python

September 21, 2023 at 9:27 pm

As it says in the instructions, elements greater than 150 should not be printed.

assignment questions in python

August 20, 2022 at 6:09 pm

assignment questions in python

August 20, 2022 at 6:11 pm

thank you It’s 👍😊 <3

assignment questions in python

August 3, 2022 at 2:52 pm

question number 17. an alternative using nested loops

didn’t know we could do it at the beginning and at the end just once so did it for every line here is the “better to look” version

October 6, 2023 at 12:29 am

I did it like this

assignment questions in python

August 2, 2022 at 2:33 pm

solution for exercise number 15

August 1, 2022 at 3:26 pm

August 3, 2022 at 2:14 pm

lol dude i too did in the same way

August 1, 2022 at 3:25 pm

a more simplified silution for exercise 8

assignment questions in python

July 16, 2022 at 4:37 pm

assignment questions in python

July 1, 2022 at 8:29 pm

For Exercise 17

assignment questions in python

June 23, 2022 at 1:34 pm

question 14

assignment questions in python

June 16, 2022 at 9:52 pm

assignment questions in python

June 24, 2022 at 7:17 pm

The range of i must be star+1 Remaining code is good Excellent job there

June 16, 2022 at 9:49 pm

assignment questions in python

August 9, 2022 at 1:27 am

assignment questions in python

June 16, 2022 at 3:22 pm

assignment questions in python

June 13, 2022 at 4:39 pm

to reverse a string

assignment questions in python

May 18, 2022 at 3:57 pm

assignment questions in python

May 8, 2022 at 2:21 am

assignment questions in python

May 4, 2022 at 2:32 pm

for 18th problem

assignment questions in python

April 20, 2022 at 1:30 pm

in q6 why not display 50?

June 15, 2022 at 7:22 pm

SAME QUE BRO ANY ONE CAN EXPLAIN

assignment questions in python

June 24, 2022 at 5:58 am

you mean Question 5 with the List, program will break when it iterates over the list and find a number greater than 500 …525 precedes 50. program will terminate at 525.

assignment questions in python

March 18, 2022 at 3:34 am

#for 8th problem

assignment questions in python

April 22, 2022 at 7:11 pm

assignment questions in python

February 23, 2022 at 1:58 am

Q18 Alternate and Easy Solution

assignment questions in python

January 30, 2022 at 7:53 pm

There are N people in a party numbered 1 to N. Sruthi has K card with her. Starting with person A, she gives the cards one by one to the people in the party in the numbering order. A, A+1,A+2 ….N. 1,2…..A-1. your task is to output the number of the person who will get the last card. INPUT 1 3 3 2 OUTPUT 1 1

INPUT2 1 100 1 OUTPUT 1

kindly explain this question with a solution

assignment questions in python

May 10, 2022 at 1:24 pm

assignment questions in python

January 21, 2022 at 2:56 pm

Exercise 12

January 21, 2022 at 2:49 pm

assignment questions in python

January 6, 2022 at 12:27 am

assignment questions in python

December 31, 2021 at 11:47 pm

For exercise 17

assignment questions in python

December 28, 2021 at 11:11 pm

assignment questions in python

April 10, 2022 at 3:24 am

assignment questions in python

December 6, 2021 at 5:46 pm

Exercise 7 – An alternative using only 2 variables inside the for loops:

assignment questions in python

December 1, 2021 at 6:16 pm

assignment questions in python

November 12, 2021 at 8:57 pm

November 12, 2021 at 8:59 pm

November 5, 2021 at 1:06 pm

Exercise 8:

November 4, 2021 at 9:48 pm

Exercise 4 for any number

November 4, 2021 at 8:48 pm

assignment questions in python

October 21, 2021 at 12:36 am

assignment questions in python

October 16, 2021 at 7:24 pm

Q7. Print the following pattern.

assignment questions in python

October 4, 2021 at 2:05 pm

# Exercise 18: Print the following pattern

assignment questions in python

October 6, 2021 at 6:39 pm

I don’t think this is very efficient but that’s what I came up with haha

assignment questions in python

October 6, 2021 at 6:42 pm

Using if is unnecessary here my friend

assignment questions in python

September 9, 2021 at 2:58 am

Q 18 in very simple way:

assignment questions in python

September 17, 2021 at 2:45 am

assignment questions in python

October 14, 2021 at 10:53 am

assignment questions in python

August 24, 2021 at 2:23 pm

Exercise-9 Answer

assignment questions in python

September 9, 2021 at 6:16 am

August 23, 2021 at 9:39 pm

Exercise-5-Answer

August 23, 2021 at 9:36 pm

assignment questions in python

August 15, 2021 at 6:38 pm

Exercise 6: – Answer –

August 14, 2021 at 9:36 pm

Exercise 18: I believe this is easy.

assignment questions in python

August 19, 2021 at 2:39 pm

Also works, and I believe it’s faster ( O(n) ) because it only loops once, not twice. For clarification: I use a user input here for the number of columns for testing purposes, but you can easily set num to 5 to get exactly the pattern that was asked.

August 8, 2021 at 3:05 pm

Exercise 15: one more solution

August 8, 2021 at 2:57 pm

Exercise 14: Reverse a given integer number

August 8, 2021 at 1:29 pm

Exercise 10: this also works

August 8, 2021 at 12:32 pm

assignment questions in python

September 18, 2021 at 5:31 pm

But it works only for number 2, but we need a code that works for every number that the user input . try this code

assignment questions in python

July 17, 2021 at 3:06 pm

Another method for Exercise 8

assignment questions in python

August 6, 2021 at 4:19 pm

#another solution

July 17, 2021 at 3:05 pm

ANOTHER METHOD OF SOLVING PYTHON EXERCISE 8

assignment questions in python

July 15, 2021 at 11:07 pm

Explanation is very poor!! Need to change it.

assignment questions in python

July 14, 2021 at 6:41 pm

July 6, 2021 at 6:36 pm

Exercise 4: Print multiplication table of a given number:

will be perfect.

assignment questions in python

June 25, 2021 at 9:31 pm

Exercise 12 Solution:

assignment questions in python

June 23, 2021 at 4:29 am

For exercise 11, you actually only need to check for divisors up to the sqrt(num) . This is because any composite number has a factor less than the square root of itself. Minor improvement in the runtime, but thought I would mention it.

August 19, 2021 at 2:44 pm

Thank you, I didn’t know about that! This will probably be useful at some point. What I did was only check from 2 to the number – 1 (ommiting 1 and the number itself), which compared to the provided solution makes hardly any difference.

assignment questions in python

June 22, 2021 at 4:06 pm

for exercise 07:

assignment questions in python

July 31, 2021 at 1:34 am

assignment questions in python

June 14, 2021 at 1:01 pm

Another solution for Exercise 8:

June 13, 2021 at 5:50 am

For exercise 3, I found that I had to add float, e.g.

or I would get this error message with some ranges “ValueError: invalid literal for int() with base 10: “

assignment questions in python

June 12, 2021 at 1:48 pm

assignment questions in python

May 25, 2021 at 11:58 am

Another solution for Exercise 18

assignment questions in python

June 11, 2021 at 5:06 pm

Another solution for Question no -11

assignment questions in python

June 20, 2021 at 8:22 am

This is beautiful!

May 25, 2021 at 11:38 am

Exercise 14

assignment questions in python

June 26, 2021 at 7:26 pm

thanks for sharing this solution

assignment questions in python

May 2, 2021 at 11:57 am

We can also achieve the result using this code:

assignment questions in python

April 7, 2021 at 3:42 am

For Exercise 18:

Output: How many blocks do you want to add to your vertical pyramid?: 5

assignment questions in python

March 15, 2021 at 9:37 pm

#EXercise 18 less steps

assignment questions in python

June 26, 2021 at 2:13 am

This prints the pattern based on the distance (absolute value) from 5. Thus a simple algorithm.

March 15, 2021 at 9:20 pm

Exercise 17 #modified exercise 17 so that user can enter the no of rows and the starting value of the series

July 31, 2021 at 11:08 am

SMOOTH! THANK YOU!

March 15, 2021 at 8:49 pm

#EXercise 16

March 15, 2021 at 11:28 am

for ex 7 cant we use

assignment questions in python

March 9, 2021 at 10:31 am

# question 1

assignment questions in python

March 9, 2021 at 1:06 am

Are you also there on youtube

assignment questions in python

March 8, 2021 at 12:00 am

for example. 6 Can’t you just use

assignment questions in python

February 13, 2021 at 2:39 am

Hello. I am a beginner programmer and your laconic exercises help me a lot. I appreciate your work and thank you .(Georgia.Tbilisi)

assignment questions in python

February 5, 2021 at 11:56 am

Solution to 6:

assignment questions in python

January 31, 2021 at 6:31 pm

The answer to the exercise 15

assignment questions in python

January 20, 2021 at 9:00 pm

I think it’s much more convenient to answer question NUMBER 5 with a function. MY SOLUTION:

assignment questions in python

January 12, 2021 at 8:49 pm

The solution to exercise 16

January 12, 2021 at 4:05 pm

Aolution to 8

assignment questions in python

December 21, 2020 at 12:01 pm

Question 18. print the following pattern

assignment questions in python

January 11, 2021 at 12:08 pm

December 20, 2020 at 11:34 pm

Question 16

December 20, 2020 at 11:25 pm

Question 15

December 20, 2020 at 11:12 pm

December 20, 2020 at 10:51 pm

Question 14: Reverse a given integer numbers

December 20, 2020 at 6:08 pm

Question 10

December 20, 2020 at 6:05 pm

Question 10:

December 20, 2020 at 6:29 pm

December 18, 2020 at 8:07 pm

Question 6. Given a no, count the total no of digits in the no.

July 21, 2021 at 9:14 pm

don’t even need to convert to a string. just use len(num)

September 21, 2023 at 9:48 pm

TypeError: object of type ‘int’ has no len()

December 18, 2020 at 7:32 pm

December 18, 2020 at 4:03 pm

Question 4. Print multiplication table of a given number

assignment questions in python

December 7, 2020 at 3:03 pm

assignment questions in python

November 29, 2020 at 10:35 pm

an easy way of 14th exercise

September 21, 2023 at 9:51 pm

Output [76543]

Do you guys even test your code before posting solutions?

assignment questions in python

November 29, 2020 at 9:30 pm

question number 8 in loop exercise

assignment questions in python

November 2, 2020 at 7:00 am

Here are my worked solutions. Some are different from the answers given. Please ask if you have any questions.

assignment questions in python

November 1, 2020 at 3:06 pm

I want solution for this question write a python program to read the numbers until -1 is encountered.find the average of positive numbers and negative numbers entered by the user

August 3, 2022 at 4:17 pm

After I read your comment I went straight to the code editor to try and solve it……little did I know that your comment was 2 yrs ago…LOL…But still, I’m posting it so that you or others who tried to solve this problem but failed can refer. Most probably you won’t even see it. Ok bye, thanks!

Hope you understood my solution thanks!

assignment questions in python

October 30, 2020 at 9:10 pm

August 21, 2022 at 8:16 pm

TypeError: ‘int’ object is not callable

assignment questions in python

October 20, 2020 at 8:30 am

question 16

October 20, 2020 at 8:24 am

question 15

October 20, 2020 at 8:00 am

question 12 using for loop

October 20, 2020 at 6:27 am

question 10

October 20, 2020 at 6:23 am

October 20, 2020 at 6:18 am

October 17, 2020 at 12:21 am

October 16, 2020 at 11:44 pm

assignment questions in python

September 29, 2020 at 6:13 pm

Alternative answer for question 14

assignment questions in python

October 14, 2020 at 1:27 am

Question asked to use a loop.

assignment questions in python

September 28, 2020 at 6:03 pm

Alternative solution for question 18:

assignment questions in python

September 23, 2020 at 3:07 pm

solution 16:

September 23, 2020 at 2:26 pm

solution 14:

September 23, 2020 at 5:03 am

solution 13 :

assignment questions in python

September 8, 2020 at 4:15 pm

Exercise Question 10: Display a message “Done” after successful execution of for loop

print(“Done”)

assignment questions in python

September 2, 2020 at 9:47 am

Q3: n= int(input(“enter a number”) result = n*(n+1)//2 print(result)

assignment questions in python

September 6, 2020 at 3:01 pm

assignment questions in python

August 13, 2020 at 3:23 pm

Do you have class/oop exercises?

assignment questions in python

August 8, 2020 at 12:52 am

Can I just use print("Done") without the else? What does the else do in the code?

In Q10, I forgot to mention it.

assignment questions in python

August 14, 2020 at 3:14 pm

So basically the else runs if there is a break in the loop otherwise the else dose not come in to picture

assignment questions in python

August 3, 2020 at 5:40 am

assignment questions in python

August 10, 2020 at 7:10 pm

think so, item+=1 is unwanted in the above code

assignment questions in python

August 27, 2020 at 7:47 pm

No,, you can’t every time when it’s count,, it also prints “done”,,

September 6, 2020 at 3:14 pm

assignment questions in python

August 3, 2020 at 3:11 am

I didn’t use a loop for Question 6, but this works for 0 and negative numbers:

August 3, 2020 at 3:22 am

Edited so it will also work with decimals:

August 3, 2020 at 3:28 am

Scratch that last one! Needs work!

August 3, 2020 at 3:59 am

How’s this for Question 6:

assignment questions in python

October 8, 2020 at 10:05 am

should we have an easier alternative

# the outcome is still 5, btw

September 26, 2022 at 1:28 am

without a loop, it’s so easy, but with the loop is kind of difficult hey! I have done here have a look for –optimized code–

assignment questions in python

July 28, 2020 at 7:33 am

assignment questions in python

October 6, 2020 at 12:47 pm

Ya it worked and it is very simple compare to loop

assignment questions in python

July 25, 2020 at 11:11 pm

In a question 4:

assignment questions in python

July 16, 2020 at 7:39 pm

Question 7:

July 16, 2020 at 7:31 pm

Question 2:

assignment questions in python

July 15, 2020 at 10:50 am

solution for exercise 5

July 15, 2020 at 10:45 am

July 15, 2020 at 10:40 am

assignment questions in python

July 12, 2020 at 4:00 pm

for question no. 4

assignment questions in python

July 9, 2020 at 3:38 pm

assignment questions in python

August 11, 2020 at 2:01 pm

You are the best bro.

July 9, 2020 at 3:31 pm

July 9, 2020 at 3:23 pm

assignment questions in python

June 29, 2020 at 10:37 pm

assignment questions in python

June 29, 2020 at 8:42 am

# Exercise Question 6: Given a number count the total number of digits in a number

assignment questions in python

June 20, 2020 at 7:44 am

I got a question if someone can help, why do they use triple coordinates, like in exercise 3 for i in range(1, n + 1, 1) I tried it without the extra,1 and the result is the same, I just want to know the purpose of it being there or were I cand find out more about this 🙂

assignment questions in python

June 20, 2020 at 7:31 pm

Hey Jakes, Please refer this detailed article on Python range()

The last argument of range() function is the step. The step is a difference between each number in the result. The default value of the step is 1 if not specified. If you change it to 2 the difference between each number is 2

For example:

This will produce the following output.

I hope it helps you. Let me know if you have any doubts.

June 21, 2020 at 10:55 pm

got it, thank you :))

assignment questions in python

June 23, 2020 at 1:40 pm

the third co ordinate represents the difference of numbers in the range in the given case it is 1 which means that num are 1,2,3…n if it is 2 then 1,3,5…

assignment questions in python

July 18, 2020 at 8:33 pm

It is basically used to determine how you want to increment the base value. for example –

The output will be 1 4 7.

assignment questions in python

June 17, 2020 at 9:57 pm

Q6 without a loop

assignment questions in python

June 15, 2020 at 6:44 pm

assignment questions in python

June 8, 2020 at 2:52 pm

Exercise Question 4: Accept n number from user and print its multiplication table

June 8, 2020 at 2:21 pm

Exercise Question 2: Print the following pattern

assignment questions in python

June 7, 2020 at 10:44 pm

The for in Q10 Dose NOT go with else:

Here is a Better Solution:

assignment questions in python

May 26, 2020 at 10:24 am

assignment questions in python

July 4, 2020 at 9:32 am

assignment questions in python

September 5, 2020 at 10:07 pm

50 40 30 20 10

May 26, 2020 at 9:55 am

May 26, 2020 at 9:21 am

assignment questions in python

May 23, 2020 at 12:06 am

# # Exercise Question 1:

# Exercise Question 3:

# # Exercise Question 4:

# Exercise Question 5:

# # Exercise Question 6:

# Exercise Question 7:

# Exercise Question 8:

# Exercise Question 9:

# Exercise Question 10:

assignment questions in python

May 19, 2020 at 2:13 pm

for Question 4:

May 19, 2020 at 2:12 pm

Solution for Exercise 4:

num = int(input(“Enter Number= “)) table = 0 for i in range(1,11): table = (i*num) print(table)

assignment questions in python

May 17, 2020 at 10:23 pm

assignment questions in python

May 22, 2020 at 10:46 pm

May 17, 2020 at 9:59 pm

Question 6 doesn’t work with 0 and negative numbers. I don’t understand what is

and how does it help to count, if I delete that line, I get an endless loop which is to be expected.

assignment questions in python

May 11, 2020 at 1:52 am

May 11, 2020 at 1:50 am

assignment questions in python

May 8, 2020 at 4:50 pm

alternative for answer of question 8

assignment questions in python

May 5, 2020 at 4:34 pm

sir, i want to ask that are these python exercises sufficient for project works?

May 7, 2020 at 8:36 pm

These exercises will help you to improve your understanding and coding ability.

April 25, 2020 at 1:11 am

Hey team, so I arrived at this “alternative answer” for question 4:

However, I’m having difficulty wrapping my head around “i” within the for statements. When using it for the solutions, is it merely a dynamic variable in between the stated ranges?

April 26, 2020 at 5:02 pm

Yes, i is an iterator variable, changes its value in each iteration.

assignment questions in python

April 23, 2020 at 2:54 am

Hi Everyone, I’m new to Python and confused of the line print(i, end=' ') I acknowledge that it’d print the number generated from the same loop in one line but what exactly does it mean?

April 23, 2020 at 7:45 pm

Hey Trung Nguyen,

The default value of the end is \n meaning that after the print statement, it will print a new line. The end is you want to be printed after the print statement has been executed. For example, print(i, end=' ') will print all the values of i on the same line. If we replace this with print(i, end="\n\n") it will write two newlines after each value of i

assignment questions in python

August 5, 2022 at 1:36 pm

assignment questions in python

April 17, 2020 at 10:12 pm

Thanks Sir! this is one of the best website and here i got to learn many things. And the practice part including quiz that’s the great work and it’s very helpful for me.

Thanks for making this lovely website i really appreciate your work.

April 18, 2020 at 12:48 am

Thank you, Ashish. I really appreciate your kind words and encouragement.

assignment questions in python

April 16, 2020 at 8:35 pm

For exercise question 2, here is a short answer:

April 17, 2020 at 5:07 pm

Hey, Thank you for an alternative solution

assignment questions in python

April 13, 2020 at 12:11 pm

Hi In solution of question 8, “-1” is equivalent with 10? Then why we reduce with -1 in

assignment questions in python

April 13, 2020 at 4:13 am

another way for Exercise Question 8: Reverse the following list using for loop

April 13, 2020 at 7:57 pm

Thank you, Agus

assignment questions in python

August 8, 2023 at 3:29 am

list1 = [10, 20, 30, 40, 50][::-1] for i in list1: print(i)

assignment questions in python

April 9, 2020 at 1:27 pm

In question number 2 when input given is beyond 50 it does not generate desired pattern . Can you please explain it

April 10, 2020 at 3:55 pm

Hey Avinash, It is generating Pattern correctly after giving input bigger than 50. Can you please share your code.

assignment questions in python

March 24, 2020 at 9:00 pm

we can use the reverse() and it much easier!

assignment questions in python

March 19, 2020 at 11:56 am

Hi! Your exercises are very helpful. I was wondering if you could add some comments in your codes as they are very helpful for beginners like me. ? Thanking you.?

March 19, 2020 at 9:09 pm

Thank you, elite_coder. Sure we will add comments

assignment questions in python

March 15, 2020 at 9:17 am

do the solution of question 10 and the following code make any difference?

Thank you in advance.

March 16, 2020 at 5:03 pm

Hi Ashna, The question was created to demonstrate the use of else clause in for loop. The else block executes only when loop terminates naturally

assignment questions in python

March 5, 2020 at 8:12 am

what does num//=10 means in exercise 6?

March 5, 2020 at 10:33 am

Hi Nifdi, Its Floor division operator and returns the “floor” of the result.

assignment questions in python

July 5, 2020 at 9:55 pm

the numbers are divided by 7 without a remainder per 1,000,000

assignment questions in python

October 11, 2020 at 4:01 pm

how is the solution of the question Create a variable List and fill it with the number and number of free lists. Make it use IF ELSE and Looping statements (FOR, While, etc) that call from a List. Print output “number including number x” (x consists of even, odd, and prime). ??

assignment questions in python

July 24, 2020 at 11:10 pm

It fetches the quotient. num //= 10 for example 1234//=10 , will fetch 123 alone. It is opposite to num%10 which fetches the remainder.

assignment questions in python

November 9, 2020 at 4:50 pm

Leave a Reply Cancel reply

your email address will NOT be published. all comments are moderated according to our comment policy.

Use <pre> tag for posting code. E.g. <pre> Your entire code </pre>

About PYnative

PYnative.com is for Python lovers. Here, You can get Tutorials, Exercises, and Quizzes to practice and improve your Python skills .

Explore Python

  • Learn Python
  • Python Basics
  • Python Databases
  • Python Exercises
  • Python Quizzes
  • Online Python Code Editor
  • Python Tricks

To get New Python Tutorials, Exercises, and Quizzes

Legal Stuff

We use cookies to improve your experience. While using PYnative, you agree to have read and accepted our Terms Of Use , Cookie Policy , and Privacy Policy .

Copyright © 2018–2024 pynative.com

IMAGES

  1. Python Assignment help by Python Assignment Help

    assignment questions in python

  2. Assignment-questions-python

    assignment questions in python

  3. Python Assignment Expression? The 13 Top Answers

    assignment questions in python

  4. HW1

    assignment questions in python

  5. Solved In this assignment, you will use Python and Numpy to

    assignment questions in python

  6. Solved This is a Python Assignment. A sample demo screenshot

    assignment questions in python

VIDEO

  1. Python

  2. Python Basics: Assignment Operators (Continuation)

  3. Assignment statements

  4. Python Coding Interview Question Part 1

  5. 53 Python Interview Questions

  6. Python Interview Questions Latest #python #coding

COMMENTS

  1. Python Exercises, Practice, Challenges

    Practice Python Exercises and Challenges with Solutions

  2. Python Exercise with Practice Questions and Solutions

    Python Exercise with Practice Questions and Solutions

  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. 35 Python Programming Exercises and Solutions

    35 Python Programming Exercises and Solutions

  5. Python Basic Exercise for Beginners with Solutions

    Python Basic Exercise for Beginners with Solutions

  6. Python Functions Exercise with Solution [10 Programs]

    Python Functions Exercise with Solution [10 Programs]

  7. Python Practice Problems: Get Ready for Your Next Interview

    Python Practice Problems: Get Ready for Your Next Interview

  8. 10 Python Practice Exercises for Beginners with Solutions

    10 Python Practice Exercises for Beginners with Solutions

  9. Python Exercises, Practice, Solution

    Python Exercises, Practice, Solution

  10. 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).

  11. Python Practice: 93 Unique Online Coding Exercises

    Python Practice: 93 Unique Online Coding Exercises

  12. 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

  13. Python Exercises

    Python Exercises

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

    There is a single operator in Python, capable of providing the remainder of a division operation. Two numbers are passed as parameters. The first parameter divided by the second parameter will have a remainder, possibly zero. Return that value. Examples remainder(1, 3) 1 remainder(3, 4) 3 remainder(5, 5) 0 remainde …

  15. Python List Exercise with Solution [10 Exercise Questions]

    Python List Exercise with Solutions

  16. 70+ Python if else Statement Important Practice Questions

    70+ Python if else Statement Important Practice Questions

  17. Python's Assignment Operator: Write Robust Assignments

    Python's Assignment Operator: Write Robust Assignments

  18. Different Forms of Assignment Statements in Python

    Different Forms of Assignment Statements in Python

  19. 21 Python for Loop Exercises and Examples

    21 Python for Loop Exercises and Examples

  20. Solve Python

    Solve Python - HackerRank ... Solve Python

  21. Python OOP Exercise

    Python OOP Exercise - Classes and Objects ...

  22. Assignment Operators in Python

    Assignment Operators in Python

  23. Python Dictionary Exercise with Solution [10 Exercise Questions]

    Python Dictionary Exercise with Solutions

  24. Python for loop and if else Exercises [10 Exercise Programs]

    Python if else, for loop, and range() Exercises with Solutions