 Python »
 3.12.5 Documentation »
 The Python Standard Library »
 Numeric and Mathematical Modules »
 math — Mathematical functions
 Theme Auto Light Dark 
math — Mathematical functions ¶
This module provides access to the mathematical functions defined by the C standard.
These functions cannot be used with complex numbers; use the functions of the same name from the cmath module if you require support for complex numbers. The distinction between functions which support complex numbers and those which don’t is made since most users do not want to learn quite as much mathematics as required to understand complex numbers. Receiving an exception instead of a complex result allows earlier detection of the unexpected complex number used as a parameter, so that the programmer can determine how and why it was generated in the first place.
The following functions are provided by this module. Except when explicitly noted otherwise, all return values are floats.
Numbertheoretic and representation functions ¶
Return the ceiling of x , the smallest integer greater than or equal to x . If x is not a float, delegates to x.__ceil__ , which should return an Integral value.
Return the number of ways to choose k items from n items without repetition and without order.
Evaluates to n! / (k! * (n  k)!) when k <= n and evaluates to zero when k > n .
Also called the binomial coefficient because it is equivalent to the coefficient of kth term in polynomial expansion of (1 + x)ⁿ .
Raises TypeError if either of the arguments are not integers. Raises ValueError if either of the arguments are negative.
Added in version 3.8.
Return a float with the magnitude (absolute value) of x but the sign of y . On platforms that support signed zeros, copysign(1.0, 0.0) returns 1.0 .
Return the absolute value of x .
Return n factorial as an integer. Raises ValueError if n is not integral or is negative.
Deprecated since version 3.9: Accepting floats with integral values (like 5.0 ) is deprecated.
Return the floor of x , the largest integer less than or equal to x . If x is not a float, delegates to x.__floor__ , which should return an Integral value.
Return fmod(x, y) , as defined by the platform C library. Note that the Python expression x % y may not return the same result. The intent of the C standard is that fmod(x, y) be exactly (mathematically; to infinite precision) equal to x  n*y for some integer n such that the result has the same sign as x and magnitude less than abs(y) . Python’s x % y returns a result with the sign of y instead, and may not be exactly computable for float arguments. For example, fmod(1e100, 1e100) is 1e100 , but the result of Python’s 1e100 % 1e100 is 1e1001e100 , which cannot be represented exactly as a float, and rounds to the surprising 1e100 . For this reason, function fmod() is generally preferred when working with floats, while Python’s x % y is preferred when working with integers.
Return the mantissa and exponent of x as the pair (m, e) . m is a float and e is an integer such that x == m * 2**e exactly. If x is zero, returns (0.0, 0) , otherwise 0.5 <= abs(m) < 1 . This is used to “pick apart” the internal representation of a float in a portable way.
Return an accurate floatingpoint sum of values in the iterable. Avoids loss of precision by tracking multiple intermediate partial sums.
The algorithm’s accuracy depends on IEEE754 arithmetic guarantees and the typical case where the rounding mode is halfeven. On some nonWindows builds, the underlying C library uses extended precision addition and may occasionally doubleround an intermediate sum causing it to be off in its least significant bit.
For further discussion and two alternative approaches, see the ASPN cookbook recipes for accurate floatingpoint summation .
Return the greatest common divisor of the specified integer arguments. If any of the arguments is nonzero, then the returned value is the largest positive integer that is a divisor of all arguments. If all arguments are zero, then the returned value is 0 . gcd() without arguments returns 0 .
Added in version 3.5.
Changed in version 3.9: Added support for an arbitrary number of arguments. Formerly, only two arguments were supported.
Return True if the values a and b are close to each other and False otherwise.
Whether or not two values are considered close is determined according to given absolute and relative tolerances.
rel_tol is the relative tolerance – it is the maximum allowed difference between a and b , relative to the larger absolute value of a or b . For example, to set a tolerance of 5%, pass rel_tol=0.05 . The default tolerance is 1e09 , which assures that the two values are the same within about 9 decimal digits. rel_tol must be greater than zero.
abs_tol is the minimum absolute tolerance – useful for comparisons near zero. abs_tol must be at least zero.
If no errors occur, the result will be: abs(ab) <= max(rel_tol * max(abs(a), abs(b)), abs_tol) .
The IEEE 754 special values of NaN , inf , and inf will be handled according to IEEE rules. Specifically, NaN is not considered close to any other value, including NaN . inf and inf are only considered close to themselves.
PEP 485 – A function for testing approximate equality
Return True if x is neither an infinity nor a NaN, and False otherwise. (Note that 0.0 is considered finite.)
Added in version 3.2.
Return True if x is a positive or negative infinity, and False otherwise.
Return True if x is a NaN (not a number), and False otherwise.
Return the integer square root of the nonnegative integer n . This is the floor of the exact square root of n , or equivalently the greatest integer a such that a ² ≤ n .
For some applications, it may be more convenient to have the least integer a such that n ≤ a ², or in other words the ceiling of the exact square root of n . For positive n , this can be computed using a = 1 + isqrt(n  1) .
Return the least common multiple of the specified integer arguments. If all arguments are nonzero, then the returned value is the smallest positive integer that is a multiple of all arguments. If any of the arguments is zero, then the returned value is 0 . lcm() without arguments returns 1 .
Added in version 3.9.
Return x * (2**i) . This is essentially the inverse of function frexp() .
Return the fractional and integer parts of x . Both results carry the sign of x and are floats.
Return the floatingpoint value steps steps after x towards y .
If x is equal to y , return y , unless steps is zero.
math.nextafter(x, math.inf) goes up: towards positive infinity.
math.nextafter(x, math.inf) goes down: towards minus infinity.
math.nextafter(x, 0.0) goes towards zero.
math.nextafter(x, math.copysign(math.inf, x)) goes away from zero.
See also math.ulp() .
Changed in version 3.12: Added the steps argument.
Return the number of ways to choose k items from n items without repetition and with order.
Evaluates to n! / (n  k)! when k <= n and evaluates to zero when k > n .
If k is not specified or is None , then k defaults to n and the function returns n! .
Calculate the product of all the elements in the input iterable . The default start value for the product is 1 .
When the iterable is empty, return the start value. This function is intended specifically for use with numeric values and may reject nonnumeric types.
Return the IEEE 754style remainder of x with respect to y . For finite x and finite nonzero y , this is the difference x  n*y , where n is the closest integer to the exact value of the quotient x / y . If x / y is exactly halfway between two consecutive integers, the nearest even integer is used for n . The remainder r = remainder(x, y) thus always satisfies abs(r) <= 0.5 * abs(y) .
Special cases follow IEEE 754: in particular, remainder(x, math.inf) is x for any finite x , and remainder(x, 0) and remainder(math.inf, x) raise ValueError for any nonNaN x . If the result of the remainder operation is zero, that zero will have the same sign as x .
On platforms using IEEE 754 binary floating point, the result of this operation is always exactly representable: no rounding error is introduced.
Added in version 3.7.
Return the sum of products of values from two iterables p and q .
Raises ValueError if the inputs do not have the same length.
Roughly equivalent to:
For float and mixed int/float inputs, the intermediate products and sums are computed with extended precision.
Added in version 3.12.
Return x with the fractional part removed, leaving the integer part. This rounds toward 0: trunc() is equivalent to floor() for positive x , and equivalent to ceil() for negative x . If x is not a float, delegates to x.__trunc__ , which should return an Integral value.
Return the value of the least significant bit of the float x :
If x is a NaN (not a number), return x .
If x is negative, return ulp(x) .
If x is a positive infinity, return x .
If x is equal to zero, return the smallest positive denormalized representable float (smaller than the minimum positive normalized float, sys.float_info.min ).
If x is equal to the largest positive representable float, return the value of the least significant bit of x , such that the first float smaller than x is x  ulp(x) .
Otherwise ( x is a positive finite number), return the value of the least significant bit of x , such that the first float bigger than x is x + ulp(x) .
ULP stands for “Unit in the Last Place”.
See also math.nextafter() and sys.float_info.epsilon .
Note that frexp() and modf() have a different call/return pattern than their C equivalents: they take a single argument and return a pair of values, rather than returning their second return value through an ‘output parameter’ (there is no such thing in Python).
For the ceil() , floor() , and modf() functions, note that all floatingpoint numbers of sufficiently large magnitude are exact integers. Python floats typically carry no more than 53 bits of precision (the same as the platform C double type), in which case any float x with abs(x) >= 2**52 necessarily has no fractional bits.
Power and logarithmic functions ¶
Return the cube root of x .
Added in version 3.11.
Return e raised to the power x , where e = 2.718281… is the base of natural logarithms. This is usually more accurate than math.e ** x or pow(math.e, x) .
Return 2 raised to the power x .
Return e raised to the power x , minus 1. Here e is the base of natural logarithms. For small floats x , the subtraction in exp(x)  1 can result in a significant loss of precision ; the expm1() function provides a way to compute this quantity to full precision:
With one argument, return the natural logarithm of x (to base e ).
With two arguments, return the logarithm of x to the given base , calculated as log(x)/log(base) .
Return the natural logarithm of 1+x (base e ). The result is calculated in a way which is accurate for x near zero.
Return the base2 logarithm of x . This is usually more accurate than log(x, 2) .
Added in version 3.3.
int.bit_length() returns the number of bits necessary to represent an integer in binary, excluding the sign and leading zeros.
Return the base10 logarithm of x . This is usually more accurate than log(x, 10) .
Return x raised to the power y . Exceptional cases follow the IEEE 754 standard as far as possible. In particular, pow(1.0, x) and pow(x, 0.0) always return 1.0 , even when x is a zero or a NaN. If both x and y are finite, x is negative, and y is not an integer then pow(x, y) is undefined, and raises ValueError .
Unlike the builtin ** operator, math.pow() converts both its arguments to type float . Use ** or the builtin pow() function for computing exact integer powers.
Changed in version 3.11: The special cases pow(0.0, inf) and pow(0.0, inf) were changed to return inf instead of raising ValueError , for consistency with IEEE 754.
Return the square root of x .
Trigonometric functions ¶
Return the arc cosine of x , in radians. The result is between 0 and pi .
Return the arc sine of x , in radians. The result is between pi/2 and pi/2 .
Return the arc tangent of x , in radians. The result is between pi/2 and pi/2 .
Return atan(y / x) , in radians. The result is between pi and pi . The vector in the plane from the origin to point (x, y) makes this angle with the positive X axis. The point of atan2() is that the signs of both inputs are known to it, so it can compute the correct quadrant for the angle. For example, atan(1) and atan2(1, 1) are both pi/4 , but atan2(1, 1) is 3*pi/4 .
Return the cosine of x radians.
Return the Euclidean distance between two points p and q , each given as a sequence (or iterable) of coordinates. The two points must have the same dimension.
Return the Euclidean norm, sqrt(sum(x**2 for x in coordinates)) . This is the length of the vector from the origin to the point given by the coordinates.
For a two dimensional point (x, y) , this is equivalent to computing the hypotenuse of a right triangle using the Pythagorean theorem, sqrt(x*x + y*y) .
Changed in version 3.8: Added support for ndimensional points. Formerly, only the two dimensional case was supported.
Changed in version 3.10: Improved the algorithm’s accuracy so that the maximum error is under 1 ulp (unit in the last place). More typically, the result is almost always correctly rounded to within 1/2 ulp.
Return the sine of x radians.
Return the tangent of x radians.
Angular conversion ¶
Convert angle x from radians to degrees.
Convert angle x from degrees to radians.
Hyperbolic functions ¶
Hyperbolic functions are analogs of trigonometric functions that are based on hyperbolas instead of circles.
Return the inverse hyperbolic cosine of x .
Return the inverse hyperbolic sine of x .
Return the inverse hyperbolic tangent of x .
Return the hyperbolic cosine of x .
Return the hyperbolic sine of x .
Return the hyperbolic tangent of x .
Special functions ¶
Return the error function at x .
The erf() function can be used to compute traditional statistical functions such as the cumulative standard normal distribution :
Return the complementary error function at x . The complementary error function is defined as 1.0  erf(x) . It is used for large values of x where a subtraction from one would cause a loss of significance .
Return the Gamma function at x .
Return the natural logarithm of the absolute value of the Gamma function at x .
Constants ¶
The mathematical constant π = 3.141592…, to available precision.
The mathematical constant e = 2.718281…, to available precision.
The mathematical constant τ = 6.283185…, to available precision. Tau is a circle constant equal to 2 π , the ratio of a circle’s circumference to its radius. To learn more about Tau, check out Vi Hart’s video Pi is (still) Wrong , and start celebrating Tau day by eating twice as much pie!
Added in version 3.6.
A floatingpoint positive infinity. (For negative infinity, use math.inf .) Equivalent to the output of float('inf') .
A floatingpoint “not a number” (NaN) value. Equivalent to the output of float('nan') . Due to the requirements of the IEEE754 standard , math.nan and float('nan') are not considered to equal to any other numeric value, including themselves. To check whether a number is a NaN, use the isnan() function to test for NaNs instead of is or == . Example:
Changed in version 3.11: It is now always available.
CPython implementation detail: The math module consists mostly of thin wrappers around the platform C math library functions. Behavior in exceptional cases follows Annex F of the C99 standard where appropriate. The current implementation will raise ValueError for invalid operations like sqrt(1.0) or log(0.0) (where C99 Annex F recommends signaling invalid operation or dividebyzero), and OverflowError for results that overflow (for example, exp(1000.0) ). A NaN will not be returned from any of the functions above unless one or more of the input arguments was a NaN; in that case, most functions will return a NaN, but (again following C99 Annex F) there are some exceptions to this rule, for example pow(float('nan'), 0.0) or hypot(float('nan'), float('inf')) .
Note that Python makes no effort to distinguish signaling NaNs from quiet NaNs, and behavior for signaling NaNs remains unspecified. Typical behavior is to treat all NaNs as though they were quiet.
Complex number versions of many of these functions.
Table of Contents
 Numbertheoretic and representation functions
 Power and logarithmic functions
 Trigonometric functions
 Angular conversion
 Hyperbolic functions
 Special functions
Previous topic
numbers — Numeric abstract base classes
cmath — Mathematical functions for complex numbers
 Report a Bug
 Show Source
Learn Python practically and Get Certified .
Popular Tutorials
Popular examples, reference materials, learn python interactively, python introduction.
 Get Started With Python
 Your First Python Program
 Python Comments
Python Fundamentals
 Python Variables and Literals
 Python Type Conversion
 Python Basic Input and Output
Python Operators
Python flow control.
Python if...else Statement
 Python for Loop
 Python while Loop
 Python break and continue
 Python pass Statement
Python Data types
 Python Numbers and Mathematics
 Python List
 Python Tuple
 Python String
 Python Dictionary
 Python Functions
 Python Function Arguments
 Python Variable Scope
 Python Global Keyword
 Python Recursion
 Python Modules
 Python Package
 Python Main function
Python Files
 Python Directory and Files Management
 Python CSV: Read and Write CSV files
 Reading CSV files in Python
 Writing CSV files in Python
 Python Exception Handling
 Python Exceptions
 Python Custom Exceptions
Python Object & Class
 Python Objects and Classes
 Python Inheritance
 Python Multiple Inheritance
 Polymorphism in Python
Python Operator Overloading
Python Advanced Topics
 List comprehension
 Python Lambda/Anonymous Function
 Python Iterators
 Python Generators
 Python Namespace and Scope
 Python Closures
 Python Decorators
 Python @property decorator
 Python RegEx
Python Date and Time
 Python datetime
 Python strftime()
 Python strptime()
 How to get current date and time in Python?
 Python Get Current Time
 Python timestamp to datetime and viceversa
 Python time Module
 Python sleep()
Additional Topic
Precedence and Associativity of Operators in Python
 Python Keywords and Identifiers
 Python Asserts
 Python Json
 Python *args and **kwargs
Python Tutorials
Python 3 Tutorial
 Python Strings
 Python any()
Operators are special symbols that perform operations on variables and values. For example,
Here, + is an operator that adds two numbers: 5 and 6 .
 Types of Python Operators
Here's a list of different types of Python operators that we will learn in this tutorial.
 Arithmetic Operators
 Assignment Operators
 Comparison Operators
 Logical Operators
 Bitwise Operators
 Special Operators
1. Python Arithmetic Operators
Arithmetic operators are used to perform mathematical operations like addition, subtraction, multiplication, etc. For example,
Here,  is an arithmetic operator that subtracts two values or variables.
Operator  Operation  Example 

Addition  
Subtraction  
Multiplication  
Division  
Floor Division  
Modulo  
Power 
Example 1: Arithmetic Operators in Python
In the above example, we have used multiple arithmetic operators,
 + to add a and b
  to subtract b from a
 * to multiply a and b
 / to divide a by b
 // to floor divide a by b
 % to get the remainder
 ** to get a to the power b
2. Python Assignment Operators
Assignment operators are used to assign values to variables. For example,
Here, = is an assignment operator that assigns 5 to x .
Here's a list of different assignment operators available in Python.
Operator  Name  Example 

Assignment Operator  
Addition Assignment  
Subtraction Assignment  
Multiplication Assignment  
Division Assignment  
Remainder Assignment  
Exponent Assignment 
Example 2: Assignment Operators
Here, we have used the += operator to assign the sum of a and b to a .
Similarly, we can use any other assignment operators as per our needs.
3. Python Comparison Operators
Comparison operators compare two values/variables and return a boolean result: True or False . For example,
Here, the > comparison operator is used to compare whether a is greater than b or not.
Operator  Meaning  Example 

Is Equal To  gives us  
Not Equal To  gives us  
Greater Than  gives us  
Less Than  gives us  
Greater Than or Equal To  give us  
Less Than or Equal To  gives us 
Example 3: Comparison Operators
Note: Comparison operators are used in decisionmaking and loops . We'll discuss more of the comparison operator and decisionmaking in later tutorials.
4. Python Logical Operators
Logical operators are used to check whether an expression is True or False . They are used in decisionmaking. For example,
Here, and is the logical operator AND . Since both a > 2 and b >= 6 are True , the result is True .
Operator  Example  Meaning 

a b  : only if both the operands are  
a b  : if at least one of the operands is  
a  : if the operand is and viceversa. 
Example 4: Logical Operators
Note : Here is the truth table for these logical operators.
5. Python Bitwise operators
Bitwise operators act on operands as if they were strings of binary digits. They operate bit by bit, hence the name.
For example, 2 is 10 in binary, and 7 is 111 .
In the table below: Let x = 10 ( 0000 1010 in binary) and y = 4 ( 0000 0100 in binary)
Operator  Meaning  Example 

Bitwise AND  x & y = 0 ( )  
Bitwise OR  x  y = 14 ( )  
Bitwise NOT  ~x = 11 ( )  
Bitwise XOR  x ^ y = 14 ( )  
Bitwise right shift  x >> 2 = 2 ( )  
Bitwise left shift  x 0010 1000) 
6. Python Special operators
Python language offers some special types of operators like the identity operator and the membership operator. They are described below with examples.
 Identity operators
In Python, is and is not are used to check if two values are located at the same memory location.
It's important to note that having two variables with equal values doesn't necessarily mean they are identical.
Operator  Meaning  Example 

if the operands are identical (refer to the same object)  
if the operands are not identical (do not refer to the same object) 
Example 4: Identity operators in Python
Here, we see that x1 and y1 are integers of the same values, so they are equal as well as identical. The same is the case with x2 and y2 (strings).
But x3 and y3 are lists. They are equal but not identical. It is because the interpreter locates them separately in memory, although they are equal.
 Membership operators
In Python, in and not in are the membership operators. They are used to test whether a value or variable is found in a sequence ( string , list , tuple , set and dictionary ).
In a dictionary, we can only test for the presence of a key, not the value.
Operator  Meaning  Example 

if value/variable is in the sequence  
if value/variable is in the sequence 
Example 5: Membership operators in Python
Here, 'H' is in message , but 'hello' is not present in message (remember, Python is casesensitive).
Similarly, 1 is key, and 'a' is the value in dictionary dict1 . Hence, 'a' in y returns False .
 Precedence and Associativity of operators in Python
Table of Contents
 Introduction
 Python Arithmetic Operators
 Python Assignment Operators
 Python Comparison Operators
 Python Logical Operators
 Python Bitwise operators
 Python Special operators
Before we wrap up, let’s put your knowledge of Python operators to the test! Can you solve the following challenge?
Write a function to split the restaurant bill among friends.
 Take the subtotal of the bill and the number of friends as inputs.
 Calculate the total bill by adding 20% tax to the subtotal and then divide it by the number of friends.
 Return the amount each friend has to pay, rounded off to two decimal places.
Video: Operators in Python
Sorry about that.
Our premium learning platform, created with over a decade of experience and thousands of feedbacks .
Learn and improve your coding skills like never before.
 Interactive Courses
 Certificates
 2000+ Challenges
Related Tutorials
Python Tutorial
Python Operators Cheat Sheet
 python basics
 learn python
Discover the essential Python operators and how to effectively use them with our comprehensive cheat sheet. We cover everything from arithmetic to bitwise operations!
If you’ve ever written a few lines of Python code, you are likely familiar with Python operators. Whether you're doing basic arithmetic calculations, creating variables, or performing complex logical operations, chances are that you had to use a Python operator to perform the task. But just how many of them exist, and what do you use them for?
In this cheat sheet, we will cover every one of Python’s operators:
 Arithmetic operators.
 Assignment operators.
 Comparison operators.
 Logical operators.
 Identity operators.
 Membership operators.
 Bitwise operators.
Additionally, we will discuss operator precedence and its significance in Python.
If you're just starting out with Python programming, you may want to look into our Python Basics Track . Its nearly 40 hours of content covers Python operators and much more; you’ll get an excellent foundation to build your coding future on.
Without further ado, let's dive in and learn all about Python operators.
What Are Python Operators?
Python operators are special symbols or keywords used to perform specific operations. Depending on the operator, we can perform arithmetic calculations, assign values to variables, compare two or more values, use logical decisionmaking in our programs, and more.
How Operators Work
Operators are fundamental to Python programming (and programming as a whole); they allow us to manipulate data and control the flow of our code. Understanding how to use operators effectively enables programmers to write code that accomplishes a desired task.
In more specific terms, an operator takes two elements – called operands – and combines them in a given manner. The specific way that this combination happens is what defines the operator. For example, the operation A + B takes the operands A and B , performs the “sum” operation (denoted by the + operator), and returns the total of those two operands.
The Complete List of Python Operators
Now that we know the basic theory behind Python operators, it’s time to go over every single one of them.
In each section below, we will explain a family of operators, provide a few code samples on how they are used, and present a comprehensive table of all operators in that family. Let’s get started!
Python Arithmetic Operators
Arithmetic operators are used to perform mathematical calculations like addition, subtraction, multiplication, division, exponentiation, and modulus. Most arithmetic operators look the same as those used in everyday mathematics (or in spreadsheet formulas).
Here is the complete list of arithmetic operators in Python:




+  Addition  2 + 3  5 
  Subtraction  5  2  3 
*  Multiplication  4 * 6  24 
/  Division  11 / 4  2.75 
//  Floor division  11 // 4  2 
%  Modulo ( )  11 % 4  3 
**  Exponentiation ( )  2 ** 3  8 
Most of these operators are selfexplanatory, but a few are somewhat tricky. The floor division operator ( // ), for example, returns the integer portion of the division between two numbers.
The modulo operator ( % ) is also uncommon: it returns the remainder of an integer division, i.e. what remains when you divide a number by another. When dividing 11 by 4, the number 4 divides “perfectly” up to the value 8. This means that there’s a remainder of 3 left, which is the value returned by the modulo operator.
Also note that the addition ( + ) and subtraction (  ) operators are special in that they can operate on a single operand; the expression +5 or 5 is considered an operation in itself. When used in this fashion, these operators are referred to as unary operators . The negative unary operator (as in 5 ) is used to invert the value of a number, while the positive unary operator (as in +5 ) was mostly created for symmetrical reasons, since writing +5 is effectively the same as just writing 5 .
Python Assignment Operators
Assignment operators are used to assign values to variables . They can also perform arithmetic operations in combination with assignments.
The canonical assignment operator is the equal sign ( = ). Its purpose is to bind a value to a variable: if we write x = 10 , we store the value 10 inside the variable x. We can then later refer to the variable x in order to retrieve its value.
The remaining assignment operators are collectively known as augmented assignment operators . They combine a regular assignment with an arithmetic operator in a single line. This is denoted by the arithmetic operator placed directly before the “vanilla” assignment operator.
Augmented assignment operators are simply used as a shortcut. Instead of writing x = x + 1 , they allow us to write x += 1 , effectively “updating” a variable in a concise manner. Here’s a code sample of how this works:
In the table below, you can find the complete list of assignment operators in Python. Note how there is an augmented assignment operator for every arithmetic operator we went over in the previous section:




=  Assign a value to a variable  x = 5  N/A 
+=  Add and assign  x += 3  x = x + 3 
=  Subtract and assign  x = 2  x = x  2 
*=  Multiply and assign  x *= 4  x = x * 4 
/=  Divide and assign  x /= 2  x = x / 2 
%=  Modulo and assign  x %= 3  x = x // 3 
//=  Floor divide and assign  x //= 2  x = x % 2 
**=  Exponentiate and assign  x **= 2  x = x ** 2 
Python Comparison Operators
Comparison operators are used to compare two values . They return a Boolean value ( True or False ) based on the comparison result.
These operators are often used in conjunction with if/else statements in order to control the flow of a program. For example, the code block below allows the user to select an option from a menu:
The table below shows the full list of Python comparison operators:




==  Equal to  2 == 2  True 
!=  Not equal to  3 != 4  True 
>  Greater than  5 > 10  False 
<  Less than  2 < 6  True 
>=  Greater than or equal  4 >= 5  False 
<=  Less than or equal  2 <= 2  True 
Note: Pay attention to the “equal to” operator ( == ) – it’s easy to mistake it for the assignment operator ( = ) when writing Python scripts!
If you’re coming from other programming languages, you may have heard about “ternary conditional operators”. Python has a very similar structure called conditional expressions, which you can learn more about in our article on ternary operators in Python . And if you want more details on this topic, be sure to check out our article on Python comparison operators .
Python Logical Operators
Logical operators are used to combine and manipulate Boolean values . They return True or False based on the Boolean values given to them.
Logical operators are often used to combine different conditions into one. You can leverage the fact that they are written as normal English words to create code that is very readable. Even someone who isn’t familiar with Python could roughly understand what the code below attempts to do:
Here is the table with every logical operator in Python:




and  Returns True only if Boolean values are True; otherwise returns False  (10 > 5) and (10 < 50)  True 
(True ) and (True )  
or  Returns True if value is True; otherwise returns False  (1 < 0) or (1 < 100)  False 
(False) or (True )  
not  Returns True if the value is False (and False if it is True)  not (10 > 5)  False 
not (True ) 
Note: When determining if a value falls inside a range of numbers, you can use the “interval notation” commonly used in mathematics; the expression x > 0 and x < 100 can be rewritten as 0 < x < 100 .
Python Identity Operators
Identity operators are used to query whether two Python objects are the exact same object . This is different from using the “equal to” operator ( == ) because two variables may be equal to each other , but at the same time not be the same object .
For example, the lists list_a and list_b below contain the same values, so for all practical purposes they are considered equal. But they are not the same object – modifying one list does not change the other:
The table below presents the two existing Python identity operators:



is  Returns True if both variables are the same object  x is y 
is not  Returns True if both variables are not the same object  x is not y 
Python Membership Operators
Membership operators are used to test if a value is contained inside another object .
Objects that can contain other values in them are known as collections . Common collections in Python include lists, tuples, and sets.




in  Returns True if the value is in the collection  3 in [1, 2, 3]  True 
not in  Returns True if the value is not in the collection  4 not in [1, 2, 3]  True 
Python Bitwise Operators
Bitwise operators in Python are the most esoteric of them all. They are used to perform bitlevel operations on integers. Although you may not use these operators as often in your day to day coding, they are a staple in lowlevel programming languages like C.
As an example, let’s consider the numbers 5 (whose binary representation is 101 ), and the number 3 (represented as 011 in binary).
In order to apply the bitwise AND operator ( & ), we take the first digit from each number’s binary representation (in this case: 1 for the number 5, and 0 for the number 3). Then, we perform the AND operation, which works much like Python’s logical and operator except True is now 1 and False is 0 .
This gives us the operation 1 AND 0 , which results in 0 .
We then simply perform the same operation for each remaining pair of digits in the binary representation of 5 and 3, namely:
 0 AND 1 = 0
 1 AND 1 = 1
We end up with 0 , 0 , and 1 , which is then put back together as the binary number 001 – which is, in turn, how the number 1 is represented in binary. This all means that the bitwise operation 5 & 3 results in 1 . What a ride!
The name “bitwise” comes from the idea that these operations are performed on “bits” (the numbers 0 or 1), one pair at a time. Afterwards, they are all brought up together in a resulting binary value.
The table below presents all existing bitwise operations in Python:





&  Bitwise AND  5 & 3  101 & 001  1 
  Bitwise OR  5  3  101  011  7 
^  Bitwise XOR (exclusive OR)  5 ^ 3  101 ^ 011  6 
~  Bitwise NOT (complement)  ~5  ~101  6 
<<  Left shift  5 << 1  101 << 1  10 
>>  Right shift  5 >> 1  101 >> 1  2 
Operator Precedence in Python
Operator precedence determines the order in which operators are evaluated in an expression. Operators with higher precedence are evaluated first.
For example, the fact that the exponentiation operator ( ** ) has a higher precedence than the addition operator ( + ) means that the expression 2 ** 3 + 4 is seen by Python as (2 ** 3) + 4 . The order of operation is exponentiation and then addition. To override operator precedence, you need to explicitly use parentheses to encapsulate a part of the expression, i.e. 2 ** (3 + 4) .
The table below illustrates the operator precedence in Python. Operators in the earlier rows have a higher precedence:



1  Parentheses  ( ) 
2  Exponentiation  ** 
3  Unary operators, Bitwise NOT  +x, x, ~x 
4  Multiplication, division, and modulo  *, /, //, % 
5  Addition and subtraction  +,  
6  Bitwise shifts  <<, >> 
7  Bitwise AND  & 
8  Bitwise XOR  ^ 
9  Bitwise OR   
10  Comparison, identity, and membership  <, <=, >, >=, ==, !=, is, is not, in, not in 
11  Logical not  not 
12  Logical and  and 
13  Logical or  or 
Want to Learn More About Python Operators?
In this article, we've covered every single Python operator. This includes arithmetic, assignment, comparison, logical, identity, membership, and bitwise operators. Understanding these operators is crucial for writing Python code effectively!
For those looking to dive deeper into Python, consider exploring our Learn Programming with Python track . It consists of five indepth courses and over 400 exercises for you to master the language. You can also challenge yourself with our article on 10 Python practice exercises for beginners !
You may also like
How Do You Write a SELECT Statement in SQL?
What Is a Foreign Key in SQL?
Enumerate and Explain All the Basic Elements of an SQL Query
Python Operators: Arithmetic, Assignment, Comparison, Logical, Identity, Membership, Bitwise
Operators are special symbols that perform some operation on operands and returns the result. For example, 5 + 6 is an expression where + is an operator that performs arithmetic add operation on numeric left operand 5 and the right side operand 6 and returns a sum of two operands as a result.
Python includes the operator module that includes underlying methods for each operator. For example, the + operator calls the operator.add(a,b) method.
Above, expression 5 + 6 is equivalent to the expression operator.add(5, 6) and operator.__add__(5, 6) . Many function names are those used for special methods, without the double underscores (dunder methods). For backward compatibility, many of these have functions with the double underscores kept.
Python includes the following categories of operators:
Arithmetic Operators
Assignment operators, comparison operators, logical operators, identity operators, membership test operators, bitwise operators.
Arithmetic operators perform the common mathematical operation on the numeric operands.
The arithmetic operators return the type of result depends on the type of operands, as below.
 If either operand is a complex number, the result is converted to complex;
 If either operand is a floating point number, the result is converted to floating point;
 If both operands are integers, then the result is an integer and no conversion is needed.
The following table lists all the arithmetic operators in Python:
Operation  Operator  Function  Example in Python Shell 

Sum of two operands  +  operator.add(a,b)  
Left operand minus right operand    operator.sub(a,b)  
*  operator.mul(a,b)  
Left operand raised to the power of right  **  operator.pow(a,b)  
/  operator.truediv(a,b)  
equivilant to  //  operator.floordiv(a,b)  
Reminder of  %  operator.mod(a, b) 
The assignment operators are used to assign values to variables. The following table lists all the arithmetic operators in Python:
Operator  Function  Example in Python Shell 

=  
+=  operator.iadd(a,b)  
=  operator.isub(a,b)  
*=  operator.imul(a,b)  
/=  operator.itruediv(a,b)  
//=  operator.ifloordiv(a,b)  
%=  operator.imod(a, b)  
&=  operator.iand(a, b)  
=  operator.ior(a, b)  
^=  operator.ixor(a, b)  
>>=  operator.irshift(a, b)  
<<=  operator.ilshift(a, b) 
The comparison operators compare two operands and return a boolean either True or False. The following table lists comparison operators in Python.
Operator  Function  Description  Example in Python Shell 

>  operator.gt(a,b)  True if the left operand is higher than the right one  
<  operator.lt(a,b)  True if the left operand is lower than right one  
==  operator.eq(a,b)  True if the operands are equal  
!=  operator.ne(a,b)  True if the operands are not equal  
>=  operator.ge(a,b)  True if the left operand is higher than or equal to the right one  
<=  operator.le(a,b)  True if the left operand is lower than or equal to the right one 
The logical operators are used to combine two boolean expressions. The logical operations are generally applicable to all objects, and support truth tests, identity tests, and boolean operations.
Operator  Description  Example 

and  True if both are true  
or  True if at least one is true  
not  Returns True if an expression evalutes to false and viceversa 
The identity operators check whether the two objects have the same id value e.i. both the objects point to the same memory location.
Operator  Function  Description  Example in Python Shell 

is  operator.is_(a,b)  True if both are true  
is not  operator.is_not(a,b)  True if at least one is true 
The membership test operators in and not in test whether the sequence has a given item or not. For the string and bytes types, x in y is True if and only if x is a substring of y .
Operator  Function  Description  Example in Python Shell 

in  operator.contains(a,b)  Returns True if the sequence contains the specified item else returns False.  
not in  not operator.contains(a,b)  Returns True if the sequence does not contains the specified item, else returns False. 
Bitwise operators perform operations on binary operands.
Operator  Function  Description  Example in Python Shell 

&  operator.and_(a,b)  Sets each bit to 1 if both bits are 1.  
  operator.or_(a,b)  Sets each bit to 1 if one of two bits is 1.  
^  operator.xor(a,b)  Sets each bit to 1 if only one of two bits is 1.  
~  operator.invert(a)  Inverts all the bits.  
<<  operator.lshift(a,b)  Shift left by pushing zeros in from the right and let the leftmost bits fall off.  
>>  operator.rshift(a,b)  Shift right by pushing copies of the leftmost bit in from the left, and let the rightmost bits fall off. 
 Compare strings in Python
 Convert file data to list
 Convert User Input to a Number
 Convert String to Datetime in Python
 How to call external commands in Python?
 How to count the occurrences of a list item?
 How to flatten list in Python?
 How to merge dictionaries in Python?
 How to pass value by reference in Python?
 Remove duplicate items from list in Python
 More Python articles
We are a team of passionate developers, educators, and technology enthusiasts who, with their combined expertise and experience, create in depth, comprehensive, and easy to understand tutorials.We focus on a blend of theoretical explanations and practical examples to encourages hands  on learning. Visit About Us page for more information.
 Python Questions & Answers
 Python Skill Test
 Python Latest Articles
Python Programming
Practice Python Exercises and Challenges with Solutions
Free Coding Exercises for Python Developers. Exercises cover Python Basics , Data structure , to Data analytics . As of now, this page contains 18 Exercises.
What included in these Python Exercises?
Each exercise contains specific Python topic questions you need to practice and solve. These free exercises are nothing but Python assignments for the practice where you need to solve different programs and challenges.
 All exercises are tested on Python 3.
 Each exercise has 1020 Questions.
 The solution is provided for every question.
 Practice each Exercise in Online Code Editor
These Python programming exercises are suitable for all Python developers. If you are a beginner, you will have a better understanding of Python after solving these exercises. Below is the list of exercises.
Select the exercise you want to solve .
Basic Exercise for Beginners
Practice and Quickly learn Python’s necessary skills by solving simple questions and problems.
Topics : Variables, Operators, Loops, String, Numbers, List
Python Input and Output Exercise
Solve input and output operations in Python. Also, we practice file handling.
Topics : print() and input() , File I/O
Python Loop Exercise
This Python loop exercise aims to help developers to practice branching and Looping techniques in Python.
Topics : Ifelse statements, loop, and while loop.
Python Functions Exercise
Practice how to create a function, nested functions, and use the function arguments effectively in Python by solving different questions.
Topics : Functions arguments, builtin functions.
Python String Exercise
Solve Python String exercise to learn and practice String operations and manipulations.
Python Data Structure Exercise
Practice widely used Python types such as List, Set, Dictionary, and Tuple operations in Python
Python List Exercise
This Python list exercise aims to help Python developers to learn and practice list operations.
Python Dictionary Exercise
This Python dictionary exercise aims to help Python developers to learn and practice dictionary operations.
Python Set Exercise
This exercise aims to help Python developers to learn and practice set operations.
Python Tuple Exercise
This exercise aims to help Python developers to learn and practice tuple operations.
Python Date and Time Exercise
This exercise aims to help Python developers to learn and practice DateTime and timestamp questions and problems.
Topics : Date, time, DateTime, Calendar.
Python OOP Exercise
This Python Objectoriented programming (OOP) exercise aims to help Python developers to learn and practice OOP concepts.
Topics : Object, Classes, Inheritance
Python JSON Exercise
Practice and Learn JSON creation, manipulation, Encoding, Decoding, and parsing using Python
Python NumPy Exercise
Practice NumPy questions such as Array manipulations, numeric ranges, Slicing, indexing, Searching, Sorting, and splitting, and more.
Python Pandas Exercise
Practice Data Analysis using Python Pandas. Practice Dataframe, Data selection, groupby, Series, sorting, searching, and statistics.
Python Matplotlib Exercise
Practice Data visualization using Python Matplotlib. Line plot, Style properties, multiline plot, scatter plot, bar chart, histogram, Pie chart, Subplot, stack plot.
Random Data Generation Exercise
Practice and Learn the various techniques to generate random data in Python.
Topics : random module, secrets module, UUID module
Python Database Exercise
Practice Python database programming skills by solving the questions step by step.
Use any of the MySQL, PostgreSQL, SQLite to solve the exercise
Exercises for Intermediate developers
The following practice questions are for intermediate Python developers.
If you have not solved the above exercises, please complete them to understand and practice each topic in detail. After that, you can solve the below questions quickly.
Exercise 1: Reverse each word of a string
Expected Output
 Use the split() method to split a string into a list of words.
 Reverse each word from a list
 finally, use the join() function to convert a list into a string
Steps to solve this question :
 Split the given string into a list of words using the split() method
 Use a list comprehension to create a new list by reversing each word from a list.
 Use the join() function to convert the new list into a string
 Display the resultant string
Exercise 2: Read text file into a variable and replace all newlines with space
Given : Assume you have a following text file (sample.txt).
Expected Output :
 First, read a text file.
 Next, use string replace() function to replace all newlines ( \n ) with space ( ' ' ).
Steps to solve this question : 
 First, open the file in a read mode
 Next, read all content from a file using the read() function and assign it to a variable.
 Display final string
Exercise 3: Remove items from a list while iterating
Description :
In this question, You need to remove items from a list while iterating but without creating a different copy of a list.
Remove numbers greater than 50
Expected Output : 
 Get the list's size
 Iterate list using while loop
 Check if the number is greater than 50
 If yes, delete the item using a del keyword
 Reduce the list size
Solution 1: Using while loop
Solution 2: Using for loop and range()
Exercise 4: Reverse Dictionary mapping
Exercise 5: display all duplicate items from a list.
 Use the counter() method of the collection module.
 Create a dictionary that will maintain the count of each item of a list. Next, Fetch all keys whose value is greater than 2
Solution 1 :  Using collections.Counter()
Solution 2 : 
Exercise 6: Filter dictionary to contain keys present in the given list
Exercise 7: print the following number pattern.
Refer to Print patterns in Python to solve this question.
 Use two for loops
 The outer loop is reverse for loop from 5 to 0
 Increment value of x by 1 in each iteration of an outer loop
 The inner loop will iterate from 0 to the value of i of the outer loop
 Print value of x in each iteration of an inner loop
 Print newline at the end of each outer loop
Exercise 8: Create an inner function
Question description : 
 Create an outer function that will accept two strings, x and y . ( x= 'Emma' and y = 'Kelly' .
 Create an inner function inside an outer function that will concatenate x and y.
 At last, an outer function will join the word 'developer' to it.
Exercise 9: Modify the element of a nested list inside the following list
Change the element 35 to 3500
Exercise 10: Access the nested key increment from the following dictionary
Under Exercises: 
Python ObjectOriented Programming (OOP) Exercise: Classes and Objects Exercises
Updated on: December 8, 2021  52 Comments
Python Date and Time Exercise with Solutions
Updated on: December 8, 2021  10 Comments
Python Dictionary Exercise with Solutions
Updated on: May 6, 2023  56 Comments
Python Tuple Exercise with Solutions
Updated on: December 8, 2021  96 Comments
Python Set Exercise with Solutions
Updated on: October 20, 2022  27 Comments
Python if else, for loop, and range() Exercises with Solutions
Updated on: July 6, 2024  296 Comments
Updated on: August 2, 2022  155 Comments
Updated on: September 6, 2021  109 Comments
Python List Exercise with Solutions
Updated on: December 8, 2021  200 Comments
Updated on: December 8, 2021  7 Comments
Python Data Structure Exercise for Beginners
Updated on: December 8, 2021  116 Comments
Python String Exercise with Solutions
Updated on: October 6, 2021  221 Comments
Updated on: March 9, 2021  23 Comments
Updated on: March 9, 2021  51 Comments
Updated on: July 20, 2021  29 Comments
Python Basic Exercise for Beginners
Updated on: August 31, 2023  498 Comments
Useful Python Tips and Tricks Every Programmer Should Know
Updated on: May 17, 2021  23 Comments
Python random Data generation Exercise
Updated on: December 8, 2021  13 Comments
Python Database Programming Exercise
Updated on: March 9, 2021  17 Comments
 Online Python Code Editor
Updated on: June 1, 2022 
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
 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
 Python Home
 ▼Python Exercises
 Exercises Home
 ▼Python Basic
 Basic  PartI
 Basic  PartII
 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 ObjectOriented 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
 Challenges1
 ▼Python Mini Project
 Python Projects
 ▼Python Natural Language Toolkit
 Python NLTK
 ▼Python Project
 Novel Coronavirus (COVID19)
 ..More to come..
Python Math:  Exercises, Practice, Solution
Python math [94 exercises with solution].
[ An editor is available at the bottom of the page to write and execute the scripts. Go to the editor ]
1. Write a Python program to convert degrees to radians. Note : The radian is the standard unit of angular measure, used in many areas of mathematics. An angle's measurement in radians is numerically equal to the length of a corresponding arc of a unit circle; one radian is just under 57.3 degrees (when the arc length is equal to the radius). Test Data: Degree : 15 Expected Result in radians: 0.2619047619047619 Click me to see the sample solution
3. Write a Python program to calculate the area of a trapezoid. Note : A trapezoid is a quadrilateral with two sides parallel. The trapezoid is equivalent to the British definition of the trapezium. An isosceles trapezoid is a trapezoid in which the base angles are equal so. Test Data: Height : 5 Base, first value : 5 Base, second value : 6 Expected Output: Area is : 27.5 Click me to see the sample solution
5. Write a Python program to calculate the surface volume and area of a cylinder. Note: A cylinder is one of the most basic curvilinear geometric shapes, the surface formed by the points at a fixed distance from a given straight line, the axis of the cylinder. Test Data: volume : Height (4), Radius(6) Expected Output: Volume is : 452.57142857142856 Surface Area is : 377.1428571428571 Click me to see the sample solution
6. Write a Python program to calculate the surface volume and area of a sphere. Note: A sphere is a perfectly round geometrical object in threedimensional space that is the surface of a completely round ball. Test Data: Radius of sphere : .75 Expected Output : Surface Area is : 7.071428571428571 Volume is : 1.7678571428571428 Click me to see the sample solution
7. Write a Python program to calculate the arc length of an angle. Note: In a planar geometry, an angle is the figure formed by two rays, called the sides of the angle, sharing a common endpoint, called the vertex of the angle. Angles formed by two rays lie in a plane, but this plane does not have to be a Euclidean plane. Test Data: Diameter of a circle : 8 Angle measure : 45 Expected Output : Arc Length is : 3.142857142857143 Click me to see the sample solution
8. Write a Python program to calculate the area of the sector. Note: A circular sector or circle sector, is the portion of a disk enclosed by two radii and an arc, where the smaller area is known as the minor sector and the larger being the major sector. Test Data: Radius of a circle : 4 Angle measure : 45 Expected Output: Sector Area: 6.285714285714286 Click me to see the sample solution
9. Write a Python program to calculate the discriminant value. Note: The discriminant is the name given to the expression that appears under the square root (radical) sign in the quadratic formula. Test Data: The x value : 4 The y value : 0 The z value : 4 Expected Output: Two Solutions. Discriminant value is : 64.0 Click me to see the sample solution
10. Write a Python program to find the smallest multiple of the first n numbers. Also, display the factors. Test Data: If n = (13) Expected Output : [13, 12, 11, 10, 9, 8, 7] 360360 Click me to see the sample solution
11. Write a Python program to calculate the difference between the squared sum of the first n natural numbers and the sum of squared first n natural numbers.(default value of number=2). Test Data: If sum_difference(12) Expected Output : 5434 Click me to see the sample solution
12. Write a Python program to calculate the sum of all digits of the base to the specified power. Test Data: If power_base_sum(2, 100) Expected Output : 115 Click me to see the sample solution
13. Write a Python program to find out if the given number is abundant. Note: In number theory, an abundant number or excessive number is a number for which the sum of its proper divisors is greater than the number itself. The integer 12 is the first abundant number. Its proper divisors are 1, 2, 3, 4 and 6 for a total of 16. Test Data: If is_abundant(12) If is_abundant(13) Expected Output: True False Click me to see the sample solution
14. Write a Python program to find out if the given number is abundant. Note: Amicable numbers are two different numbers so related that the sum of the proper divisors of each is equal to the other number. (A proper divisor of a number is a positive factor of that number other than the number itself. For example, the proper divisors of 6 are 1, 2, and 3.) Test Data: If amicable_numbers_sum(9999) If amicable_numbers_sum(999) If amicable_numbers_sum(99) Expected Output: 31626 504 0 Click me to see the sample solution
15. Write a Python program to return the sum of all divisors of a number. Test Data: If number = 8 If number = 12 Expected Output: 7 16 Click me to see the sample solution
16. Write a Python program to print all permutations of a given string (including duplicates). Click me to see the sample solution
17. Write a Python program to print the first n lucky numbers. Lucky numbers are defined via a sieve as follows. Begin with a list of integers starting with 1 : 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, . . . . Now eliminate every second number : 1, 3, 5, 7, 9, 11, 13, 15, 17, 19, 21, 23, 25, ... The second remaining number is 3, so remove every 3rd number: 1, 3, 7, 9, 13, 15, 19, 21, 25, ... The next remaining number is 7, so remove every 7th number: 1, 3, 7, 9, 13, 15, 21, 25, ... Next, remove every 9th number and so on. Finally, the resulting sequence is the lucky numbers. Click me to see the sample solution
18. Write a Python program to compute square roots using the Babylonian method. Perhaps the first algorithm used for approximating √S is known as the Babylonian method, named after the Babylonians, or "Hero's method", named after the firstcentury Greek mathematician Hero of Alexandria who gave the first explicit description of the method. It can be derived from (but predates by 16 centuries) Newton's method. The basic idea is that if x is an overestimate to the square root of a nonnegative real number S then S / x will be an underestimate and so the average of these two numbers may reasonably be expected to provide a better approximation. Click me to see the sample solution
19. Write a Python program to multiply two integers without using the * operator. Click me to see the sample solution
21. Write a Python program to print all primes (Sieve_of_Eratosthenes) smaller than or equal to a specified number. In mathematics, the sieve of Eratosthenes, one of a number of prime number sieves, is a simple, ancient algorithm for finding all prime numbers up to any given limit. It does so by iteratively marking as composite (i.e., not prime) the multiples of each prime, starting with the multiples of 2. Click me to see the sample solution
22. Write a Python program to find the next smallest palindrome of a specified number. Click me to see the sample solution
23. Write a Python program to find the next and previous palindromes of a specified number. Click me to see the sample solution
24. Write a Python program to convert a float to ratio.
Expected Output :
Click me to see the sample solution
25. Write a Python program for the nth Catalan numbers. In combinatorial mathematics, the Catalan numbers form a sequence of natural numbers that occur in various counting problems, often involving recursivelydefined objects. They are named after the Belgian mathematician Eugène Charles Catalan (1814 –1894). Click me to see the sample solution
26. Write a Python program to display numbers separated by commas as thousands. Click me to see the sample solution
27. Write a Python program to calculate the distance between two points using latitude and longitude.
28. Write a Python program to calculate the area of a regular polygon.
29. Write a Python program to calculate the wind chill index.
30. Write a Python program to find the roots of a quadratic function.
31. Write a Python program to convert a decimal number to a binary number.
32. Write a Python program to print a complex number and its real and imaginary parts.
33. Write a Python program to add, subtract, multiply, and divide two complex numbers.
34. Write a Python program to get the length and the angle of a complex number.
35. Write a Python program to convert Polar coordinates to rectangular coordinates.
36. Write a Python program to find the maximum and minimum numbers from the specified decimal numbers.
Decimal numbers : 2.45, 2.69, 2.45, 3.45, 2.00, 0.04, 7.25
37. Write a Python program to find the sum of the following decimal numbers and display the numbers in sorted order.
38. Write a Python program to get the square root and exponential of a given decimal number.
Decimal number : 1.44
39. Write a Python program to retrieve the current global context (public properties) for all decimal.
40. Write a Python program to round a specified decimal by setting precision (between 1 and 4).
Sample Number : 0.26598 Original Number : 0.26598 Precision 1 : 0.3 Precision 2 : 0.27 Precision 3 : 0.266 Precision 4 : 0.2660
41. Write a Python program to round a specified number upwards towards infinity and down towards negative infinity with precision 4.
42. Write a Python program to get the local and default precision.
43. Write a Python program to display fraction instances of the string representation of a number.
Sample data : '0.7', '2.5', '9.32', '7e1'
44. Write a Python program to create fraction instances of float numbers.
Sample numbers: 0.2, 0.7, 6.5, 6.0
45. Write a Python program to create fraction instances of decimal numbers.
Sample decimal.2' number: Decimal('0), Decimal('0.7'), Decimal('2.5'), Decimal('3.0')
46. Write a Python program to add, subtract, multiply and divide two fractions.
47. Write a Python program to convert a floating point number (PI) to an approximate rational value on the various denominators.
Note: max_denominator=1000000
48. Write a Python program to generate random floating numbers in a specific numerical range.
49. Write a Python program to generate random integers in a specific numerical range.
50. Write a Python program to generate random even integers in a specific numerical range.
51. Write a Python program to get a single random element from a specified string.
52. Write a Python program to shuffle the following elements randomly.
Sample elements : [1, 2, 3, 4, 5, 6, 7]
53. Write a Python program to flip a coin 1000 times and count heads and tails.
54. Write a Python program to print a random sample of words from the system dictionary.
55. Write a Python program to randomly select an item from a list.
56. Write a Python program to calculate the absolute value of a floating point number.
57. Write a Python program to calculate the standard deviation of the following data.
58. Write a Python program to print the floating point of the mantissa, exponent pair.
59. Write a Python program to split the fractional and integer parts of a floating point number.
60. Write a Python program to parse math formulas and put parentheses around multiplication and division.
61. Write a Python program to describe linear regression.
62. Write a Python program to calculate a grid of hexagon coordinates of the given radius given lowerleft and upperright coordinates. The function will return a list of lists containing 6 tuples of x, y point coordinates. These can be used to construct valid regular hexagonal polygons.
63. Write a Python program to create a simple math quiz.
64. Write a Python program to calculate the volume of a tetrahedron.
Note: In geometry, a tetrahedron (plural: tetrahedra or tetrahedrons) is a polyhedron composed of four triangular faces, six straight edges, and four vertex corners. The tetrahedron is the simplest of all the ordinary convex polyhedra and the only one that has fewer than 5 faces.
65. Write a Python program to compute the value of e(2.718281827...) using an infinite series.
66. Write a Python program to create an ASCII waveform.
67. Write a Python program to create a dot string.
68. Write a Python program to create a Pythagorean theorem calculator.
69. Write a Python function to round up a number to specified digits.
70. Write a Python program for a casino simulation.
71. Write a Python program to reverse a range.
72. Write a Python program to create a range for floating numbers.
73. Write a Python program to generate (given an integer n) a square matrix filled with elements from 1 to n raised to the power of 2 in spiral order.
74. Write a Python program to select a random date in the current year.
75. Write a Python program to calculate clusters using the Hierarchical Clustering method.
76. Write a Python program to implement the Euclidean Algorithm to compute the greatest common divisor (GCD).
77. Write a Python program to convert RGB color to HSV color.
78. Write a Python program to find perfect squares between two given numbers.
79. Write a Python program to compute Euclidean distances.
80. Write a Python program to convert an integer to a 2 byte Hex value.
81. Write a Python program to generate a series of distinct random numbers.
82. Write a Python program to convert a given float value to a ratio.
83. Write a Python program to calculate the aliquot sum of a given number.
84. Write a Python program to get the nth tetrahedral number from a given integer(n) value.
85. Write a Python program to get the sum of the powers of all the numbers from start to end (both inclusive).
86. Write a Python program to calculate the Hamming distance between two given values.
87. Write a Python program to cap a number within the inclusive range specified by the given boundary values x and y.
88. Write a Python program to check whether a given number is a Disarium number or an unhappy number.
89. Write a Python program to check if a given number is a repdigit number or not. If the given number is repdigit return true otherwise false. Sample Data: (0) > True (1) > True (1111) > False (9999999) > True Click me to see the sample solution
90. Write a Python program to check if a given number is a Harshad number or not. Return True if the number is Harshad otherwise False. Sample Data: (666) > True (11) > False (144) > None (200) > True Click me to see the sample solution
91. Write a Python program that accepts an integer number with distinct digits and displays the next number containing only distinct digits. Sample Data: 12345) > 12346 (99999) > 102345 (100) > 102 Click me to see the sample solution
92. Write a Python program that checks whether the absolute difference between two consecutive digits is two or not. Return true otherwise false. Sample Data: (666) > False (3579) > True (2468) > True (20420) > False Click me to see the sample solution
93. Write a Python program that takes an integer and rearranges the digits to create two maximum and minimum numbers. Click me to see the sample solution
94. Write a Python program to calculate the sum of all prime numbers in a given list of positive integers. Sample Data: ([1, 3, 4, 7, 9]) > 10 ([]) > Empty list! ([11, 37, 444]) > 48 Click me to see the sample solution
Python Code Editor:
More to Come !
Test your Python skills with w3resource's quiz
Follow us on Facebook and Twitter for latest update.
 Weekly Trends and Language Statistics
7. Basic Python Operators: Arithmetic, Comparison, and Assignment
Diving into Python, one of the most popular programming languages today, it’s crucial to grasp the basics. Operators in Python are the building blocks for performing calculations, making decisions, and storing values. I’ll walk you through the essentials of arithmetic, comparison, and assignment operators, which are foundational for anyone looking to code in Python.
Whether you’re a beginner just starting out or a seasoned coder brushing up on the basics, understanding these operators is key to writing efficient and effective code. From adding numbers to comparing values and assigning data, I’ve got you covered. Let’s unlock the power of Python operators together and make your coding journey a breeze.
Table of Contents
Arithmetic Operators
Python’s arithmetic operators are the backbone of numerical computations in this versatile language. I’ll break them down for you, so you have a clear understanding of how each operator works and where it’s applicable.
Addition and Subtraction
The Addition ( + ) and Subtraction (  ) operators are straightforward. You’ll use them for adding or subtracting two numbers:
Subtraction
Multiplication and division.
For Multiplication ( * ) and Division ( / ), Python obeys the typical order of operations to ensure accurate results:
Multiplication
Remember, division always produces a float, even if you’re dividing two integers.
Modulus and Exponentiation
Moving on, the Modulus ( % ) operator finds the remainder after division of one number by another. It’s particularly useful in algorithms that require you to determine if a number is even or odd. Meanwhile, the Exponentiation ( ** ) operator raises one number, the base, to the power of another, the exponent:
Exponentiation
Floor division.
Lastly, Floor Division ( // ) divides and rounds down to the nearest whole number:
Mastering these operations is a must for any task that requires mathematical calculations. Whether you’re building financial models or creating games, arithmetic operators are your fundamental tools. Next, let’s move on to another set of operators that are as critical as arithmetic ones: comparison operators. This will help you make decisions in your code based on the data at hand.
When diving into Python, one of the fundamental tools in your programmer’s kit is the addition operator. Simple to use, it’s represented by the + sign and performs exactly what you’d expect—adds together two values. In practice, here’s how it plays out:
Adding integers
Adding floats.
This operator doesn’t just handle numerical data types like integers and floats, it can also concatenate strings and lists, making it extremely versatile:
Concatenating strings
Combining lists.
Furthermore, the addition operator can be used in an augmented assignment format to both add and assign a value to a variable in one expression:
Augmented assignment
It’s important to note that while addition in Python is fairly straightforward, it’s essential to consider the data type of the items you’re working with to avoid errors. For instance, trying to add together a string and an integer will result in a TypeError, as Python expects homogeneity in addition operations.
As you become more skilled with Python, you’ll find that the addition operator is not just about arithmetic. It’s a powerful tool that allows you to accumulate values, construct strings, merge data structures, and much more. Whether you’re calculating sums or constructing complex data payloads, the addition operator remains a reliable ally in your coding endeavors.
Just as the addition operator plays a crucial role in Python, the subtraction operator is equally fundamental for performing arithmetic calculations. Signified by a minus sign (  ), subtraction in Python allows you to calculate the difference between numbers, and just like addition, can also be used with various data types.
When working with integers and floats , the subtraction operator operates as expected. If I write 10  5 , the output will naturally be 5 . However, subtracting a float from an integer, or vice versa, will result in a float: 7  2.0 yields 5.0 . It’s simple arithmetic but forms the basis for many complex operations in Python programming.
Interestingly, in the realm of strings and lists, Python does not directly support the subtraction operator. Trying to subtract one string from another, or one list from another, results in a TypeError . This is because the concept of subtraction doesn’t naturally extend to these data types in the same intuitive way as it does for numbers. However, developers often work around this limitation by using other methods to achieve similar outcomes, such as string methods or list comprehension.
Augmented assignment with subtraction is also available in Python. Using = allows for a value to be subtracted from a variable and the result assigned back to that variable in a single, concise step. For example, I can write x = 2 and whatever value x held would be decremented by 2 .
Remember, while Python’s subtraction operator might seem straightforward, its application is broad, acting as one of the pillars of mathematical operations in coding. From calculating simple differences to adjusting values on the fly, subtraction is vital for data manipulation and needs to be understood in depth by any aspiring Python programmer.
When it comes to programming in Python, the multiplication operator is as fundamental as it gets. Denoted by the asterisk (*), this operator allows for the product of two numbers, be they integers or floats. Here’s a quick example: if I write 3 * 4 , Python outputs 12 . This same principle applies to floats: 2.5 * 4.0 returns 10.0 .
But multiplication isn’t limited to numbers alone. Python’s flexibility shines when the multiplication operator is applied to strings. For instance, 'Python!' * 3 gives us 'Python!Python!Python!' , repeating the string thrice. It’s important to remember, this operation doesn’t combine separate strings — it repeats the same string multiple times.
Lists see similar benefits. Multiplying a list by an integer repeats the list’s contents. Therefore, [1, 2, 3] * 2 transforms into [1, 2, 3, 1, 2, 3] . This can be particularly useful when initializing a list with a fixed number of identical elements without manually typing them out.
I should point out that Python enforces type consistency when using the multiplication operator. Attempts to multiply incompatible types, like a string by a list, will result in a TypeError . This ensures that you’re aware of the data types you’re working with and helps maintain clean code.
Moreover, Python supports multiplications using external libraries like NumPy, which offer advanced features for array multiplications. In these scenarios, the multiplication operator can perform operations like matrix multiplications and dot products, taking Python’s capabilities well beyond basic arithmetic.
Using multiplication operator with caution is recommended, particularly when applying it to lists, since it could potentially lead to memory issues. Large list operations can consume significant amounts of memory and slow down performance, especially if you’re repeating a substantial list. Hence, always assess the impact on your code’s efficiency and memory usage before running such operations.
When we dive into the world of Python arithmetic, the division operator emerges as a crucial tool for numerical calculations. Python uses the forward slash (/) for division, providing a straightforward way to divide numbers. This operator can handle both integers and floats with ease. Here’s a quick example: if I write 10 / 5 , Python will give me 2.0 . Notice how the result is a float, not an integer. This is because Python automatically converts integer division results into float for more precision.
But what if you’re interested in integer division? That’s where the floor division operator (//) steps in. If I want to divide 10 by 3 and get an integer result without any decimal places, I’d use 10 // 3 , which yields 3 . It effectively rounds down the result to the nearest whole number. It’s paramount to mention that if there’s a negative number involved, floor division will round towards the negative of infinity. This behavior ensures consistency across different arithmetic operations.
Perhaps less commonly discussed but equally important is the modulus operator (%) , which gives us the remainder of a division operation. If I want to know what’s left over when 10 is divided by 3 , 10 % 3 would return 1 .
Knowing how to handle division in Python is particularly vital in data analysis and scientific computations, where precision and the type of division are key. It’s also important to highlight that Python will raise a ZeroDivisionError if you attempt to divide by zero. Hence, checks for zero are critical before performing division operations to prevent runtime errors.
One might also incorporate libraries like NumPy when dealing with arrays or matrices as these can offer more sophisticated functions and handle division in a way that’s optimized for large datasets. The flexibility of these libraries in handling various numerical operations complements the builtin Python division capabilities.
Remember, just like multiplication, division must be approached with an understanding of the data type involved to avoid type inconsistency errors. By keeping these intricacies in mind, you’ll be able to write more efficient and errorfree code.
When I delve into Python’s arithmetic operations, the modulo operator often stands out. Represented by the % symbol, the modulo provides the remainder of a division operation rather than the quotient. It’s especially handy in various programming scenarios, such as determining odd or even numbers or iterating over a sequence with wraparound.
Understanding the Modulo Operator
To use the modulo operator:
Where dividend is the number you’re dividing and divisor is the number by which you’re dividing. For example, 10 % 3 would return 1 because when dividing 10 by 3, the remainder is 1.
Key Uses of Modulo in Python
 Looping Techniques : When you need to cycle through a list repeatedly, modulo helps to reset the index.
 Even: if number % 2 == 0
 Odd: if number % 2 != 0
 Time Calculations : Modulo is perfect for converting seconds to minutes and hours, ensuring values stay within calendar bounds.
Unlike division operators, the modulo is less prone to runtime errors like ZeroDivisionError , but you still can’t use zero as a divisor. If attempted, Python will raise a ZeroDivisionError , similar to using the division operator.
Integrating modulo requires mindfulness about operand types — a common theme in Python arithmetic. The result of a modulo operation involving floats can be counterintuitive because we’re often taught to think of remainders in the context of integers.
In cases involving negative values:
The operation considers the sign of the divisor, resulting in 2 , because Python’s modulo returns the remainder closest to zero.
For advanced scenarios, external packages might offer specialized functions. NumPy, for instance, provides a variation of the modulo operator that behaves differently with negative values. Choosing the right tool for each job is critical in programming for efficiency and accuracy.
Whenever I’m faced with a problem requiring the determination of a quotient’s remainder, I make sure the modulo operator is top of mind. It’s a small but mighty tool in Python’s operator arsenal and can be the difference between a good and a great solution. With this knowledge, I can navigate numbers with precision and employ effective strategies for commonly faced challenges in programming.
When diving into Python’s arithmetic operators, we quickly come across the power operator , ** , which is used for exponentiation. This operator raises a number to the power of another, making it an invaluable tool when working with powers and roots in Python.
Let’s take a look at how it’s used:
Raising 2 to the power of 3
In this example, 2 is the base and 3 is the exponent. Python beautifully simplifies what could otherwise be a complex mathematical process into a single line of code.
Understanding the rules and behavior of exponentiation in Python is crucial, especially when dealing with large numbers or when performing precision computing. Here are some key points:
 Positive exponents : The base is multiplied by itself as many times as the value of the exponent.
 Negative exponents : Python will return the reciprocal of the base raised to the absolute value of the exponent.
 Zero exponent : Any base raised to the power of zero will always be 1.
The ** operator isn’t just limited to integers. It can also be used with floats to handle scenarios requiring fractional exponents, which is common in scientific computations:
Square root of 9
Remember though, float operations might introduce rounding errors due to the nature of binary representation in computing. It’s always good practice to be aware of this when expecting precise results.
For more complex mathematical operations that go beyond what Python’s builtin functions offer, you might want to look into modules like math or numpy . These libraries have optimized functions for exponentiation and other intricate mathematical computations that ensure accuracy and efficiency.
As we continue to explore operators, it’s essential to practice using them in realworld problems that require exponentiation. There are countless applications, from calculating compound interest to transforming datasets in data science projects. Empowering yourself with the power operator opens up a universe of possibilities in Python programming.
When working with division in Python, you’ll inevitably come across the Floor Division operator, denoted by a double forward slash // . Unlike the standard division operator / that returns a floatingpoint result, floor division rounds down the result to the nearest whole number.
Let’s take a deeper dive into why floor division is crucial for certain calculations. One of the primary uses of floor division is to get an integer quotient from the division of two numbers. For instance, if you’re dividing 7 by 2 using the standard division operator, the result would be 3.5. However, with floor division, the result is simply 3 .
Here are a few scenarios where floor division is particularly handy:
 Allocating resources evenly and determining leftovers
 Working with time calculations , where decimal parts don’t make sense
 Processing images or graphics by ensuring pixel counts remain whole numbers
Consider this code snippet for a better understanding:
It’s important to note that when dealing with negative numbers, floor division can have surprising results. For example:
Although 11 / 3 would typically yield approximately 3.6667, floor division will round this down to 4 . This behavior keeps the floor division consistent, always rounding towards minus infinity, which can be essential for maintaining predictable results in your code.
Using floor division in Python is an easy way to keep your calculations integerbased when needed. Integrating this operator into your toolbox can save time and additional steps, especially when working with loops or array indices where noninteger values could cause errors. Remember to test your code with a variety of inputs to understand how floor division operates across different scenarios.
Comparison Operators
When coding in Python, Comparison Operators are the bread and butter for making decisions. These operators allow me to compare two values and, based on the comparison, return a Boolean value of either True or False .
The Common Comparison Operators Are:
 == : Equal to
 != : Not equal
 > : Greater than
 < : Less than
 >= : Greater than or equal to
 <= : Less than or equal to
These operators are fundamental for control flow, enabling functions like if statements and while loops to make logical decisions. For example, I’ll compare user input to a set value to determine the next steps in a program.
Practical Uses of Comparison Operators
In realworld scenarios, I find comparison operators particularly useful when sorting items, validating user input , or implementing algorithms that require condition checking. They’re also crucial while filtering data , such as when I need to extract specific information from large datasets.
Avoiding Common Pitfalls
A common mistake I can make when using comparison operators is confusing the ‘equal to’ operator == with the assignment operator = . It’s vital to ensure that I’m using the correct operator to avoid unexpected behavior in my code. Another issue to watch out for is the mixup between is and == . While is checks if two variables point to the same object, == evaluates if the values they hold are the same. This distinction is significant when working with mutable objects like lists.
Mastery Through Practice
The more I work with comparison operators, the more intuitive they become. I often incorporate various comparison operations in my practice exercises to get a solid grasp of each operator’s nuances. By combining comparison operators with logical ones like and , or , and not , I can craft complex conditions that can handle multifaceted scenarios in my programs.
Understanding the ‘equal to’ operator in Python is crucial for carrying out effective comparisons. The operator is denoted by two equal signs (==) and is used to determine whether two values are identical. When it comes to programming logic, this operator plays a pivotal role.
Consider a situation where I need to validate user input . I’d use the ‘equal to’ operator to compare the input with a predefined correct answer. If the user’s answer matches the correct answer, the operation evaluates to True .
Here’s a simple code snippet to illustrate its use:
In the code above, if the user_input matches secret_code , the message “Access Granted!” is displayed. Otherwise, the user sees “Access Denied!”
It’s also vital to remember that the ‘equal to’ operator checks for value equality, not identity. Object identity, or whether two variables point to the same object in memory, is checked using the is operator .
Here’s how you shouldn’t confuse ‘equal to’ with the assignment operator:
 Assignment operator ( = ): Assigns a value to a variable.
 Equal to operator ( == ): Compares two values for equality.
Moreover, when working with floatingpoint numbers, programmers need to be cautious of precision issues . Due to the way computers represent floatingpoint numbers, two values that seem identical may not be considered equal. Always validate such comparisons within a tolerance level or use the math.isclose() function for comparing floatingpoint numbers.
Using the ‘equal to’ operator effectively requires a firm grasp of the types of data being compared. Always ensure the operands are comparable and understand how Python treats different data types during comparison. For instance, comparing a string with an integer using ‘equal to’ will result in False because their data types are different.
In my next section, I’ll delve into another comparison operator that is often used side by side with ‘equal to’: the ‘not equal to’ operator.
Not Equal To
While the ‘equal to’ operator checks for similarity, the ‘not equal to’ operator serves the opposite function. Represented by an exclamation point followed by an equal sign (!=) , it determines if two values are different. I often use this operator when I need to execute a block of code only if a certain condition is not met. For instance, when dealing with user input, it’s crucial to ensure the input doesn’t match something specific, like a forbidden password or username.
Here’s a simple scenario:
In this example, the != operator saves the day by preventing users from choosing a restricted username. This safeguard is as vital as allowing correct inputs, especially when considering security implications.
Handling Data Types is another area where the ‘not equal to’ operator comes into play. Since Python is dynamically typed, you don’t always know what data types you’ll receive. So, checking for inequality also requires an understanding of how Python compares different data types. When Python compares an integer and a floatingpoint number, even if their mathematical values are the same, the != operator will consider the different types and may not behave as expected.
It’s especially important to Test Thoroughly when working with != . Situations involving collections like lists and dictionaries might not be straightforward, as the operator checks for inequality between all elements, potentially leading to confusion if not used correctly. Consider how Python treats different container types:
 Lists: Element by element comparison
 Dictionaries: Pair by pair (key and value) comparison
When you master the ‘not equal to’ operator, you enhance your error handling and control flow capabilities dramatically. This improvement leads to more robust and reliable code.
Greater Than
In the universe of Python’s comparison operators, the Greater than symbol > stands tall. It’s straightforward yet potent, enabling me to compare two values and determine if one is larger than the other. This operator is commonly used in control structures like if statements and loops, where decisions hinge on numerical comparisons.
When I apply the > operator, Python does what you’d expect – it checks to see if the value on the left is indeed greater than the value on the right. For instance, if I’ve got two variables, age1 set to 30 and age2 set to 25, writing age1 > age2 would yield True because 30 is, in fact, greater than 25. But the practical applications go far beyond just comparing simple integers.
Imagine working on a piece of code where I need to filter a list of items based on their prices. I’ll loop through each item and use the > operator to select only those whose price exceeds a certain threshold. This kind of operation is crucial in tasks like data analysis, where I’m often sieving through vast quantities of data to find significant figures.
 Syntax: value1 > value2
 Returns: True if value1 is greater than value2 , otherwise False
It’s also important to be aware of how Python handles comparisons between different data types. For example, comparing an integer to a float works seamlessly since Python knows how to interpret these kinds. However, using the > operator between incompatible types, such as an integer and a string, throws a TypeError. Intuitively, it’s comparing apples to oranges, which Python wisely refrains from.
In complex structures like dictionaries, I need to be more careful. Since dictionaries can hold various data types as values, ensuring I’m comparing items of the same type is imperative. Oftentimes, I’d have to iterate over the dictionary’s values and, based on context, apply the > operator to the elements that I can fairly compare.
Leveraging the > operator intelligently can propel conditionbased logic to work precisely as I intend. It’s a cornerstone in building robust Python scripts that respond dynamically to varying data.
Just as crucial as the ‘greater than’ operator, the ‘less than’ operator in Python is denoted by the symbol < . This operator assesses whether the lefthand operand is smaller than the righthand operand. It returns a boolean value – True if the assertion is correct and False otherwise.
Useful in various programming scenarios , the ‘less than’ operator is fundamental when sorting algorithms are in play or when we need to impose a threshold. Here are some common applications:
 Imposing limits within loops
 Conditional expressions in if statements
 Filtering data during analysis
I use the ‘less than’ operator with numbers predominantly, but it’s versatile with other compatible types in Python, such as strings which are compared based on their alphabetical order.
When comparing strings with numbers , however, Python will raise a TypeError . It’s vital to ensure compatibility between the data types to prevent any unintended errors in the code. Keep in mind that specific comparisons involving complex data structures might require casting or additional checks for a smooth experience.
Up next, I’ll tackle the versatile yet simple assignment operators. Thriving in simplicity, these operators play a pivotal role in almost every aspect of a Python script. From variables initialization to the reassignment of values, assignment operators maintain state and control flow within a program, proving their indispensability in the realm of Python coding.
Greater Than or Equal To
When I’m programming in Python, the ‘greater than or equal to’ operator (>=) is equally essential as its counterpart. It’s used to compare two values, checking not only if one value is greater than the other but also if they’re equal. This operator is particularly useful when setting boundary conditions or ranges within my code.
Let’s explore its application with a realworld example . Imagine I’m writing a program that determines if a user is eligible for a senior discount. The eligibility age is 65 or older.
Here, I’m using the >= operator to check if the age entered is 65 or more. If the condition is true, the message ‘Eligible for discount’ is printed.
Moving beyond simple comparisons, the ‘greater than or equal to’ operator is vital in loop structures . For instance, consider processing a list of scores to determine how many are above a certain threshold:
print(f”Scores above threshold: {above_threshold}”)
In this snippet, each score is checked against the threshold, and the counter increases for each score that meets the condition.
Just as with the ‘less than’ operator, ensuring data type compatibility is crucial. Remember, comparing a string and an integer with >= could lead to errors. To maintain the integrity of my programs I ensure the variables in comparison are of the same or coercible types. This prevents unexpected behavior and promotes reliable code execution.
Like the threads of a tapestry, these operators interweave to form the logic of our Python script, making them indispensable tools in my arsenal for crafting efficient and effective code.
As I familiarize myself with these operators I find my scripts growing not only more sophisticated but also more robust. Stepping through each one, the journey through Python’s basic operators continues to unfold, revealing the simplicity and power of the language.
Less Than or Equal To
Just as important as the ‘greater than or equal to’ operator in Python is the ‘less than or equal to’ operator. This operator is denoted by <= and serves a critical role in programming—especially when you need to evaluate whether a value falls below or exactly at a certain threshold. For example, when managing inventory, confirming that stock levels are sufficient before processing a sale is essential. Here’s how it’s used:
In this snippet, Python checks if the order_quantity is less than or equal to stock . If the order quantity is 10 or less, the condition is true, and we proceed to process the order.
Understanding <= in Different Contexts
The <= operator isn’t limited to simple numerical comparisons—it’s also effective in other contexts:
 String Comparison : Strings are compared lexicographically in Python, so you can check if one precedes another alphabetically.
 Date Comparison : When working with date objects, <= ensures that an event occurs before or on a certain date.
Practical Applications of <=
I’ve observed that the use of <= spans a variety of applications:
 Setting thresholds in game development to trigger an event
 Validating user input to ensure it doesn’t exceed a limit
 Analyzing datasets to filter entries based on a condition
It’s crucial to remember that the data types on either side of the <= must be compatible to avoid a TypeError .
Applying the ‘less than or equal to’ operator within loops and conditional statements allows for more complex decisionmaking processes:
This loop will only print numbers that are 5 or less, demonstrating how <= can control the flow of a program. As you can see, employing <= alongside other Python operators enhances the control and precision we have over our code. With this understanding, you’ll be able to craft more intricate and reliable Python programs that handle a multitude of scenarios effectively.
Assignment Operators
Assignment operators in Python are the foundation of variable management and data storage. These operators are used to assign values to variables . The most common assignment operator is the = sign, which might seem straightforward but is the workhorse of just about any Python program. For instance, when I create a variable to keep track of a score in a game, I use the = to set its initial value: score = 0 .
Beyond the basic assignment, Python also provides a suite of compound assignment operators that combine arithmetic operations with assignment. These are incredibly handy for modifying variable values efficiently. They not only make code cleaner and easier to read but often reduce the chance of typing errors in the process. Here are the main ones I frequently utilize:
 += for adding and assignment: counter += 1 increments the counter by one.
 = for subtraction and assignment: health = damage subtracts damage from health.
 *= for multiplication and assignment: price *= discount applies a discount to the price.
 /= for division and assignment: total /= num_items calculates the average price per item.
In Python, these operators do more than just reduce the amount of typing. For example, they can streamline loop operations or increment counters within a loop without having to write out the full assignment. This can make a significant difference in the readability and performance of the code. Let’s say I’m processing a list of numbers to get a total:
Here, the += operator is effortlessly increasing the total with each iteration. Additionally, in scenarios where I’m working with mutable data types like lists, these operators allow for the modification of data in place, which can lead to more memoryefficient code .
Moreover, Python’s assignment operators support chaining , which brings another layer of elegance to variable management. For example, I can initialize multiple variables at once: x = y = z = 0 . It’s also worth noting that Python 3.8 introduced the walrus operator := , which assigns values within an expression, further expanding the realms of assignment possibilities.
Simple Assignment
In mastering Python, Simple assignment is an essential tool in your programming arsenal. It’s the most straightforward form of assigning a value to a variable. You’ve already seen the = operator in action, which serves as the backbone for variable creation and manipulation in the language.
When I use simple assignment, I follow the basic syntax where the variable name comes first, followed by the = sign, and then the value I wish to assign. Here’s an easytounderstand example:
In this case, my_variable now holds the value 10 . It’s a clear, concise method that underpins virtually every Python program I write. Additionally, Python allows for multiple assignments in a single line, further simplifying the code:
Here, x , y , and z are assigned to 1 , 2 , and 3 , respectively. It’s a handy shortcut that I often use to initialize several variables at once.
But simple assignment isn’t just about initializing; it’s also used for reassigning values . If I decide that my_variable needs a new value, a simple reassignment does the trick:
my_variable holds 30 instead of 10 . It’s crucial to remember that in Python, variables are just labels pointing to objects, and reassignment doesn’t affect the object originally referenced; it merely attaches the label to a new object.
Furthermore, Python uses dynamic typing , which means that I don’t need to declare the data type of a variable beforehand. This contrasts with staticallytyped languages, in which variable types must be explicitly stated. Dynamic typing allows for more flexibility and quicker coding—Python figures out the data type on its own:
Initially, dynamic_var starts as an integer with any numerically assigned value but can just as quickly be reassigned to hold a string. This flexibility is one of Python’s strengths, making it an excellent choice for rapid development and iterative coding processes.
Addition Assignment
Shifting gears from simple assignment, let’s delve into addition assignment. In Python, the += operator does more than just add two numbers together; it’s used to add a value to a variable, updating the variable itself in the process. If I have a variable x and I want to increase its value by 10, I’d simply write x += 10 . This is equivalent to x = x + 10 but far more succinct.
What makes addition assignment invaluable is its ability to streamline code. Think about running totals or iterative updates in a loop – that’s where += shines. It’s not just beneficial for numbers; I’ve frequently used addition assignment with strings to concatenate additional text.
Here’s a quick glimpse:
This code snippet would output Hello, World! , demonstrating how += appends text to an existing string.
Common use cases for addition assignment in practical coding scenarios include:
 Accumulating values in counters or sums
 Updating the value of a variable in response to events
 Concatenating strings or lists over multiple iterations
It’s important to note that addition assignment is part of a broader category of compound assignment operators . These operators include others like subtraction assignment ( = ), multiplication assignment ( *= ), and division assignment ( /= ), each performing a similar updateinplace for their respective operations.
One aspect of addition assignment that’s often overlooked is its atomicity in singlethreaded scenarios. When I use x += 1 , it’s a nearguarantee that x will be incremented by exactly one without the risk of interference from other operations, making it safer in certain applications over a separated statement like x = x + 1 .
Embracing addition assignment helps in writing more efficient and readable code . It’s a small piece of syntax that eloquently embodies Python’s philosophy of simplicity and elegance in programming.
Subtraction Assignment
Following the theme of compound assignment operators, let’s delve into subtraction assignment, another handy operator that Python programmers frequently use. Similar to addition assignment, subtraction assignment uses the = operator to subtract a value from a variable and then update that same variable in one succinct step. Subtraction assignment is particularly useful when you need to decrease the value of a variable incrementally, such as when tracking decrements in a loop or managing a countdown.
Practical applications of subtraction assignment are easy to spot in daytoday coding scenarios. For instance, imagine you’re developing a basic game where the player’s health decreases with each enemy encounter. Here’s how subtraction assignment simplifies the code:
player_health = enemy_damage
By employing subtraction assignment, you avoid the more verbose and less intuitive player_health = player_health  enemy_damage , making the code cleaner and more maintainable.
More than just a convenient shortcut, subtraction assignment can knock out a few processor cycles, optimizing performance at a micro level. This might not stand out in smaller scripts, but when you’re dealing with largescale applications, every bit of efficiency counts.
Subtraction assignment plays well within the bounds of atomicity in certain contexts, contributing to safer coding patterns. However, it’s important to note that like all operators, the atomicity of a = operation isn’t guaranteed across all environments, especially in multithreaded applications where race conditions might occur.
To master Python, practicing with these operators is essential. They’re not merely shorthand—they represent a deeper understanding of Python’s design philosophy that favors simplicity over complexity. Incorporating subtraction assignment where appropriate will ensure your code is not only functional but also adheres to Python’s ethos, making it both efficient and elegant.
Moving alongside subtraction assignment, multiplication and division assignment operators offer similar benefits with their unique twists…
Multiplication Assignment
Moving on to multiplication assignment in Python, we encounter the *= operator. This operator functions similarly to subtraction assignment but focuses on multiplying the current value of a variable by another and then updating the variable. Just like subtraction assignment, multiplication assignment streamlines code , making it more readable and efficient. Here’s how you can put it to use:
my_number is now 15
In the above example, my_number originally holds the value of 5. After applying my_number *= 3 , the value of my_number becomes 15. This tool is particularly useful when dealing with iterative multiplication within loops.
One must keep in mind that multiplication assignment can lead to unexpected results when used with mutable data types, such as lists. For instance, using *= on a list will repeat the elements in that list:
my_list is now [1, 2, 3, 1, 2, 3]
This convenience comes with the same caveats as subtraction assignment. Atomicity isn’t assured, especially in multithreaded applications where race conditions might affect the value of the variable before the operation takes place.
Just as subtraction assignment simplified decrementing a value, multiplication assignment makes incrementing values exponentially a succinct operation. It ensures that code isn’t cluttered with longwinded expressions, adhering to Python’s philosophy that “Readability counts”. Practicing these operators allows programmers to harness their true potential, enabling one to write concise and clearly structured code.
While multiplication assignment is ideal for numerical calculations , it also plays a significant role in creating repeated sequences or extending lists within your programs. Implementing the *= operator pushes the envelope on what can be achieved with a single line of Python code, reminding us that sometimes, powerful solutions are just an operator away.
Division Assignment
In Python programming, Division assignment is another operation that streamlines the process of dividing a variable by a number and then updating that variable with the new value. Just like multiplication assignment, division assignment uses a compound operator, which is /= . This operator takes the variable on its left, divides it by the expression on its right, and then assigns the result back to the originally named variable.
Consider the scenario where I have a variable defining a quantity of items and I’d like to split these items evenly among a certain number of people. Instead of using two lines of code—one to divide and another to assign the result—I can simply employ the /= operator to perform both actions simultaneously. Here’s how it’s done:
After this operation, the items variable would contain the value 24, precisely what you’d expect after dividing 120 by 5. Easy and efficient, isn’t it?
It’s important to highlight that the division assignment operator in Python always performs floatingpoint division . This means that even when dividing two integers, the result will be a float . If an integer result is needed, you’d have to manually convert the outcome back to an integer using the int() function or use the floor division assignment operator //= .
However, when using division assignment, a key thing to be cautious about is ZeroDivisionError . This error occurs if the righthand side of the assignment is zero. In realworld applications, it’s always smart to implement error handling to catch and address such potential issues:
While division assignment is extremely useful, it’s also vital to keep in mind that this operator modifies the variable inplace. If the variable is shared across different parts of a program or among multiple threads, one must consider the implications of altering its value through division assignment to avoid unexpected behaviors or conflicts.
Modulo Assignment
When working with Python, I often find the modulo assignment operator as a secret weapon for certain tasks. Modulo assignment `%=“ combines the modulo operation with assignment in one step. This operator takes the current value of a variable, performs a modulo operation with the specified value, and then updates the variable with the result. Here’s how it works in practice:
After executing, my_number becomes 1, because 10 modulo 3 leaves a remainder of 1.
This is particularly useful when I need to:
 Ensure a Value Stays Within a Range : If I’m iterating over a list and want to wrap around when I reach the end, modulo assignment ensures that my index value never exceeds the list length.
 Perform Frequent Remainder Operations : In situations like checking for even or odd numbers, calculating residues in math problems or creating checksums, using %= makes the code cleaner and more efficient.
It’s vital to consider the datatype of the variables involved, as modulo assignment with floatingpoint numbers can lead to unexpected results due to precision issues.
Common errors such as TypeError may occur if I try to use modulo assignment between incompatible data types like strings and integers. For example, my_string %='world' would raise a TypeError because a string cannot be the left operand for this operator.
The beauty of using modulo assignment lies in its ability to simplify code and reduce the chance of mistakes that might happen if I were to split the modulo operation and the assignment into two separate lines. However, like division assignment, I’m cautious to avoid ZeroDivisionError when the righthand side is zero, which is crucial to keeping my code exceptionproof.
Exponentiation Assignment
When I dive into the concept of Exponentiation assignment in Python, it’s evident that it serves a significant role in mathematical operations. This operator combines exponentiation with assignment, streamlining the process of raising a variable to the power of another number. Exponentiation assignment is represented by **= and is a shorthand way to write the operation x = x ** y , where x is the base variable and y is the exponent.
By using this operator, I can conveniently update the value of a variable without needing to type its name multiple times. This is incredibly efficient when dealing with complex calculations or iterating over large datasets . Here’s an example that illustrates its simplicity:
The result would be 125 , as 5 to the power of 3 is 125 . Using exponentiation assignment, the variable x is now updated to hold the value of 125 .
It’s important to remember that while this operator is powerful, it should be used with precision, particularly with floatingpoint numbers, where results might not be exact due to the nature of binary floatingpoint representation.
Moreover, just like with modulo assignment, there’s the need to be aware of and prevent any attempt to raise a number to the power of 0 . Not because it will cause an error, since any number to the power of 0 is 1 , but because it might result in unexpected behavior depending on the use case. Ensuring that the data types are correct before performing operations will help to avoid errors and ensure that the code runs as expected.
In practice, exponentiation assignment can be a very handy tool when coding functions that involve exponential growth , such as compound interest calculations or geometric progression. This operator also highlights Python’s design philosophy of readability, making code more concise and readable at a glance.
Floor Division Assignment
When delving into the realm of arithmetic operators in Python, we often encounter the floor division operator // , which divides two numbers and rounds down to the nearest whole number. Combining this with an assignment operator creates the Floor division assignment operator //= , which is both a timesaver and an enhancer of code legibility. This operator effectively changes the value of a variable to the result of the floor division of its current value by another number.
Imagine working with a dataset that requires the normalization of values by batches. Doing this efficiently requires updating each value without introducing a temporary variable. That’s where //= shines. For example, a //= b translates to a = a // b , hence reducing the lines of code and potential for error.
However, it’s crucial to remember that floor division behaves differently with positive and negative numbers. While 9 // 2 will give you 4 , 9 // 2 will result in 5 , since the result is always rounded down to the nearest whole number. This nuance must be kept in mind to avoid unexpected results, especially when working with datasets that may include negative numbers.
Floor division assignment also plays well with integer and floatingpoint numbers. Precision may vary with floatingpoint numbers, so confirming the accuracy of results is always good practice.
In scenarios involving repeated halving or distribution of elements into bins, //= remains a beneficial tool. Whether you’re rounding down timestamps to the nearest minute, or partitioning resources, it provides a straightforward, readable approach to inplace arithmetic operations.
Python’s emphasis on readability and simplicity is echoed throughout its operator suite – and the floor division assignment operator is a testament to that. It streamlines mathematical operations while maintaining clarity, an essential trait for writing clean and maintainable code .
I’ve taken you through the essentials of Python’s arithmetic, comparison, and assignment operators, highlighting the floor division assignment operator’s role in streamlining your code. Remember, while it’s a powerful tool for batch normalization, it’s crucial to be mindful of its behavior with different number types. With these operators in your toolkit, you’re now better equipped to write more concise and readable Python scripts. Embrace these fundamentals, and you’ll see your coding efficiency soar.
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 assignment operators.
Assignment operators are used to assign values to variables:
Operator  Example  Same As  Try it 

=  x = 5  x = 5  
+=  x += 3  x = x + 3  
=  x = 3  x = x  3  
*=  x *= 3  x = x * 3  
/=  x /= 3  x = x / 3  
%=  x %= 3  x = x % 3  
//=  x //= 3  x = x // 3  
**=  x **= 3  x = x ** 3  
&=  x &= 3  x = x & 3  
=  x = 3  x = x  3  
^=  x ^= 3  x = x ^ 3  
>>=  x >>= 3  x = x >> 3  
<<=  x <<= 3  x = x << 3 
Related Pages
COLOR PICKER
Contact Sales
If you want to use W3Schools services as an educational institution, team or enterprise, send us an email: [email protected]
Report Error
If you want to report an error, or if you want to make a suggestion, send us an email: [email protected]
Top Tutorials
Top references, top examples, get certified.
Python Numerical Methods
This notebook contains an excerpt from the Python Programming and Numerical Methods  A Guide for Engineers and Scientists , the content is also available at Berkeley Python Numerical Methods .
The copyright of the book belongs to Elsevier. We also have this interactive book online for a better learning experience. The code is released under the MIT license . If you find this content useful, please consider supporting the work on Elsevier or Amazon !
< 2.0 Variables and Basic Data Structures  Contents  2.2 Data Structure  Strings >
Variables and Assignment ¶
When programming, it is useful to be able to store information in variables. A variable is a string of characters and numbers associated with a piece of information. The assignment operator , denoted by the “=” symbol, is the operator that is used to assign values to variables in Python. The line x=1 takes the known value, 1, and assigns that value to the variable with name “x”. After executing this line, this number will be stored into this variable. Until the value is changed or the variable deleted, the character x behaves like the value 1.
TRY IT! Assign the value 2 to the variable y. Multiply y by 3 to show that it behaves like the value 2.
A variable is more like a container to store the data in the computer’s memory, the name of the variable tells the computer where to find this value in the memory. For now, it is sufficient to know that the notebook has its own memory space to store all the variables in the notebook. As a result of the previous example, you will see the variable “x” and “y” in the memory. You can view a list of all the variables in the notebook using the magic command %whos .
TRY IT! List all the variables in this notebook
Note that the equal sign in programming is not the same as a truth statement in mathematics. In math, the statement x = 2 declares the universal truth within the given framework, x is 2 . In programming, the statement x=2 means a known value is being associated with a variable name, store 2 in x. Although it is perfectly valid to say 1 = x in mathematics, assignments in Python always go left : meaning the value to the right of the equal sign is assigned to the variable on the left of the equal sign. Therefore, 1=x will generate an error in Python. The assignment operator is always last in the order of operations relative to mathematical, logical, and comparison operators.
TRY IT! The mathematical statement x=x+1 has no solution for any value of x . In programming, if we initialize the value of x to be 1, then the statement makes perfect sense. It means, “Add x and 1, which is 2, then assign that value to the variable x”. Note that this operation overwrites the previous value stored in x .
There are some restrictions on the names variables can take. Variables can only contain alphanumeric characters (letters and numbers) as well as underscores. However, the first character of a variable name must be a letter or underscores. Spaces within a variable name are not permitted, and the variable names are casesensitive (e.g., x and X will be considered different variables).
TIP! Unlike in pure mathematics, variables in programming almost always represent something tangible. It may be the distance between two points in space or the number of rabbits in a population. Therefore, as your code becomes increasingly complicated, it is very important that your variables carry a name that can easily be associated with what they represent. For example, the distance between two points in space is better represented by the variable dist than x , and the number of rabbits in a population is better represented by nRabbits than y .
Note that when a variable is assigned, it has no memory of how it was assigned. That is, if the value of a variable, y , is constructed from other variables, like x , reassigning the value of x will not change the value of y .
EXAMPLE: What value will y have after the following lines of code are executed?
WARNING! You can overwrite variables or functions that have been stored in Python. For example, the command help = 2 will store the value 2 in the variable with name help . After this assignment help will behave like the value 2 instead of the function help . Therefore, you should always be careful not to give your variables the same name as builtin functions or values.
TIP! Now that you know how to assign variables, it is important that you learn to never leave unassigned commands. An unassigned command is an operation that has a result, but that result is not assigned to a variable. For example, you should never use 2+2 . You should instead assign it to some variable x=2+2 . This allows you to “hold on” to the results of previous commands and will make your interaction with Python must less confusing.
You can clear a variable from the notebook using the del function. Typing del x will clear the variable x from the workspace. If you want to remove all the variables in the notebook, you can use the magic command %reset .
In mathematics, variables are usually associated with unknown numbers; in programming, variables are associated with a value of a certain type. There are many data types that can be assigned to variables. A data type is a classification of the type of information that is being stored in a variable. The basic data types that you will utilize throughout this book are boolean, int, float, string, list, tuple, dictionary, set. A formal description of these data types is given in the following sections.
Python Enhancement Proposals
 Python »
 PEP Index »
PEP 636 – Structural Pattern Matching: Tutorial
Matching sequences, matching multiple patterns, matching specific values, matching multiple values, adding a wildcard, composing patterns, or patterns, capturing matched subpatterns, adding conditions to patterns, adding a ui: matching objects, matching positional attributes, matching against constants and enums, going to the cloud: mappings, matching builtin classes, appendix a – quick intro.
This PEP is a tutorial for the pattern matching introduced by PEP 634 .
PEP 622 proposed syntax for pattern matching, which received detailed discussion both from the community and the Steering Council. A frequent concern was about how easy it would be to explain (and learn) this feature. This PEP addresses that concern providing the kind of document which developers could use to learn about pattern matching in Python.
This is considered supporting material for PEP 634 (the technical specification for pattern matching) and PEP 635 (the motivation and rationale for having pattern matching and design considerations).
For readers who are looking more for a quick review than for a tutorial, see Appendix A .
As an example to motivate this tutorial, you will be writing a text adventure. That is a form of interactive fiction where the user enters text commands to interact with a fictional world and receives text descriptions of what happens. Commands will be simplified forms of natural language like get sword , attack dragon , go north , enter shop or buy cheese .
Your main loop will need to get input from the user and split it into words, let’s say a list of strings like this:
The next step is to interpret the words. Most of our commands will have two words: an action and an object. So you may be tempted to do the following:
The problem with that line of code is that it’s missing something: what if the user types more or fewer than 2 words? To prevent this problem you can either check the length of the list of words, or capture the ValueError that the statement above would raise.
You can use a matching statement instead:
The match statement evaluates the “subject” (the value after the match keyword), and checks it against the pattern (the code next to case ). A pattern is able to do two different things:
 Verify that the subject has certain structure. In your case, the [action, obj] pattern matches any sequence of exactly two elements. This is called matching
 It will bind some names in the pattern to component elements of your subject. In this case, if the list has two elements, it will bind action = subject[0] and obj = subject[1] .
If there’s a match, the statements inside the case block will be executed with the bound variables. If there’s no match, nothing happens and the statement after match is executed next.
Note that, in a similar way to unpacking assignments, you can use either parenthesis, brackets, or just comma separation as synonyms. So you could write case action, obj or case (action, obj) with the same meaning. All forms will match any sequence (for example lists or tuples).
Even if most commands have the action/object form, you might want to have user commands of different lengths. For example, you might want to add single verbs with no object like look or quit . A match statement can (and is likely to) have more than one case :
The match statement will check patterns from top to bottom. If the pattern doesn’t match the subject, the next pattern will be tried. However, once the first matching pattern is found, the body of that case is executed, and all further cases are ignored. This is similar to the way that an if/elif/elif/... statement works.
Your code still needs to look at the specific actions and conditionally execute different logic depending on the specific action (e.g., quit , attack , or buy ). You could do that using a chain of if/elif/elif/... , or using a dictionary of functions, but here we’ll leverage pattern matching to solve that task. Instead of a variable, you can use literal values in patterns (like "quit" , 42 , or None ). This allows you to write:
A pattern like ["get", obj] will match only 2element sequences that have a first element equal to "get" . It will also bind obj = subject[1] .
As you can see in the go case, we also can use different variable names in different patterns.
Literal values are compared with the == operator except for the constants True , False and None which are compared with the is operator.
A player may be able to drop multiple items by using a series of commands drop key , drop sword , drop cheese . This interface might be cumbersome, and you might like to allow dropping multiple items in a single command, like drop key sword cheese . In this case you don’t know beforehand how many words will be in the command, but you can use extended unpacking in patterns in the same way that they are allowed in assignments:
This will match any sequences having “drop” as its first elements. All remaining elements will be captured in a list object which will be bound to the objects variable.
This syntax has similar restrictions as sequence unpacking: you can not have more than one starred name in a pattern.
You may want to print an error message saying that the command wasn’t recognized when all the patterns fail. You could use the feature we just learned and write case [*ignored_words] as your last pattern. There’s however a much simpler way:
This special pattern which is written _ (and called wildcard) always matches but it doesn’t bind any variables.
Note that this will match any object, not just sequences. As such, it only makes sense to have it by itself as the last pattern (to prevent errors, Python will stop you from using it before).
This is a good moment to step back from the examples and understand how the patterns that you have been using are built. Patterns can be nested within each other, and we have been doing that implicitly in the examples above.
There are some “simple” patterns (“simple” here meaning that they do not contain other patterns) that we’ve seen:
 Capture patterns (standalone names like direction , action , objects ). We never discussed these separately, but used them as part of other patterns.
 Literal patterns (string literals, number literals, True , False , and None )
 The wildcard pattern _
Until now, the only nonsimple pattern we have experimented with is the sequence pattern. Each element in a sequence pattern can in fact be any other pattern. This means that you could write a pattern like ["first", (left, right), _, *rest] . This will match subjects which are a sequence of at least three elements, where the first one is equal to "first" and the second one is in turn a sequence of two elements. It will also bind left=subject[1][0] , right=subject[1][1] , and rest = subject[3:]
Going back to the adventure game example, you may find that you’d like to have several patterns resulting in the same outcome. For example, you might want the commands north and go north to be equivalent. You may also desire to have aliases for get X , pick up X and pick X up for any X.
The  symbol in patterns combines them as alternatives. You could for example write:
This is called an or pattern and will produce the expected result. Patterns are tried from left to right; this may be relevant to know what is bound if more than one alternative matches. An important restriction when writing or patterns is that all alternatives should bind the same variables. So a pattern [1, x]  [2, y] is not allowed because it would make unclear which variable would be bound after a successful match. [1, x]  [2, x] is perfectly fine and will always bind x if successful.
The first version of our “go” command was written with a ["go", direction] pattern. The change we did in our last version using the pattern ["north"]  ["go", "north"] has some benefits but also some drawbacks in comparison: the latest version allows the alias, but also has the direction hardcoded, which will force us to actually have separate patterns for north/south/east/west. This leads to some code duplication, but at the same time we get better input validation, and we will not be getting into that branch if the command entered by the user is "go figure!" instead of a direction.
We could try to get the best of both worlds doing the following (I’ll omit the aliased version without “go” for brevity):
This code is a single branch, and it verifies that the word after “go” is really a direction. But the code moving the player around needs to know which one was chosen and has no way to do so. What we need is a pattern that behaves like the or pattern but at the same time does a capture. We can do so with an as pattern :
The aspattern matches whatever pattern is on its lefthand side, but also binds the value to a name.
The patterns we have explored above can do some powerful data filtering, but sometimes you may wish for the full power of a boolean expression. Let’s say that you would actually like to allow a “go” command only in a restricted set of directions based on the possible exits from the current_room. We can achieve that by adding a guard to our case. Guards consist of the if keyword followed by any expression:
The guard is not part of the pattern, it’s part of the case. It’s only checked if the pattern matches, and after all the pattern variables have been bound (that’s why the condition can use the direction variable in the example above). If the pattern matches and the condition is truthy, the body of the case executes normally. If the pattern matches but the condition is falsy, the match statement proceeds to check the next case as if the pattern hadn’t matched (with the possible sideeffect of having already bound some variables).
Your adventure is becoming a success and you have been asked to implement a graphical interface. Your UI toolkit of choice allows you to write an event loop where you can get a new event object by calling event.get() . The resulting object can have different type and attributes according to the user action, for example:
 A KeyPress object is generated when the user presses a key. It has a key_name attribute with the name of the key pressed, and some other attributes regarding modifiers.
 A Click object is generated when the user clicks the mouse. It has an attribute position with the coordinates of the pointer.
 A Quit object is generated when the user clicks on the close button for the game window.
Rather than writing multiple isinstance() checks, you can use patterns to recognize different kinds of objects, and also apply patterns to its attributes:
A pattern like Click(position=(x, y)) only matches if the type of the event is a subclass of the Click class. It will also require that the event has a position attribute that matches the (x, y) pattern. If there’s a match, the locals x and y will get the expected values.
A pattern like KeyPress() , with no arguments will match any object which is an instance of the KeyPress class. Only the attributes you specify in the pattern are matched, and any other attributes are ignored.
The previous section described how to match named attributes when doing an object match. For some objects it could be convenient to describe the matched arguments by position (especially if there are only a few attributes and they have a “standard” ordering). If the classes that you are using are named tuples or dataclasses, you can do that by following the same order that you’d use when constructing an object. For example, if the UI framework above defines their class like this:
then you can rewrite your match statement above as:
The (x, y) pattern will be automatically matched against the position attribute, because the first argument in the pattern corresponds to the first attribute in your dataclass definition.
Other classes don’t have a natural ordering of their attributes so you’re required to use explicit names in your pattern to match with their attributes. However, it’s possible to manually specify the ordering of the attributes allowing positional matching, like in this alternative definition:
The __match_args__ special attribute defines an explicit order for your attributes that can be used in patterns like case Click((x,y)) .
Your pattern above treats all mouse buttons the same, and you have decided that you want to accept leftclicks, and ignore other buttons. While doing so, you notice that the button attribute is typed as a Button which is an enumeration built with enum.Enum . You can in fact match against enumeration values like this:
This will work with any dotted name (like math.pi ). However an unqualified name (i.e. a bare name with no dots) will be always interpreted as a capture pattern, so avoid that ambiguity by always using qualified constants in patterns.
You have decided to make an online version of your game. All of your logic will be in a server, and the UI in a client which will communicate using JSON messages. Via the json module, those will be mapped to Python dictionaries, lists and other builtin objects.
Our client will receive a list of dictionaries (parsed from JSON) of actions to take, each element looking for example like these:
 {"text": "The shop keeper says 'Ah! We have Camembert, yes sir'", "color": "blue"}
 If the client should make a pause {"sleep": 3}
 To play a sound {"sound": "filename.ogg", "format": "ogg"}
Until now, our patterns have processed sequences, but there are patterns to match mappings based on their present keys. In this case you could use:
The keys in your mapping pattern need to be literals, but the values can be any pattern. As in sequence patterns, all subpatterns have to match for the general pattern to match.
You can use **rest within a mapping pattern to capture additional keys in the subject. Note that if you omit this, extra keys in the subject will be ignored while matching, i.e. the message {"text": "foo", "color": "red", "style": "bold"} will match the first pattern in the example above.
The code above could use some validation. Given that messages came from an external source, the types of the field could be wrong, leading to bugs or security issues.
Any class is a valid match target, and that includes builtin classes like bool str or int . That allows us to combine the code above with a class pattern. So instead of writing {"text": message, "color": c} we can use {"text": str() as message, "color": str() as c} to ensure that message and c are both strings. For many builtin classes (see PEP 634 for the whole list), you can use a positional parameter as a shorthand, writing str(c) rather than str() as c . The fully rewritten version looks like this:
A match statement takes an expression and compares its value to successive patterns given as one or more case blocks. This is superficially similar to a switch statement in C, Java or JavaScript (and many other languages), but much more powerful.
The simplest form compares a subject value against one or more literals:
Note the last block: the “variable name” _ acts as a wildcard and never fails to match.
You can combine several literals in a single pattern using  (“or”):
Patterns can look like unpacking assignments, and can be used to bind variables:
Study that one carefully! The first pattern has two literals, and can be thought of as an extension of the literal pattern shown above. But the next two patterns combine a literal and a variable, and the variable binds a value from the subject ( point ). The fourth pattern captures two values, which makes it conceptually similar to the unpacking assignment (x, y) = point .
If you are using classes to structure your data you can use the class name followed by an argument list resembling a constructor, but with the ability to capture attributes into variables:
You can use positional parameters with some builtin classes that provide an ordering for their attributes (e.g. dataclasses). You can also define a specific position for attributes in patterns by setting the __match_args__ special attribute in your classes. If it’s set to (“x”, “y”), the following patterns are all equivalent (and all bind the y attribute to the var variable):
Patterns can be arbitrarily nested. For example, if we have a short list of points, we could match it like this:
We can add an if clause to a pattern, known as a “guard”. If the guard is false, match goes on to try the next case block. Note that value capture happens before the guard is evaluated:
Several other key features:
 Like unpacking assignments, tuple and list patterns have exactly the same meaning and actually match arbitrary sequences. An important exception is that they don’t match iterators or strings. (Technically, the subject must be an instance of collections.abc.Sequence .)
 Sequence patterns support wildcards: [x, y, *rest] and (x, y, *rest) work similar to wildcards in unpacking assignments. The name after * may also be _ , so (x, y, *_) matches a sequence of at least two items without binding the remaining items.
 Mapping patterns: {"bandwidth": b, "latency": l} captures the "bandwidth" and "latency" values from a dict. Unlike sequence patterns, extra keys are ignored. A wildcard **rest is also supported. (But **_ would be redundant, so it is not allowed.)
 Subpatterns may be captured using the as keyword: case ( Point ( x1 , y1 ), Point ( x2 , y2 ) as p2 ): ...
 Most literals are compared by equality, however the singletons True , False and None are compared by identity.
 Patterns may use named constants. These must be dotted names to prevent them from being interpreted as capture variable: from enum import Enum class Color ( Enum ): RED = 0 GREEN = 1 BLUE = 2 match color : case Color . RED : print ( "I see red!" ) case Color . GREEN : print ( "Grass is green" ) case Color . BLUE : print ( "I'm feeling the blues :(" )
This document is placed in the public domain or under the CC01.0Universal license, whichever is more permissive.
Source: https://github.com/python/peps/blob/main/peps/pep0636.rst
Last modified: 20230909 17:39:29 GMT
 Stack Overflow for Teams Where developers & technologists share private knowledge with coworkers
 Advertising & Talent Reach devs & technologists worldwide about your product, service or employer brand
 OverflowAI GenAI features for Teams
 OverflowAPI Train & finetune LLMs
 Labs The future of collective knowledge sharing
 About the company Visit the blog
Collectives™ on Stack Overflow
Find centralized, trusted content and collaborate around the technologies you use most.
Q&A for work
Connect and share knowledge within a single location that is structured and easy to search.
Get early access and see previews of new features.
One line ifconditionassignment
I have the following code
I need to set the value of num1 to 20 if someBoolValue is True ; and do nothing otherwise. So, here is my code for that
Is there someway I could avoid the ...else num1 part to make it look cleaner? An equivalent to
I tried replacing it with ...else pass like this: num1=20 if someBoolValue else pass . All I got was syntax error. Nor I could just omit the ...else num1 part.
 ifstatement
 2 Just change it all to num1 = 20 if someBoolValue else 10 . Then you save the num1=10 line as well? – Thomas Ahle Commented Oct 24, 2011 at 8:37
 Thanks. But this is not exactly my code. I meant that num1 exists already... – bdhar Commented Oct 24, 2011 at 8:51
14 Answers 14
I don't think this is possible in Python, since what you're actually trying to do probably gets expanded to something like this:
If you exclude else num1 , you'll receive a syntax error since I'm quite sure that the assignment must actually return something.
As others have already mentioned, you could do this, but it's bad because you'll probably just end up confusing yourself when reading that piece of code the next time:
I'm not a big fan of the num1 = someBoolValue and 20 or num1 for the exact same reason. I have to actually think twice on what that line is doing.
The best way to actually achieve what you want to do is the original version:
The reason that's the best verison is because it's very obvious what you want to do, and you won't confuse yourself, or whoever else is going to come in contact with that code later.
Also, as a side note, num1 = 20 if someBoolValue is valid Ruby code, because Ruby works a bit differently.
 19 Per PEP308 ( docs.python.org/2.5/whatsnew/pep308.html ), the conditional expression can be made clearer if put in paren, as in num1 = (20 if someBoolValue else num1) . – haridsv Commented Apr 22, 2017 at 8:04
 1 Watch out for divide byzero statements though  num_cats = math.ceil(num_humans / my_var) if my_var > 1 else 1 generates divide by zero if my_var is 0, even though the conditional for that code is false – bunkerdive Commented Oct 9, 2021 at 2:32
 7 this is what i have been using .. and looking for an alternate.. thanks anyways!! – bdhar Commented Oct 24, 2011 at 8:24
 How to call this block ? I mean what is it name ? – fuat Commented Dec 1, 2019 at 16:26
 4 it is a ternary operator – Chris Maes Commented Dec 4, 2019 at 16:34
 3 One should not use this approach if looping through large data sets since it introduces an unnecessary assignment in case we end up in the elsestatement. – dapc Commented Dec 12, 2019 at 9:23
For the future time traveler from Google, here is a new way (available from Python 3.8 onward):
This is known as "the walrus operator". More info at the What’s New In Python 3.8 page.
 Thank you for the answer, I was wondering what is this weird syntax and why it doesn't work with python3.7 :D – Andy Commented May 1, 2021 at 23:07
 1 Note that this only available in Python>=3.8 – Amer Sawan Commented Sep 19, 2021 at 13:54
 1 It would be nice to be able to use a right away in the condition like this: if a := b and a != 0 . – Gleb Ignatev Commented Nov 8, 2022 at 21:23
 2 could you please fit the variables to the question? num1 and someBoolValue – PythoNic Commented Feb 10, 2023 at 7:45
 1 @PythoNic they can't because the answer is irrelevant for the question. – carlo Commented Sep 22, 2023 at 16:56
In one line:
But don’t do that. This style is normally not expected. People prefer the longer form for clarity and consistency.
(Equally, camel caps should be avoided. So rather use some_bool_value .)
Note that an inline expression some_value if predicate without an else part does not exist because there would not be a return value if the predicate were false. However, expressions must have a clearly defined return value in all cases. This is different from usage as in, say, Ruby or Perl.
 2 Because it gets hard to read and you'll probably end up getting confused by your own code, and that's never a good idea. – Frost Commented Oct 24, 2011 at 8:20
 1 @bdhar, why do you want to put it on one line? It won't run any faster, it will just be harder for other people to read – John La Rooy Commented Oct 24, 2011 at 8:27
 1 @gnibbler, no reason, actually. i was looking for a shorter form with better readability.. – bdhar Commented Oct 24, 2011 at 8:30
you can use one of the following:
 1 Nice one liner conditional assignment – minhas23 Commented Aug 16, 2017 at 20:01
 How is that "structure" called? I've never seen that in ~6 months of learning Python. – Guimoute Commented Jul 31, 2018 at 13:12
 2 At least these are not assignments, unless you put one in front of them, and second, they will not work the way described here. The first one creates a tuple, then picks one of its elements by index. It will only work for tests that return an integer between 1 and 1, or True / False , since bool is a subclass of int . In all cases where the test returns something that would just evaluate true, it fails with an exception. Second one only works as long as trueVal doesn't evaluate false itself, which would result in falseVal beeing assigned even if the test was true. – Bachsau Commented Dec 12, 2018 at 17:58
 it is nicely short, but also very tricky to safely be used as "recommended pattern", see above comment from Bachsau ... (so I downvoted it) – tverrbjelke Commented Mar 1, 2019 at 11:57
If one line code is definitely going to happen for you, Python 3.8 introduces assignment expressions affectionately known as “the walrus operator”.
The 20 will be assigned to num if the first boolean expression is True . The assignment must be inside parentheses here otherwise you will get a syntax error.
No. I guess you were hoping that something like num1 = 20 if someBoolValue would work, but it doesn't. I think the best way is with the if statement as you have written it:
That's my new final answer. Prior answer was as follows and was overkill for the stated problem. Getting_too_clever == not Good . Here's the prior answer... still good if you want add one thing for True cond and another for False :
You mentioned num1 would already have a value that should be left alone. I assumed num1 = 10 since that's the first statement of the post, so the operation to get to 20 is to add 10 .
produced this output
 Now I'm thinking that I should have answered 'num1 = 10 + 10*(someBoolValue == True)' Problem defined as the 'False' condition as a noop basically. If it needed to be a choice of adding a different value for 'False' then the prior answer is a better fit. Do I edit my post or do this in the comments? – Mike from PSG Commented Dec 10, 2017 at 23:50
If you wish to invoke a method if some boolean is true, you can put else None to terminate the trinary.
Here is what i can suggest. Use another variable to derive the if clause and assign it to num1.
You can definitely use num1 = (20 if someBoolValue else num1) if you want.
 Duplicate of answer(s) above? – Adam Smith Commented Jun 21, 2018 at 16:34
Another way num1 = (20*boolVar)+(num1*(not boolVar))
You can do it this way.
You can solve your problem this way but, using 'try/except block' is not the best practice for python.
Not the answer you're looking for? Browse other questions tagged python ifstatement or ask your own question .
 The Overflow Blog
 From PHP to JavaScript to Kubernetes: how one backend engineer evolved over time
 Where does Postgres fit in a world of GenAI and vector databases?
 Featured on Meta
 We've made changes to our Terms of Service & Privacy Policy  July 2024
 Bringing clarity to status tag usage on meta sites
 Feedback requested: How do you use tag hover descriptions for curating and do...
 What does a new user need in a homepage experience on Stack Overflow?
 Staging Ground Reviewer Motivation
Hot Network Questions
 Can light become a satellite of a black hole?
 Why did General Leslie Groves evade Robert Oppenheimer's question here?
 Completely introduce your friends
 Need strftime() output in the buffer
 How can I draw water level in a cylinder like this?
 Why are most big lakes in North America aligned?
 Is there any video of an airtoair missile shooting down an aircraft?
 Why do National Geographic and Discovery Channel broadcast fake or pseudoscientific programs?
 How to justify our beliefs so that it is not circular?
 Why are volumes of revolution typically taught in Calculus 2 and not Calculus 3?
 How Can this Limit be really Evaluated?
 My enemy sent me this puzzle!
 Deviation from the optimal solution for Solomon instances of CVRPTW
 What is the name of the book about a boy dressed in layers of clothes who is actually a mouse?
 Seth and Cain take turns picking numbers from 1 to 50. Who wins?
 How can these humans cross the ocean(s) at the first possible chance?
 Can I use "historically" to mean "for a long time" in "Historically, the Japanese were almost vegetarian"?
 How can I see contents of maintainer scripts of apt packages?
 Are there different conventions for 'rounding to even'?
 Does a MySQL replication slave need to be as powerful as the master?
 Can I retain the ordinal nature of a predictor while answering a question about it that is inherently binary?
 Power latching circuit MOSFET is stuck ON
 Is 2'6" within the size constraints of small, and what would the weight of a fairy that size be?
 Amount Transfer Between Different Accounts
 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
Python Exercise with Practice Questions and Solutions
Python Exercise: Practice makes you perfect in everything. This proverb always proves itself correct. Just like this, if you are a Python learner, then regular practice of Python exercises makes you more confident and sharpens your skills. So, to test your skills, go through these Python exercises with solutions.
Python is a widely used generalpurpose highlevel language that can be used for many purposes like creating GUI, web Scraping, web development, etc. You might have seen various Python tutorials that explain the concepts in detail but that might not be enough to get hold of this language. The best way to learn is by practising it more and more.
The best thing about this Python practice exercise is that it helps you learn Python using sets of detailed programming questions from basic to advanced. It covers questions on core Python concepts as well as applications of Python in various domains. So if you are at any stage like beginner, intermediate or advanced this Python practice set will help you to boost your programming skills in Python.
List of Python Programming Exercises
In the below section, we have gathered chapterwise Python exercises with solutions. So, scroll down to the relevant topics and try to solve the Python program practice set.
Python List Exercises
 Python program to interchange first and last elements in a list
 Python program to swap two elements in a list
 Python  Ways to find length of list
 Maximum of two numbers in Python
 Minimum of two numbers in Python
>> More Programs on List
Python String Exercises
 Python program to check whether the string is Symmetrical or Palindrome
 Reverse words in a given String in Python
 Ways to remove i’th character from string in Python
 Find length of a string in python (4 ways)
 Python program to print even length words in a string
>> More Programs on String
Python Tuple Exercises
 Python program to Find the size of a Tuple
 Python – Maximum and Minimum K elements in Tuple
 Python – Sum of tuple elements
 Python – Rowwise element Addition in Tuple Matrix
 Create a list of tuples from given list having number and its cube in each tuple
>> More Programs on Tuple
Python Dictionary Exercises
 Python  Sort Python Dictionaries by Key or Value
 Handling missing keys in Python dictionaries
 Python dictionary with keys having multiple inputs
 Python program to find the sum of all items in a dictionary
 Python program to find the size of a Dictionary
>> More Programs on Dictionary
Python Set Exercises
 Find the size of a Set in Python
 Iterate over a set in Python
 Python – Maximum and Minimum in a Set
 Python – Remove items from Set
 Python – Check if two lists have atleast one element common
>> More Programs on Sets
Python Matrix Exercises
 Python – Assigning Subsequent Rows to Matrix first row elements
 Adding and Subtracting Matrices in Python
 Python – Group similar elements into Matrix
 Create an n x n square matrix, where all the submatrix have the sum of opposite corner elements as even
>> More Programs on Matrices
Python Functions Exercises
 How to get list of parameters name from a function in Python?
 How to Print Multiple Arguments in Python?
 Python program to find the power of a number using recursion
 Sorting objects of user defined class in Python
 Functions that accept variable length key value pair as arguments
>> More Programs on Functions
Python Lambda Exercises
 Lambda with if but without else in Python
 Python  Sorting string using order defined by another string
 Python  Find fibonacci series upto n using lambda
 Python program to count Even and Odd numbers in a List
 Python  Find the Number Occurring Odd Number of Times using Lambda expression and reduce function
>> More Programs on Lambda
Python Pattern printing Exercises
 Program to print half Diamond star pattern
 Programs for printing pyramid patterns in Python
 Program to print the diamond shape
 Python  Print an Inverted Star Pattern
 Python Program to print digit pattern
>> More Programs on Python Pattern Printing
Python DateTime Exercises
 Python program to get Current Time
 Get Yesterday’s date using Python
 Python program to print current year, month and day
 Python – Convert day number to date in particular year
 Get Current Time in different Timezone using Python
>> More Programs on DateTime
Python OOPS Exercises
 Python program to build flashcard using class in Python
 Shuffle a deck of card with OOPS in Python
 How to create an empty class in Python?
 Student management system in Python
>> More Programs on Python OOPS
Python Regex Exercises
 Python program to find the type of IP Address using Regex
 Python program to find Indices of Overlapping Substrings
 Python program to extract Strings between HTML Tags
 Python – Check if String Contain Only Defined Characters using Regex
 Python program to find files having a particular extension using RegEx
>> More Programs on Python Regex
Python LinkedList Exercises
 Python program to Search an Element in a Circular Linked List
 Pretty print Linked List in Python
 Python  Stack using Doubly Linked List
 Python  Queue using Doubly Linked List
 Python program to find middle of a linked list using one traversal
>> More Programs on Linked Lists
Python Searching Exercises
 Python Program for Linear Search
 Python Program for Binary Search (Recursive and Iterative)
 Python Program for Anagram Substring Search (Or Search for all permutations)
>> More Programs on Python Searching
Python Sorting Exercises
 Python Program for Bubble Sort
 Python Program for QuickSort
 Python Program for Insertion Sort
 Python Program for Selection Sort
 Python Program for Heap Sort
>> More Programs on Python Sorting
Python DSA Exercises
 Python program to reverse a stack
 Multithreaded Priority Queue in Python
 Check whether the given string is Palindrome using Stack
 Program to Calculate the Edge Cover of a Graph
 Python Program for N Queen Problem
>> More Programs on Python DSA
Python File Handling Exercises
 Read content from one file and write it into another file
 Write a dictionary to a file in Python
 How to check file size in Python?
 Find the most repeated word in a text file
 How to read specific lines from a File in Python?
>> More Programs on Python File Handling
Python CSV Exercises
 Update column value of CSV in Python
 How to add a header to a CSV file in Python?
 Get column names from CSV using Python
 Writing data from a Python List to CSV rowwise
 Convert multiple JSON files to CSV Python
>> More Programs on Python CSV
Python JSON Exercises
 Convert class object to JSON in Python
 Convert JSON data Into a Custom Python Object
 Flattening JSON objects in Python
 Convert CSV to JSON using Python
>> More Programs on Python JSON
Python OS Module Exercises
 How to get file creation and modification date or time in Python?
 Menu Driven Python program for opening the required software Application
 Python Script to change name of a file to its timestamp
 Kill a Process by name using Python
 Finding the largest file in a directory using Python
>> More Programs on OS Module
Python Tkinter Exercises
 Python  Create a GUI Marksheet using Tkinter
 Python  ToDo GUI Application using Tkinter
 Python  GUI Calendar using Tkinter
 File Explorer in Python using Tkinter
 Visiting Card Scanner GUI Application using Python
>> More Programs on Python Tkinter
NumPy Exercises
 How to create an empty and a full NumPy array?
 Create a Numpy array filled with all zeros
 Create a Numpy array filled with all ones
 Replace NumPy array elements that doesn’t satisfy the given condition
 Get the maximum value from given matrix
>> More Programs on NumPy
Pandas Exercises
 Make a Pandas DataFrame with twodimensional list  Python
 How to iterate over rows in Pandas Dataframe
 Create a pandas column using for loop
 Create a Pandas Series from array
 Pandas  Basic of Time Series Manipulation
>> More Programs on Python Pandas
Python Web Scraping Exercises
 How to extract youtube data in Python?
 How to Download All Images from a Web Page in Python?
 Test the given page is found or not on the server Using Python
 How to Extract Wikipedia Data in Python?
 How to extract paragraph from a website and save it as a text file?
>> More Programs on Web Scraping
Python Selenium Exercises
 Download File in Selenium Using Python
 Bulk Posting on Facebook Pages using Selenium
 Google Maps Selenium automation using Python
 Count total number of Links In Webpage Using Selenium In Python
 Extract Data From JustDial using Selenium
>> More Programs on Python Selenium
 Number guessing game in Python
 2048 Game in Python
 Get Live Weather Desktop Notifications Using Python
 8bit game using pygame
 Tic Tac Toe GUI In Python using PyGame
>> More Projects in Python
In closing, we just want to say that the practice or solving Python problems always helps to clear your core concepts and programming logic. Hence, we have designed this Python exercises after deep research so that one can easily enhance their skills and logic abilities.
Please Login to comment...
Similar reads.
 How to Get a Free SSL Certificate
 Best SSL Certificates Provider in India
 Elon Musk's xAI releases Grok2 AI assistant
 What is OpenAI SearchGPT? How it works and How to Get it?
 Content Improvement League 2024: From Good To A Great Article
Improve your Coding Skills with Practice
What kind of Experience do you want to share?
 Computers & Technology
 Programming
Sorry, there was a problem.
Download the free Kindle app and start reading Kindle books instantly on your smartphone, tablet, or computer  no Kindle device required .
Read instantly on your browser with Kindle for Web.
Using your mobile phone camera  scan the code below and download the Kindle app.
Image Unavailable
 To view this video download Flash Player
Follow the author
Python Crash Course, 3rd Edition: A HandsOn, ProjectBased Introduction to Programming 3rd Edition
 Use powerful Python libraries and tools, including pytest, Pygame, Matplotlib, Plotly, and Django
 Make increasingly complex 2D games that respond to keypresses and mouse clicks
 Generate interactive data visualizations using a variety of datasets
 Build apps that allow users to create accounts and manage their own data, and deploy your apps online
 Troubleshoot coding errors and solve common programming problems
 ISBN10 1718502702
 ISBN13 9781718502703
 Edition 3rd
 Publisher No Starch Press
 Publication date January 10, 2023
 Language English
 Dimensions 7 x 1.28 x 9.25 inches
 Print length 552 pages
 See all details
Products related to this item
From the Publisher
"With a patient and experienced pedagogical style, and a combination of thorough language instruction and plenty of illustrative sample code, Python Crash Course is a terrific way to begin learning computer programming in general and the Python language in particular." —Michael J. Ross, web developer and former Slashdot contributor  “All of these projects are well thought out and presented in such a way that learning the subject matter and implementing it is much more an enjoyable pastime rather than an onerous task that must be completed. Eric took the time to deal with some rather complex projects and lay them out in a consistent, logical and pleasant manner that draws the reader into the subject willingly.” —Full Circle Magazine  "While Python Crash Course uses Python to teach you to code, it also teaches clean programming skills that apply to most other languages." —Great Lakes Geek 
About the Author
Eric Matthes is a high school science and math teacher living in Alaska, where he teaches an introductory Python course. He has been writing programs since he was five years old. Eric currently focuses on writing software that addresses inefficiencies in education and brings the benefits of open source software to the field of education. In his spare time he enjoys climbing mountains and spending time with his family.
Customer Reviews  

User experience level  Beginner  Beginner  Beginner  Beginners with prior programming experience  Intermediate  Intermediate 
For readers who want  A gentle, kidfriendly introduction to Python  A fastpaced, thorough introduction to Python  A practical guide to using Python for automating tedious tasks  A thorough introduction to Python for existing programmers  Bridges the gap between novice and professional  Learn how to write powerful, efficient, and reusable code. 
Compatible with Python version  Python 3  Python 3  Python 3  Python 3.x  Python 3.6 and higher  Python 3 
Special features  Kidfriendly, fullcolor code and illustrations  Covers Django, matplotlib and plotly, and pygame  Covers working with files en masse, automating emails and texts, scraping the web, and more  Covers syntax basics, functions, parallelism and debugging  Covers decorators, generators, context managers, testing, and web development  Covers modeling, pygame, inheritance, polymorphism, abstraction, and encapsulation 
Page count  368 pages  511 pages  592 pages  752 pages  384 pages  416 pages 
About the Publisher
No Starch Press has published the finest in geek entertainment since 1994, creating both timely and timeless titles like Python Crash Course , Python for Kids , How Linux Works , and Hacking: The Art of Exploitation . An independent, San Franciscobased publishing company, No Starch Press focuses on a curated list of wellcrafted books that make a difference. They publish on many topics, including computer programming, cybersecurity, operating systems, and LEGO. The titles have personality, the authors are passionate experts, and all the content goes through extensive editorial and technical reviews. Long known for its fun, fearless approach to technology, No Starch Press has earned wide support from STEM enthusiasts worldwide.
Editorial Reviews
Product details.
 Publisher : No Starch Press; 3rd edition (January 10, 2023)
 Language : English
 Paperback : 552 pages
 ISBN10 : 1718502702
 ISBN13 : 9781718502703
 Reading age : 10 years and up
 Lexile measure : 1060L
 Grade level : 5  12
 Item Weight : 2.19 pounds
 Dimensions : 7 x 1.28 x 9.25 inches
 #1 in Introductory & Beginning Programming
 #1 in Software Development (Books)
 #1 in Python Programming
Videos for this product
Click to play video
I've been using this book for a few weeks. My thoughts.
Josh @ EasyPars
Python Crash Course book Review
Butterflies In Space Joe
I'm a beginner. Is this reference guide helpful?
About the author, eric matthes.
Discover more of the author’s books, see similar authors, read author blogs and more
Related books
Customer reviews
 5 star 4 star 3 star 2 star 1 star 5 star 85% 10% 3% 1% 1% 85%
 5 star 4 star 3 star 2 star 1 star 4 star 85% 10% 3% 1% 1% 10%
 5 star 4 star 3 star 2 star 1 star 3 star 85% 10% 3% 1% 1% 3%
 5 star 4 star 3 star 2 star 1 star 2 star 85% 10% 3% 1% 1% 1%
 5 star 4 star 3 star 2 star 1 star 1 star 85% 10% 3% 1% 1% 1%
Customer Reviews, including Product Star Ratings help customers to learn more about the product and decide whether it is the right product for them.
To calculate the overall star rating and percentage breakdown by star, we don’t use a simple average. Instead, our system considers things like how recent a review is and if the reviewer bought the item on Amazon. It also analyzed reviews to verify trustworthiness.
Customers say
Customers find the writing and content organized and laid out well for learning. They also say the projects are a blast to make and the content is not difficult to understand.
AIgenerated from the text of customer reviews
Customers find the book wellorganized, laid out well for learning, and straightforward. They also say it's a great beginner's book and an introduction to objectoriented programming with Python.
"...the major Python entry level concepts and introduces some intermediate but easily understandable concepts like unit testing...." Read more
"...Total python newbie, lotta info! Well thought out !" Read more
"...The author has done an excellent job of breaking down complex concepts into digestible sections, making it accessible for both beginners and those..." Read more
"...So far this has been great at explaining everything and giving examples and exercises to reinforce what you are learning." Read more
Customers find the projects in the book a blast to make and the content not difficult to understand. They also appreciate the handson activities on nearly every page.
"...And many assignments to keep your learning fun and etched into your coding memory...." Read more
"...are new to Python it's a great beginners book as well as gives you some nice projects in "Part 2" that you can see different paths to pursue for..." Read more
"Covers python well and has simple projects ." Read more
"...The projects were a blast to make , and the content wasn't difficult to understand...." Read more
Reviews with images
A Seamless Introduction to Python Programming
 Sort reviews by Top reviews Most recent Top reviews
Top reviews from the United States
There was a problem filtering reviews right now. please try again later..
Top reviews from other countries
 About Amazon
 Investor Relations
 Amazon Devices
 Amazon Science
 Sell products on Amazon
 Sell on Amazon Business
 Sell apps on Amazon
 Become an Affiliate
 Advertise Your Products
 SelfPublish with Us
 Host an Amazon Hub
 › See More Make Money with Us
 Amazon Business Card
 Shop with Points
 Reload Your Balance
 Amazon Currency Converter
 Amazon and COVID19
 Your Account
 Your Orders
 Shipping Rates & Policies
 Returns & Replacements
 Manage Your Content and Devices
 Conditions of Use
 Privacy Notice
 Consumer Health Data Privacy Disclosure
 Your Ads Privacy Choices
Yanxiang Zhao
Department of Mathematics, The George Washington University
Teaching Fall 2024 Math3553&6522
Basic information.
Course: Math 3553.80 Numerical Analysis
Semester: Fall 2024
Time: 08/22/202412/09/2024, Mon&Wed 12:45pm02:00pm;
Location: Duques 251
Instructor: Yanxiang Zhao, Phillips Hall 702
Phone: 2029940606
Email: username at email dot gwu dot edu username equals yxzhao
Office Hour: Mon&Wed 02:00pm03:00pm or by appointment
Course Description
This course covers: Linear systems and matrices; Direct and iterative methods for solving linear equations; Sparse matrices; Solution of nonlinear equations; interpolation and approximate representation of functions; splines.
Prerequisites
 Calculus I & II;
 Linear Algebra (Matrix theory);
 Programming language (Matlab, Python, C, etc.);
 Numerical analysis, by Burden, 10th edition, published by Cengage Learning.
Learning Outcomes
As a result of completing this course, the students will be able to:
 solve linear systems by using different numerical methods (direct or indirect methods);
 conduct some basic conditioning analysis on different numerical methods for linear methods;
 understand the convergence and rate of convergence for fixedpoint iteration methods for nonlinear problems;
 use Matlab to numerically solve some simple linear or nonlinear problems.
AI and ChatGPT ( University policies)
The use of AI and ChatGPT is completely forbidden for the homework assignments, quizzes and exams.
Average minimum amount of independent, outofclass, learning expected per week
More than 2/3 of the time you devote to this class should take place outside the classroom (lecture and recitation). Even the best students in the class should plan on spending an average of at least 5 hours a week on homework and other studying. Students who struggle with the material may need to spend more time in order to earn a grade they will find acceptable.
Monday Wednesday
Week01. Aug26Aug30 Aug 26 Aug28
Week02. Sep02Sep06 Labor Day Sep04: quiz01
Week03. Sep09Sep13 Sep09 Sep11
Week04. Sep16Sep20 Sep16 Sep18: quiz02
Week05. Sep23Sep27 Sep23 Sep25
Week06. Sep30Oct04 Sep30 Oct02: quiz03
Week07. Oct07Oct11 Oct 07 Oct09 ( midterm )
Week08. Oct14Oct18 Oct14 Oct16
Week09. Oct21Oct25 Oct21 Oct23: quiz04
Week10. Oct28Nov01 Oct28 Oct30
Week11. Nov04Nov08 Nov04 Nov06: quiz05
Week12. Nov11Nov15 Nov11 Nov13
Week13. Nov18Nov22 Nov18 Nov20 : quiz06
Week14. Nov25Nov29 Thanksgiving Thanksgiving
Week15. Dec02Dec06 Dec02 Dec04
Week16. Dec09Dec13 Dec09 ( last day ) Final (announced later)
NOTE: In accordance with university policy, the final exam will be given during the final exam period (Dec 1217). There will be no accommodation for Christmas flight before scheduled final exam.
Homework will NOT be collected and will NOT be graded. The main purpose of the homework assignment is for you to prepare for the biweekly quizzes and the exams.
 Homework 01 ( PDF ); Solution ( PDF );
 Homework 02 ( PDF ); Solution (PDF);
 Homework 03 ( PDF ); Solution (PDF);
 Homework 04 ( PDF ); Solution ( PDF , PDF2 );
 Homework 05 ( PDF ); Solution (PDF);
 Homework 06 ( PDF ); Solution (PDF);
 Homework 07 ( PDF ); Solution (PDF);
 Homework 08 (PDF); Solution (PDF);
 Homework 09 (PDF); Solution (PDF);
 Homework 10 (PDF); Solution (PDF);
 Homework 11 (PDF); Solution (PDF);
 Homework 12 (PDF); Solution (PDF);
 Homework 13 (PDF); Solution (PDF);
Notes
 Lecture Notes ( PDF );
 Topic summary ( PDF );
 Frobenius matrix ( PDF );
 Gauss elimination and LU decomposition ( PDF );
 Cholesky decomposition ( PDF );
 Orthogonal Polynomials and Gauss Quadrature ( PDF );
Quizzes
There are 6 10minute biweekly quizzes, each out of 25 points, on Wednesday's classes. Each quiz will cover the the lecture of the same Monday, lectures of the previous Monday and Wednesday, and the lecture of the Wednesday before the previous week. The first quiz will only cover the lectures from Aug 26&28. 4 highest quizzes count for the final grade. NO MAKEUP QUIZZES for any excuses .
 Quiz solutions: 1. 2. 3. 4. 5. 6.
There will be an inclass midterm exam on Oct 09, and a final exam in final exam period of Dec 1217.
 No makeup midterm exam for any excuse. If you have to miss the midterm exam due to some personal emergency, you can choose to excuse the midterm, and count your final exam score in the weight of 70%. See the Scheme I & II below for the details.
 The final exam is cumulative . It is your responsibility to ensure that you do not have a schedule conflict involving the final exam.
 Assistance of any type (notes in any form, books, AI, ChatGPT etc.) is strictly banned during exams. Using the work of others on exams is strictly prohibited.
Exam Solutions
 Midterm [PDF];
 Final Exam [PDF];
Your course grade will be determined by your cumulative average at the end of the term and will be based on the following scale:
A  A  B+  B  B  C+  C  C  D+  D  D  
Scale  95%  90%  87%  83%  80%  77%  73%  70%  67%  63%  60% 
Your cumulative average will be the higher one of the following two weighted averages:
HW  Quiz  Midterm  Final  
Scheme I  0%  30%  30%  40% 
Scheme II  0%  30%  0%  70% 
Academic Integrity Code
Academic integrity is an essential part of the educational process, and all members of the GW community take these matters very seriously. As the instructor of record for this course, my role is to provide clear expectations and uphold them in all assessments. Violations of academic integrity occur when students fail to cite research sources properly, engage in unauthorized collaboration, falsify data, and otherwise violate the Code of Academic Integrity . If you have any questions about whether particular academic practices or resources are permitted, you should ask me for clarification. If you are reported for an academic integrity violation, you should contact Conflict Education and Student Accountability (CESA), formerly known as Student Rights and Responsibilities (SRR), to learn more about your rights and options in the process. Consequences can range from failure of assignment to expulsion from the University and may include a transcript notation. For more information, refer to the CESA website at students.gwu.edu/codeacademicintegrity or contact CESA by email [email protected] or phone 2029946757.
University policy on observance of religious holidays
Students must notify faculty during the first week of the semester in which they are enrolled in the course, or as early as possible, but no later than three weeks prior to the absence, of their intention to be absent from class on their day(s) of religious observance. If the holiday falls within the first three weeks of class, the student must inform faculty in the first week of the semester. For details and policy, see provost.gwu.edu/policiesproceduresandguidelines .
Use of Electronic Course Materials and Class Recordings
Students are encouraged to use electronic course materials, including recorded class sessions, for private personal use in connection with their academic program of study. Electronic course materials and recorded class sessions should not be shared or used for noncourse related purposes unless express permission has been granted by the instructor. Students who impermissibly share any electronic course materials are subject to discipline under the Student Code of Conduct. Contact the instructor if you have questions regarding what constitutes permissible or impermissible use of electronic course materials and/or recorded class sessions. Contact Disability Support Services at disabilitysupport.gwu.edu if you have questions or need assistance in accessing electronic course materials.
Academic Commons
Academic Commons is the central location for academic support resources for GW students. To schedule a peer tutoring session for a variety of courses visit go.gwu.edu/tutoring . Visit academiccommons.gwu.edu for study skills tips, finding help with research, and connecting with other campus resources. For questions email [email protected] .
GW Writing Center
GW Writing Center cultivates confident writers in the University community by facilitating collaborative, critical, and inclusive conversations at all stages of the writing process. Working alongside peer mentors, writers develop strategies to write independently in academic and public settings. Appointments can be booked online at gwu.mywconline .
Support for students in and outside the classroom
 Disability Support Services (DSS) 2029948250: Any student who may need an accommodation based on the potential impact of a disability should contact Disability Support Services at disabilitysupport.gwu.edu to establish eligibility and to coordinate reasonable accommodations.
 Student Health Center 2029945300, 24/7: The Student Health Center (SHC) offers medical , counseling/psychological , and psychiatric services to GW students. More information about the SHC is available at healthcenter.gwu.edu . Students experiencing a medical or mental health emergency on campus should contact GW Emergency Services at 2029946111, or off campus at 911.
GW Campus Emergency Information
GW Emergency Services: 2029946111
For situationspecific instructions, refer to GW’s Emergency Procedures guide .
GW Alert is an emergency notification system that sends alerts to the GW community. GW requests students, faculty, and staff maintain current contact information by logging on to alert.gwu.edu . Alerts are sent via email, text, social media, and other means, including the Guardian app. The Guardian app is a safety app that allows you to communicate quickly with GW Emergency Services, 911, and other resources. Learn more at safety.gwu.edu .
Protective Actions
GW prescribes four protective actions that can be issued by university officials depending on the type of emergency. All GW community members are expected to follow directions according to the specified protective action. The protective actions are Shelter, Evacuate, Secure, and Lockdown (details below). Learn more at safety.gwu.edu/gwstandardemergencystatuses .
 Shelter : Protection from a specific hazard; The hazard could be a tornado, earthquake, hazardous material spill, or other environmental emergency; Specific safety guidance will be shared on a casebycase basis. Action : Follow safety guidance for the hazard.
 Evacuate : Need to move people from one location to another; Students and staff should be prepared to follow specific instructions given by first responders and University officials. Action : Evacuate to a designated location; Leave belongings behind; Follow additional instructions from first responders.
 Secure : Threat or hazard outside of buildings or around campus; Increased security, secured building perimeter, increased situational awareness, and restricted access to entry doors. Action : Go inside and stay inside; Activities inside may continue.
 Lockdown : Threat or hazard with the potential to impact individuals inside buildings; Roombased protocol that requires locking interior doors, turning off lights, and staying out of sight of corridor window. Action : Locks, lights, out of sight; Consider Run, Hide, Fight.
 Classroom emergency lockdown buttons : Some classrooms have been equipped with classroom emergency lockdown buttons. If the button is pushed, GWorld Card access to the room will be disabled, and GW Dispatch will be alerted. The door must be manually closed if it is not closed when the button is pushed. Anyone in the classroom will be able to exit, but no one will be able to get in.
Everyone is strongly encouraged to ask questions during class, and during office hours! Should you need further assistance, you may consider hiring a tutor (the department keeps a list of tutors).
This site uses cookies to offer you a better browsing experience. Visit GW’s Website Privacy Notice to learn more about how GW uses cookies.
Defining a symbolic syntax for referring to assignment targets
Full disclosure: I’m not sure this is a good idea (since it is seriously cryptic when you first encounter it, and hard to look up on your own), so I have precisely zero plans to pursue it any further myself. I do, however, find it to be an intriguing idea (prompted by this post in the PEP 736 discussion thread), so it seemed worth sharing in case someone else liked it enough to pick it up and run with it.
The core of the idea:
 A standalone @ symbol on the right hand side of an assignment expression or a regular (not augmented) assignment statement with a single target becomes a shortand that means “assignment target”. Exactly what that means depends on the nature of the assignment target (more details on that below).
 When the assignment target is an identifier, @'' or @"" can be used to mean “the assignment target as a string” (useful for APIs like collections.NamedTuple and typing.NewType )
 In function calls using keyword arguments, @ and @'' are resolved as if the parameter name were a local variable (so param_name=@ would pass a local variable named param_name , and param_name=ns[@''] would be equivalent to param_name=ns["param_name"]
Handling different kinds of assignment targets:
 identifiers: @ is an ordinary variable lookup for that name
 dotted attributes: @ looks up the corresponding attribute rather than setting it. The target expression up to the last dot is only evaluated once for the entire statement rather than being evaluated multiple times
 subscript or slice: @ looks up the corresponding container subscript rather than setting it. The target container expression and subscript expression are only evaluated once for the entire statement rather than being evaluated multiple times
 tuple unpacking: not allowed (specifically due to star unpacking)
 multiple targets: not allowed (which target should @ refer to? Leftmost? Rightmost? Tuple of all targets?)
Disallowed due to the potential for ambiguity:
Note that it isn’t that there’s no reasonable meaning for these (see the various comments about that later in the thread), it’s that the use cases for them are weak and they’d necessarily be harder to interpret than the simpler cases above. If they’re left out initially, it’s straightforward to add them later. If they’re included up front and are later found to be problematic, they’re hard to get rid of.
The mnemonic for remembering this use of the @ (“at”) symbol is the acronym “AT” for “Assignment Target”. Aside from the shared symbol, it has no connection to function decorators or matrix multiplication. As a style recommendation, it would be worth pointing out that combining assignment target references and the matrix multiplication operator in the same expression is intrinsically hard to read (due to the potential confusion between the two uses).
Edit: added a clarifying note to the list of arguably ambiguous targets
If this doesn’t comply with the presented idea, please disregard as offtopic.
I would find assignment targets useful in a forloop where the assignment is implicit.
(I madeup the syntax).
The = @.lower() examples reminded me of the previous .= assignment discussion . Still not sure whether it would be a good idea, but the @ form is more general than the .= special case. Definitely intriguing …
I’d write that numlist = [num + 100 for num in numlist]
The more I think about it, the more I like it. The matrix multiplication thing does seem a bit of an issue though.
Also, I would consider allowing multiple targets on rightmost.
Given it can provide a significant decrease in verbosity, it would be a shame to not be able to take full advantage of it:
Or could specify which one (also, exclamation mark on its own looks pretty bad, adding a number to it makes it a bit better):
That’s semantically different, though, creating a new list instead of modifying an existing list.
I was pretty skeptical when I started reading, but the examples section really sold it to me!
So many of these are things I’ve had to do many times and shrugged about the verbosity.
Especially these:
(and similar)
Infact, the function call examples (PEP 736like) seemed the least useful and intuitive to me, and I’m not quite sure I follow on how they’re consistent with the other assignment targets
The idea wouldn’t be useful in a regular for loop, but could reasonably be defined in comprehensions and generator expressions:
Less useful though, since it’s already acceptable style to use one letter iteration variable names in such cases.
I listed those separately because they’re genuinely different from the pure assignment case. Specifically, they’re looking up the given name in a different context from the one where the name is getting set.
Both tuple unpacking and multiassigment could be allowed by having @ be a tuple in those cases.
My problem with that for multiassigment is that it feels hard to remember (since rightmost and leftmost target remain plausible alternative meanings)
For tuple unpacking, the restriction could be limited to cases without star unpacking rather than all tuple targets, but it just doesn’t seem useful enough to justify that complexity.
I like the idea a lot, and I don’t quite see what can be potentially ambiguous about the two usages quoted above. The reversed example in particular makes the intent of the code that much more pronounced.
I do think that we should disallow mixed usage of matrix multiplication and the proposed assignment target reference as a special case though.
Maybe I’m missing something obvious, but I don’t even see what can be ambiguous about allowing a starred expression in the assignment targets, where the quoted example would intuitively translate into:
Also note that we should preserve the data types of tuples and/or lists in the assignment targets when evaluating them on the RHS:
This would be ambiguous if the function returns a value to an assignment target:
Meng Qinyuan
Aug 27, 2023
Hi @ncoghlan ,
Thanks for sharing this interesting idea! I think the use of @ to refer to assignment targets could be a neat feature, especially for scenarios where we need to reference the target itself, like in the examples with collections.NamedTuple and typing.NewType .
However, I do agree that the initial learning curve might be steep for newcomers, and the potential for confusion with existing uses of @ (decorators and matrix multiplication) is a concern.
It would be great to see more community feedback on this proposal, especially regarding the specific cases where it’s disallowed and how those could be handled differently.
Looking forward to seeing how this evolves!
MengQinyuan
It looks prety Perlish to me.
I’m not sure about this idea but I can see applications of it. One that comes up a lot in SymPy:
It is very easy to make a mistake with that and can easily cause bugs. This would be better:
Or maybe that is excluded because the assignment target is not an identifier…
My current summary of my own feelings: “Wow, that’s cool… I think I hate it”. Super useful (so it would get used), but super cryptic and not pretty to read (so I’d feel bad every time I used it, or saw someone else use it). I want to like it because of its utility and practicality, but the way it looks… ugh.
I only left out string forms for the nonidentifier cases because I couldn’t think of a reasonable use case for them.
Defining it to be the literal source code target string regardless of the target kind wouldn’t be ambiguous though (and wouldn’t change the meaning for identifiers). That way APIs that accept comma separated strings that are expected to match the names of tuple assignment targets could be passed @'' as shown, while those that accept iterables could be passed @''.split(',') .
It would also strengthen the case for allowing @ for target tuples in general (since it would be odd if @'' was allowed, but @ wasn’t).
TensorFlow has the same design.
In my opinion, Jax solved this problem through better design. Instead of creating the symbols by binding a name, you do:
The decorator replaces the passedin value x with a symbol x , produces the expression graph, compiles it, and then calls it with the passedin arguments.
Similarly, SymPy could have been designed this way:
That is not a nice design for something that is often used interactively or in notebooks, short scripts etc. I guess jax has a more limited scope for how the symbols are used but needing to have all code in functions would be quite limiting for most SymPy users (including many who are not really “programmers” as such).
Other computer algebra systems often just allow symbols to be appear automagically without needing to be declared (which is both good and bad). Some like Matlab and Julia which are programming languages that have symbolic capability allow a nicer declaration something like:
Those languages could be extended to support this in a nicer way but Python can’t because it lacks macros and it would be considered out of scope for this sort of thing to be built in. The duplication in x, y = symbols('x, y') is of course not unique to SymPy and applies to the other situations mentioned in this thread as well which might equally be solved by macros in other languages.
Assignment Expressions: The Walrus Operator
 Discussion (8)
In this lesson, you’ll learn about the biggest change in Python 3.8: the introduction of assignment expressions . Assignment expression are written with a new notation (:=) .This operator is often called the walrus operator as it resembles the eyes and tusks of a walrus on its side.
Assignment expressions allow you to assign and return a value in the same expression. For example, if you want to assign to a variable and print its value, then you typically do something like this:
In Python 3.8, you’re allowed to combine these two statements into one, using the walrus operator:
The assignment expression allows you to assign True to walrus , and immediately print the value. But keep in mind that the walrus operator does not do anything that isn’t possible without it. It only makes certain constructs more convenient, and can sometimes communicate the intent of your code more clearly.
One pattern that shows some of the strengths of the walrus operator is while loops where you need to initialize and update a variable. For example, the following code asks the user for input until they type quit :
This code is less than ideal. You’re repeating the input() statement, and somehow you need to add current to the list before asking the user for it. A better solution is to set up an infinite while loop, and use break to stop the loop:
This code is equivalent to the code above, but avoids the repetition and somehow keeps the lines in a more logical order. If you use an assignment expression, then you can simplify this loop further:
This moves the test back to the while line, where it should be. However, there are now several things happening at that line, so it takes a bit more effort to read it properly. Use your best judgement about when the walrus operator helps make your code more readable.
PEP 572 describes all the details of assignment expressions, including some of the rationale for introducing them into the language, as well as several examples of how the walrus operator can be used. The Python 3.8 documentation also includes some good examples of assignment expressions.
Here are a few resources for more info on using bpython, the REPL (Read–Eval–Print Loop) tool used in most of these videos:
 Discover bpython: A Python REPL With IDELike Features
 A better Python REPL: bpython vs python
 bpython Homepage
 bpython Docs
00:00 In this video, you’ll learn about what’s being called the walrus operator. One of the biggest changes in Python 3.8 is the introduction of these assignment expressions. So, what does it do?
00:12 Well, it allows the assignment and the return of a value in the same expression, using a new notation. On the left side, you’d have the name of the object that you’re assigning, and then you have the operator, a colon and an equal sign ( := ), affectionately known as the walrus operator as it resembles the eyes and tusks of a walrus on its side.
00:32 And it’s assigning this expression on the right side, so it’s assigning and returning the value in the same expression. Let me have you practice with this operator with some code.
00:44 Throughout this tutorial, when I use a REPL, I’m going to be using this custom REPL called bpython . I’ll include links on how to install bpython below this video.
00:53 So, how do you use this assignment operator? Let me have you start with a small example. You could have an object named walrus and assign it the value of False , and then you could print it. In Python 3.8, you can combine those two statements and do a single statement using the walrus operator. So inside of print() , you could say walrus , the new object, and use the operator, the assignment expression := , and a space, and then say True . That’s going to do two things. Most notably, in reverse order, it returned the value True . And then it also assigned the value to walrus , and of course the type of 'bool' .
01:38 Keep in mind, the walrus operator doesn’t do anything that isn’t possible without it. It only makes certain constructs a bit more convenient, and can sometimes communicate the intent of your code more clearly.
01:48 Let me show you another example. It’s a pattern that shows some of the strengths of the walrus operator inside of while loops, where you need to initialize and update a variable. For example, create a new file, and name it write_something.py . Here’s write_something.py .
02:09 It starts with inputs , which will be a list. So create a list called inputs .
02:16 Into an object named current , use an input() statement. The input() statement is going to provide a prompt and read a string in from standard input. The prompt will be this, "Write something: " .
02:28 So when the user inputs that, that’ll go into current . So while current != "quit" — if the person has not typed quit yet— you’re going to take inputs and append the current value.
02:44 And then here, you’re asking to "Write something: " again.
02:50 Down here at my terminal, after saving—let’s see, make sure you’re saved. Okay. Now that’s saved.
03:00 So here, I could say, Hello , Welcome , and then finally quit , which then would quit it. So, this code isn’t ideal.
03:08 You’re repeating the input() statement twice, and somehow you need to add current to the list before asking the user for it. So a better solution is going to be to set up maybe an infinite while loop, and then use a break to stop the loop. How would that look?
03:22 You’re going to rearrange this a little bit. Move the while loop up, and say while True:
03:35 and here say if current == "quit": then break . Otherwise, go ahead and append it. So, a little different here, but this is a while loop that’s going to continue as long as it doesn’t get broken out of by someone typing quit . Okay.
03:53 Running it again. And there, you can see it breaking out. Nice. So, that code avoids the repetition and kind of keeps things in a more logical order, but there’s a way to simplify this to use that new assignment expression, the walrus operator. In that case, you’re going to modify this quite a bit.
04:17 Here you’re going to say while , current and then use that assignment operator ( := ) to create current .
04:23 But also, while doing that, check to see that it’s not equal to "quit" . So here, each time that assigns the value to current and it’s returned, so the value can be checked.
04:35 So while , current , assigning the value from the input() , and then if it’s not equal to "quit" , you’re going to append current . Make sure to save.
04:42 Run the code one more time.
04:47 And it works the same. This moves that test all the way back to the while line, where it should be. However, there’s a couple of things now happening all in one line, and that might take a little more effort to read what’s happening and to understand it properly.
05:00 There are a handful of other examples that you could look into to learn a little more about assignment expressions. I’ll include a link to PEP 572, and also a link to the Python docs for version 3.8, both of which include more code examples.
05:14 So you need to use your best judgment as to when this operator’s going to make your code more readable and more useful. In the next video, you’ll learn about the new feature of positionalonly arguments.
rajeshboyalla on Dec. 4, 2019
Why do you use list() to initialize a list rather than using [] ?
Geir Arne Hjelle RP Team on Dec. 4, 2019
My two cents about list() vs [] (I wrote the original article this video series is based on):
 I find spelling out list() to be more readable and easier to notice and interpret than []
 [] is several times faster than list() , but we’re still talking nanoseconds. On my computer [] takes about 15ns, while list() runs in 60ns. Typically, lists are initiated once, so this does not cause any meaningful slowdown of code.
That said, if I’m initializing a list with existing elements, I usually use [elem1, elem2, ...] , since list(...) has different–and sometimes surprising–semantics.
Jason on April 3, 2020
Sorry for my ignorance, did the the standard assignment = operator work in this way? I don’t understand what has been gained from adding the := operator. If anything I think it will allow people to write more obfuscated code. But minds better than mine have been working on this, so I’ll have to take their word it is an improvement.
As for the discussion on whether [] is more readable than list(). I’d never seen list() before, so to me [] is better. I’ve only just come over from the dark 2.7 side so maybe it’s an old python programmer thing?
Oh I checked the operation on the assignment operator. I was obviously wrong. lol Still I think the existing operator could’ve been tweaked to do the same thing as := … I’m still on the fence about that one.
gedece on April 3, 2020
you are right in that the existing operator could have worked, but it can lead to something unexpected.
if you do something like
if (newvar = somevar): it gives a traceback, because you are supposed to use == for comparations.
So if you use the normal operator for this, then that expression is valid and you’ll be hard pressed to realize the mistake.
It then makes complete sense to use a different operator as that helps to clarify intent in code.
Jason on April 6, 2020
Yes, I’ve accidentaly done that in other languages before and it can be a difficult to “see” bug.
varelaautumn on Sept. 26, 2020
I watched this earlier today and now tonight I just can’t stop myself from throwing these walrus operators everywhere.
(I’m new and learning so these are just personal fooling around programs)
For example I have this function which cycles through a bunch of other very simple parsing functions that check if my input string is valid in the context of the game state. If the string doesn’t pass one of these parsers it returns a string with an error message such as “Input must be less than 5 characters”. And then the parse_input function returns that error string.
I mean it’s not a huge change, but it saves an extra call of the function, and I feel like it makes it much more readable.
I’m not sure if this other case might be considered abuse of the walrus operator, but I decided to use it twice in one line.
This function repeatedly asks for input. If the input does not pass the parser functions, then the error will be returned and printed out in the while loop. Otherwise the input was valid and it gets returned.
I’m able to pass my input into a function and check the result of that function all while retaining my input and the return of the function as their own variables to be used in the next line.
I think the walrus operator helped me put all the relevant details on the three lines. Like if you just read the first words of each line, it basically says “while error, print error, else return input_string.” I don’t see how I could have done that without this cool walrus operator so I’m really appreciative for this video you made! I’ve been converted to a strong believer in the walrus operator.
Geir Arne Hjelle RP Team on Sept. 26, 2020
@varelaautumn Nice examples, thanks for sharing!
I agree that the walrus operator will not revolutionize your code, but it can bring these sorts of small improvements that add up in the long run.
Become a Member to join the conversation.
IMAGES
COMMENTS
math. trunc (x) ¶ Return x with the fractional part removed, leaving the integer part. This rounds toward 0: trunc() is equivalent to floor() for positive x, and equivalent to ceil() for negative x.If x is not a float, delegates to x.__trunc__, which should return an Integral value.. math. ulp (x) ¶ Return the value of the least significant bit of the float x:. If x is a NaN (not a number ...
Getting to Know the Python math Module. The Python math module is an important feature designed to deal with mathematical operations. It comes packaged with the standard Python release and has been there from the beginning. Most of the math module's functions are thin wrappers around the C platform's mathematical functions. Since its underlying functions are written in CPython, the math ...
Arithmetic operators are used to perform mathematical operations like addition, subtraction, multiplication, etc. For example, ... Here's a list of different assignment operators available in Python. Operator Name Example = Assignment Operator: a = 7 += Addition Assignment: a += 1 # a = a + 1= Subtraction Assignment:
The assignment operator is one of the most frequently used operators in Python. The operator consists of a single equal sign ( = ), and it operates on two operands. The lefthand operand is typically a variable , while the righthand operand is an expression.
Python Assignment Operators. Assignment operators are used to assign values to variables. They can also perform arithmetic operations in combination with assignments. The canonical assignment operator is the equal sign ( =). Its purpose is to bind a value to a variable: if we write x = 10, we store the value 10 inside the variable x.
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 righthand expression to produce a concrete value or object.
Math module provides builtin functions to find such values and even to change the values between degrees and radians. 1. Finding sine, cosine, and tangent. sin (), cos (), and tan () functions returns the sine, cosine, and tangent of value passed as the argument. The value passed in this function should be in radians.
Python Operators: Arithmetic, Assignment, Comparison, Logical, Identity, Membership, Bitwise. Operators are special symbols that perform some operation on operands and returns the result. For example, 5 + 6 is an expression where + is an operator that performs arithmetic add operation on numeric left operand 5 and the right side operand 6 and ...
These free exercises are nothing but Python assignments for the practice where you need to solve different programs and challenges. All exercises are tested on Python 3. Each exercise has 1020 Questions. The solution is provided for every question. These Python programming exercises are suitable for all Python developers.
Python Identity Operators. Identity operators are used to compare the objects, not if they are equal, but if they are actually the same object, with the same memory location: Operator. Description. Example. Try it. is. Returns True if both variables are the same object. x is y.
Quadratic function : (a * x^2) + b*x + c a: 25 b: 64 c: 36 There are 2 roots: 0.834579 and 1.725421. Click me to see the sample solution. 31. Write a Python program to convert a decimal number to a binary number. Expected Output : Input a binary number: 101011 The decimal value of the number is 43.
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. Syntax: a := expression. Example: In this code, we have a Python list of integers. We have used Python Walrus assignment operator within the Python while loop.
Diving into Python, one of the most popular programming languages today, it's crucial to grasp the basics. Operators in Python are the building blocks for performing calculations, making decisions, and storing values. I'll walk you through the essentials of arithmetic, comparison, and assignment operators, which are foundational for anyone looking to code in Python.
Python Assignment Operators. Assignment operators are used to assign values to variables: Operator. Example. Same As. Try it. =. x = 5. x = 5.
Variables and Assignment¶. When programming, it is useful to be able to store information in variables. A variable is a string of characters and numbers associated with a piece of information. The assignment operator, denoted by the "=" symbol, is the operator that is used to assign values to variables in Python.The line x=1 takes the known value, 1, and assigns that value to the variable ...
An arithmetic operator is a symbol that performs a mathematical operation on one or more operands. The basic arithmetic operators in Python include addition (+), subtraction (), multiplication (*), division (/), floor division (//), modulus (%), and exponentiation (**). These operators are used to perform calculations and return a numeric result.
Return the Sum of Two Numbers. Create a function that takes two numbers as arguments and returns their sum. Examples addition (3, 2) 5 addition (3, 6) 9 addition (7, 3) 10 Notes Don't forget to return the result. If you get stuck on a challenge, find help in the Resources tab.
Each new version of Python adds new features to the language. Back when Python 3.8 was released, the biggest change was the addition of assignment expressions.Specifically, the := operator gave you a new syntax for assigning variables in the middle of expressions. This operator is colloquially known as the walrus operator.. This tutorial is an indepth introduction to the walrus operator.
This PEP is a tutorial for the pattern matching introduced by PEP 634. PEP 622 proposed syntax for pattern matching, which received detailed discussion both from the community and the Steering Council. A frequent concern was about how easy it would be to explain (and learn) this feature. This PEP addresses that concern providing the kind of ...
For the future time traveler from Google, here is a new way (available from Python 3.8 onward): b = 1 if a := b: # this section is only reached if b is not 0 or false. # Also, a is set to b print(a, b) This is known as "the walrus operator". More info at the What's New In Python 3.8 page.
The best way to learn is by practising it more and more. The best thing about this Python practice exercise is that it helps you learn Python using sets of detailed programming questions from basic to advanced. It covers questions on core Python concepts as well as applications of Python in various domains.
About the Author . Eric Matthes is a high school science and math teacher living in Alaska, where he teaches an introductory Python course. He has been writing programs since he was five years old. Eric currently focuses on writing software that addresses inefficiencies in education and brings the benefits of open source software to the field of education.
The official Python docs suggest using math.fmod() over the Python modulo operator when working with float values because of the way math.fmod() calculates the result of the modulo operation. If you're using a negative operand, then you may see different results between math.fmod(x, y) and x % y.You'll explore using the modulo operator with negative operands in more detail in the next section.
Basic Information Course: Math 3553.80 Numerical Analysis Semester: Fall 2024 Time: 08/22/202412/09/2024, Mon&Wed 12:45pm02:00pm; Location: Duques 251 Instructor: Yanxiang Zhao, Phillips Hall 702 Phone: 2029940606 Email: username at email dot gwu dot edu username equals yxzhao Office Hour: Mon&Wed 02:00pm03:00pm or by appointment Course Description This course covers: Linear systems and ...
Exactly what that means depends on the nature of the assignment target (more details on that below). When the assignment target is an identifier, @'' or @"" can be used to mean "the assignment target as a string" (useful for APIs like collections.NamedTuple and typing.NewType
In this lesson, you'll learn about the biggest change in Python 3.8: the introduction of assignment expressions.Assignment expression are written with a new notation (:=).This operator is often called the walrus operator as it resembles the eyes and tusks of a walrus on its side.. Assignment expressions allow you to assign and return a value in the same expression.