为了账号安全,请及时绑定邮箱和手机立即绑定

无法在函数内将 str 更改为 int

无法在函数内将 str 更改为 int

噜噜哒 2021-09-02 15:40:52
def Validation(digits):    while not digits.isdigit():        digits = input("Please select an interger for this part")    digits = int(digits)length_1 = input("What is the length of one of the sides?")    Validation(length_1)length_2 = input("What is the length of another side?")    Validation(length_2)answer = length_1 * length_2 / 2 我正在尝试使用验证用户输入的函数。最后它应该把它变成一个整数,这样它们就可以相乘了。但是,我收到错误:answer = length_1 * length_2 / 2 TypeError: can't乘以非int类型的'str'序列。我可以通过添加 int(length_1) 和 int(length_2) 来修复它,但是函数的重点是不要这样做
查看完整描述

3 回答

?
青春有我

TA贡献1784条经验 获得超8个赞

您必须从函数返回值并替换您将要使用的变量。


 def Validation(digits):

        while not digits.isdigit():

            digits = input("Please select an interger for this part")

        return int(digits)


    length_1 = input("What is the length of one of the sides?")

    length_1 = Validation(length_1)

    length_2 = input("What is the length of another side?")

    length_2 = Validation(length_2)

    answer = length_1 * length_2 / 2 

    print(answer)


查看完整回答
反对 回复 2021-09-02
?
交互式爱情

TA贡献1712条经验 获得超3个赞

Python 按值传递。在digits传递给你的函数是重新分配的最后一行。这不会改变原始值,它只会创建一个新变量。而不是你在做什么,return int(digits)


查看完整回答
反对 回复 2021-09-02
?
大话西游666

TA贡献1817条经验 获得超14个赞

digits = int(digits)无法更改传递给Validation. 函数中的所有重新分配都改变了函数参数所指向的内容。这在函数之外没有任何影响。


只需返回解析后的数字:


def Validation(digits):

    while not digits.isdigit():

        digits = input("Please select an interger for this part")

    return int(digits)


length_1 = input("What is the length of one of the sides?")

parsed_length_1 = Validation(length_1)


查看完整回答
反对 回复 2021-09-02
  • 3 回答
  • 0 关注
  • 175 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信