为什么我不能在我的 f 字符串中输入一个浮点数作为整数

Why can't i type a float as an integer in my f-string

我有一个 class 已经连接到一个 csv 文件,所以我无法在那里添加 'marathon'。

The query was that a club wants to display the number of whole marathons each member has walked. A marathon is 26.22 miles long.

An example of the calculation required is:

If Nikolai Bryant walks 145.6 miles this equates to: 145.6/26.22 miles = 5.59115179 marathons
Nikolai has therefore walked 5 whole marathons.

In the above example ‘Nikolai,Bryant,5’ would be stored.

Write “The number of whole marathons walked by each member is” to the results.txt file

Start loop for each record in members() array

Calculate the number of whole marathons walked

Write the forename, surname and the number of whole marathons to the results.txt file and loop

Close the results.txt file

我有这个试图让 marathon 成为一个新变量,因为将它添加到 class 而不是在这段代码中会导致 error

def output_it(members, furthest):
  of=open("results.txt", "a")
  of.write('The number of whole marathons walked is:\n')
  for loop in range(len(members)):
    int(marathon=round(1, members[loop].distance/26.22))
    of=open("results.txt", "a")
    of.write(f'{members[loop].forename} {members[loop].surname} {marathon}')
    
#Meinne programme
members=read_data_to_AOT()
furthest=find_furthest_distance(members)
display_fursthest_distance_walked(furthest, members)
output_it(members, furthest)

这一行对我来说似乎无效。 marathon 不是 int() 的参数;据我所知,这段代码没有创建一个名为 marathon 的变量。 int() returns 一个 int,但您甚至没有对返回值做任何事情。你只是把它扔掉了:

int(marathon=round(1, members[loop].distance/26.22))

看来你的意思是:

marathon = int(round(1, members[loop].distance / 26.22))

此外,在您的代码中包含 magic numbers 是 anti-pattern。相反,我会在上面的某处定义数字,例如:

# A marathon is 42.195 kilometers, or 26 miles, 385 yards:
MILES_PER_MARATHON = 26.0 + (385 * 3 / 5280)

那么,您的代码对于不知情的人来说会更有意义 reader:

marathon = int(round(1, members[loop].distance / MILES_PER_MARATHON))