Python的取模误区

Python's modulo misunderstanding

我有那个代码,但我不认为我真的理解模 returns 余数,不擅长数学..

代码如下:

#import the datetime class
import datetime

#declare and initialize variables
strDeadline = ""
totalNbrDays = 0
nbrWeeks = 0
nbrDays = 0

#Get Today's date
currentDate = datetime.date.today()

#Ask the user for the date of their deadline
strDeadline = input("Please enter the date of your deadline (mm/dd/yyyy): ")

deadline = datetime.datetime.strptime(strDeadline,"%m/%d/%Y").date()

#Calculate number of days between the two dates
totalNbrDays = deadline - currentDate

#For extra credit calculate results in weeks & days

nbrWeeks = totalNbrDays.days / 7

#The modulo will return the remainder of the division
#which will tell us how many days are left 
nbrDays = totalNbrDays.days%7

#display the result to the user

print("You have %d weeks" %nbrWeeks + " and %d days " %nbrDays + "until your deadline.")

模数用于取表达式的余数。

比如做15%7,得到1,这是因为7+7+1=15。

在您的代码中,您将总天数 (totalNbrDays.days) 除以一周中的天数 (7)。让我们以 30 为例来表示总天数。 30%7 等于 2,因为 7+7+7+7+2=30,或 (7*4)=28 和 30-28=2.

当你用一个整数除以另一个整数时,它并不总是均匀分布。例如,23 / 7 会给你 2 的余数,因为 23 = 7 * 3 + 2。 Modulo 为您提供除法运算的余数... 23 % 7 = 2。当您的天数比一周的时间长时,这很有用。您可以使用整数除法(意味着商将是一个整数)来计算周数 23 / 7 = 3 然后取模计算剩余的天数 23 % 7 = 2,告诉您 23 天等于到 3 周零 2 天。