Operators and expressions
In Python you will write a large number of expressions. An expression consists of an operator and an operand. It 2+3
's like an expression.
Knowledge points
- Relational/Logical operations
- An expression
- Type conversions
Experiment Step 1. Operator
Operators are symbols that tell the Python interpreter to do some mathematical or logical operations. Some of the basic math operators are as follows:
>>> 2 + 35>>> 23.0 - 320.0>>> 22 / 121.8333333333333333
As long as any one of the operands is a floating-point number, the result is a float.
If the division is not endless, the result will be a decimal, which is natural, if you want to divide, using the //
operator, it will return the integer part of the quotient.
%
is the seek remainder operator:
>>> 14 % 32
1.1. Integer Operation example
The code is as follows:
#!/usr/bin/env python3days = int(input("Enter days: "))months = days // 30days = days % 30print("Months = {} Days = {}".format(months, days))
To run the program:
Start by getting the number of days that the user entered, then get the months and days, and finally print out the numbers. You can use the easier way.
#!/usr/bin/env python3days = int(input("Enter days: "))print("Months = {} Days = {}".format(*divmod(days, 30)))
divmod(num1, num2)
Returns a tuple that contains two values, the first is the value of NUM1 and Num2, the second is the value obtained by NUM1 and num2, and then we use the *
operator to unpack the tuple to get these two values.
2. Relational operators
You can use the following operators to implement relational operations.
Relational operators
Operator |
meaning |
< |
is less than |
<= |
is less than or equal to |
> |
is greater than |
>= |
is greater than or equal to |
== |
is equal to |
!= |
is isn't equal to |
Give some examples:
>>> 1 < 2True>>> 3 > 34False>>> 23 == 45False>>> 34 != 323True
3. Logical operators
For logic with, or, not, we use and
, or
not
these few keywords.
Logical operators and
and or
also known as short-circuiting operators: Their parameters are parsed from left to right and stop once the result can be determined. For example, if A
and C
is true and B
false, it A and B and C
will not parse C
. When acting on a normal non-logical value, the return value of the short-circuiting operator is usually the one that can determine the result first.
Relational operations can be and
made using logical operators and or
combinations, and the results of comparisons can be used not
to reverse the meaning. The precedence of logical operators is lower than the relational operators, among them, not
with the highest priority, the or
lowest priority, so A and not B or C
equals (A and (notB)) or C
. Of course, parentheses can also be used to compare expressions.
Here are some examples:
>>>5 and 44>>> 0 and 40>>> False or 3 or 03>>> 2 > 1 and not 3 > 5 or 4True
4. Shorthand operator
x op= expression is the grammatical form of a shorthand operation. This is equivalent to x = x op expression , for example:
>>> a = 12>>> a += 13>>> a25>>> a /= 3>>> a8.333333333333334>>> a += (26 * 32)>>> a840.3333333333334
shorthand.py Example:
#!/usr/bin/env python3N = 100a = 2while a < N: print(str(a)) a *= a
Operation:
$ ./shorthand.py2416
5. Expressions
Usually when we write an expression, we place a space around each operator, which makes the code more readable, such as:
234 * (45 - 56 / 34)
An example for displaying an expression, noting the precedence of the operator.
#!/usr/bin/env python3a = 9b = 12c = 3x = a - b / 3 + c * 2 - 1y = a - b / (3 + c) * (2 - 1)z = a - (b / (3 + c) * 2) - 1print("X = ", x)print("Y = ", y)print("Z = ", z)
Operation:
$ ./evaluationexp.pyX = 10Y = 7Z = 4
The first one calculates x, the steps are as follows:
9 - 12 / 3 + 3 * 2 -19 - 4 + 3 * 2 - 19 - 4 + 6 - 15 + 6 - 111 - 110
Because the parentheses exist,y and z are calculated differently, and you can verify them yourself.
6. Type conversion
We can perform type conversions manually.
type conversion function |
Conversion Path |
float(string) |
Floating-point value, String |
int(string) |
String-Integer value |
str(integer) |
Integer value-string |
str(float) |
Floating-point value-string |
>>> a = 8.126768>>> str(a)‘8.126768‘
7. program Example 7.1. evaluateequ.py
This program calculates the sequence 1/x+1/(x+1) +1/(x+2) + ... +1/n, we set x = 1,n = 10.
#!/usr/bin/env python3sum = 0for i in range(1, 11): sum += 1 / i print("{:2d} {:6.4f}".format(i , sum))
To run the program:
7.2. quadraticequation.py
This program is used to solve two equations:
#!/usr/bin/env python3import matha = int(input("Enter value of a: "))b = int(input("Enter value of b: "))c = int(input("Enter value of c: "))d = b * b - 4 * a * cif d < 0: print("ROOTS are imaginary")else: root1 = (-b + math.sqrt(d)) / (2 * a) root2 = (-b - math.sqrt(d)) / (2 * a) print("Root 1 = ", root1) print("Root 2 = ", root2)
To run the program:
7.3. salesmansalary.py
This program calculates the salary for a digital camera salesperson. His base salary is 1500, and every camera sold he can get 200 and get 2% of the pumped. The program requires you to enter the number of cameras and the total monthly sales.
#!/usr/bin/env python3basic_salary = 1500bonus_rate = 200commision_rate = 0.02numberofcamera = int(input("Enter the number of inputs sold: "))price = float(input("Enter the total prices: "))bonus = (bonus_rate * numberofcamera)commision = (commision_rate * numberofcamera * price)print("Bonus = {:6.2f}".format(bonus))print("Commision = {:6.2f}".format(commision))print("Gross salary = {:6.2f}".format(basic_salary + bonus + commision))
To run the program:
Summarize
In addition to numerical operations, relational and logical operations are also important components of the program. In addition Python is a strongly typed language, so it is necessary to manually convert the type.
Python Operators and expressions