如何创建一个使用3个参数的函数,其中一个参数有点像(start、stop、step),但不包含列表



我只是想在一个函数中创建一个循环,该函数使用3个函数参数执行启动-停止步骤过程。因此,例如,如果用数字10、20、3调用函数,则程序将写入10、13、16、19

我还想把结果写到一个新制作的文本文件中。

这就是我目前所拥有的:

ranges = int(input("Enter a range to start: "))
step = int(input("Enter a step: "))
stop = int(input("Enter a stop: "))
def threeparameters(ranges,stop,step):
for i in range(ranges,stop, step):
with open("sequences.txt", "a") as f:
i = str(i)
f.write(ranges,stop,step)
f.close()
i = threeparameters(ranges,step,stop)

要解决这个问题,第一个问题是f.write((只能接受一个参数,因此这将不起作用。其次,您不需要使用with open((语法关闭文件。另一件需要注意的事情是,打开文件时使用的是追加模式("a"(。

目前,您正在列表的迭代中打开文件,但这应该是另一种方式。假设你想在新行上将数字序列放入一个新的txt文件中,请尝试以下操作:

def threeparameters(ranges, stop, step):
with open("sequences.txt", "w") as f:
for i in range(ranges, stop, step):
i = str(i)
f.write(i + "n")

通过这种方式,函数从打开文件开始(在写入模式下(,然后在三个参数给定的数字范围内迭代,然后将每个参数转换为字符串,并在每个参数后面用换行符"n"将其写入文件。值为range = 0stop = 10step = 2时,将保存以下txt文件:

0
2
4
6
8

首先,让我们分析您的代码。

ranges = int(input("Enter a range to start: "))
step = int(input("Enter a step: "))
stop = int(input("Enter a stop: "))
def threeparameters(ranges,stop,step):
for i in range(ranges,stop, step):
with open("sequences.txt", "a") as f:
i = str(i)
f.write(ranges,stop,step)
f.close()
i = threeparameters(ranges,step,stop)

我想在这里指出一些事情:

  1. 您没有将i用于for循环中的任何内容
  2. threeparameters()没有返回任何值,正在尝试写入整数(这会产生错误(,并向f.write传递了许多参数(另一个错误(,并且没有打印任何内容

所以,我们可以做的是:

  1. 不要将ranges, stop, step传递给f.write。我想您希望在文件中有一个10, 13, 16, 19结果(按照您的示例(,所以您可以这样做:
f.write(i+"n")  # the newline is just to be fancier
  1. 不需要f.close步骤(在with语句中,open()将在语句完成时关闭文件(。

  2. 如果需要,请在屏幕上打印i结果:

for i in range(ranges,stop, step):
with open("sequences.txt", "a") as f:
i = str(i)
f.write(i+"n")
print(i)
  1. 如果要存储某些内容,请在threeparameters函数的末尾添加一个return whatever_you_want。我没有对代码进行更改,因为我不知道你想要得到什么

最终代码如下所示:

ranges = int(input("Enter a range to start: "))
step = int(input("Enter a step: "))
stop = int(input("Enter a stop: "))
def threeparameters(ranges,stop,step):
for i in range(ranges,stop, step):
with open("sequences.txt", "a") as f:
i = str(i)
f.write(i+"n")
print(i)
# if you want to return something, put it here
# Since we didn't return something at `threeparameters`,
# we can just call the function without storing anything.
threeparameters(ranges, step, stop)

输入/输出演示:

Enter a range to start: 10
Enter a step: 20
Enter a stop: 3
10
13
16
19

您的sequences.txt文件将包含:

13
16
19

最新更新