【问题标题】:Python method positional args troubleshootingPython 方法位置 args 故障排除
【发布时间】:2021-11-01 03:03:18
【问题描述】:

所以我正在尝试制作一个将遍历字符串并替换某些字符的脚本。这个想法相当简单,sudo 代码看起来有点像这样。

Input1 = ''
Input2 = ''
Input3 = ''
rawPw = Input1 + Input2 + Input 3
Remove spaces if any exist
Creates a new empty str called finalPw

Scan the rawPw string one character at a time.  Each character goes to a Random bool and if True it goes to get converted.  If false it appends finalPw

In it goes to conversion it checks against a list of specified characters and if it matches it goes to a specific converter method.  Otherwise it will just swap upper/lower case and append finalPw

The specific converter method will use a predefined list of characters that it can be replaced by, and will use random.choice() to pick from that list to replace the character and append finalPw.

这是我到目前为止的代码,注意大写/小写交换还不是其中的一部分,我正在构建和测试代码零碎,因为我的最后一个原型有 350 行长并且完全失败。所以在这里从头开始。

import random


print("Enter 3 words or series of numbers or both, each entry must be at least 5 characters in length")


def main():
    input1 = 'Jim'
    input2 = 'Samantha'
    input3 = 'Ethan'
    rawPw = (input1 + input2 + input3)
    refinedPw = rawPw.replace(' ', '')
    print(refinedPw)
    finalPw = ''
    convertTrain(refinedPw)


def switch():
    switchVal = random.choice(True, False)
    return switchVal


def convertTrain():
    temp = main.refinedPw
    onOff = False
    for i in temp:
        switch(i)
        if i == True:
            if i == 'i':
                the_iExc(i)
        else:
            main.finalPw.append(i)


def the_iExc():
    rep_iExc = ['i', '!']
    repVal = random.choice(rep_iExc)
    for i in len(main.refinedwPw):
        slice(i)
        if i == 'i':
            i.replace(repVal)
            return i

main()

我收到的错误是: 第 15 行,主要 转换火车(精制Pw) TypeError: convertTrain() 接受 0 个位置参数,但给出了 1 个

我已经尝试稍微改变一下,看看我是否无法修复位置参数,以至于我已经将它从所有类中剥离出来,并且在我让它工作之前变得无类。对于我的生活,我似乎无法让它使用适当数量的参数。

【问题讨论】:

  • refinedPw 不是函数main 的属性;它是您试图传递给未定义任何参数的函数的局部变量。我不确定您将什么语言的习语或程序投射到 Python 上,但我建议稍微使用一下 tutorial
  • 这里也没有必要使用rawPw.replace,因为根据定义你已经知道它不包含空格。 input* 三个变量中的每一个都是无空格的,+ 不会引入任何空格。
  • chepner,这三个变量是用于测试的占位符,最终版本将是用户输入

标签: python function methods arguments


【解决方案1】:

这一行将 convertTrain 定义为一个不带参数的函数:

def convertTrain():

但是在 main() 内部你用一个参数调用它:

convertTrain(refinedPw)

要么更改函数定义以接受参数,要么更改调用以不传递参数。

【讨论】:

  • 它应该通过函数传递refinedPw,以便可以通过convertTrain() 更改refinedPw。那么我只是将提炼Pw 放入两者中吗?还是我需要做其他事情,因为调用和施法似乎一次又一次地把我搞砸了。 Obvioulsy 仍在学习编码。
【解决方案2】:

您正在尝试在这里调用带有参数的函数:

convertTrain(refinedPw)

...但是函数定义中没有参数

def convertTrain()

要解决此问题,请为 convertTrain 函数添加一个新参数,如下所示:

def convertTrain(train) # Name of argument can be changed if needed

在此处阅读有关函数声明的更多信息:click this

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2022-12-15
    • 1970-01-01
    • 2020-07-16
    • 2021-05-07
    • 1970-01-01
    • 2018-10-15
    • 1970-01-01
    相关资源
    最近更新 更多