Some Concepts
operand | 操作数、运算数 |
Python Math Operators
# This program gets an item's original price and calculates its sale price,with a 20% discount.
# Get the item's original price.
original_price = float(input("Enter the item's original price: "))
#Calculate the amount of the discount.
discount = original_price * 0.2
# Calculate the sale price.
sale_price = original_price - discount
# Display the sale price.
print("The sale price is ", sale_price)
Floating-Point and Integer Division(浮点数除法和整数除法)
Floating-Point Division
/ |
---|
Division |
Divides one number by another and gives the result as a floating-point number |
e.g.
>>> 5/2
2.5
>>> 3.2/2
1.6
Integer Division
// |
---|
Integer division |
Divides one number by another and gives the result as a whole number |
>>> 5//2
2
>>> 3.2//2
1.0
>>> -5//2
-3
• When the result is positive, it is truncated, which means that its fractional part is
thrown away.
• When the result is negative, it is rounded away from zero to the nearest integer.
Operator Precedence(运算优先级)
The precedence of the math operators, from highest to lowest, are:
- Exponentiation: **
- Multiplication, division, and remainder: * / // %
- Addition and subtraction: + −
When two ** operators share an operand, the operators execute right-to-left. For example, the expression 234 is evaluated as 2**(3**4).
>>> 2**3**4
2417851639229258349412352
>>> 2**(3**4)
2417851639229258349412352
>>> (2**3)**4
4096
The Remainder Operator(取余运算符)
>>> 17%5
2
>>> -17%5
3
e.g.
# Get a number of seconds from the user.
total_seconds = float(input("Enter a number of seconds: "))
# Get the number of hours.
hours = total_seconds // 3600
# Get the number of remaining minutes.
minutes = (total_seconds // 60) % 60
# Get the number of remaining seconds.
seconds = total_seconds % 60
# Display the results.
print('Here is the time in hours, minutes, and seconds:')
print('Hours:', hours)
print('Minutes:', minutes)
print('Seconds:', seconds)
参考文献
[1] Tony Gaddis,Starting Out with Python[M],United Kingdom: Pearson,2019