【发布时间】:2016-02-02 17:30:20
【问题描述】:
我已经编写了这段代码并且它完全可以工作,但是当我添加最后两行时,它一直说:'Total' 没有定义。没有最后两行,代码可以完美运行,是什么原因造成的?
NumGiven=''
while not NumGiven.isnumeric():
NumGiven=(input('Please enter a 7 or 8 digit number:'))
while len(NumGiven)<7 or len(NumGiven)>8:
NumGiven=(input('Please enter a 7 or 8 digit number:'))
if len(NumGiven)==8:
my_list=[int(i) for i in NumGiven]
total=(sum([int(i) for i in NumGiven]))
ans = total / 10.0
if total % 10 == 0:
print("Your GTIN8 code is correct.")
else:
print("Your GTIN8 code is incorrect")
if len(NumGiven)==7:
my_list=[int(i) for i in NumGiven]
print(my_list)
【问题讨论】:
-
因为您使用的
NumGiven的长度不是 8。total只会被定义为if len(NumGiven)==8: -
那我该怎么办?我需要使用变量
NumGiven -
如果
NumGiven的长度为7,这取决于您希望total是什么。 -
通常,我们会在代码的开头为变量赋予一个初始值,以便始终对其进行定义,但我不完全确定您在这里尝试做什么。
-
我只是要求用户输入一个 7 位或 8 位数字,如果它是 8,那么它将所有 8 位数字相加并除以 10 ,如果答案有余数,则代码(他们给出的 8 位数字)是不正确的。但是如果用户输入 7 位数字,那么如果位置是奇数(1、3、5 和 7)然后乘以 3,如果是偶数则乘以1. 然后将新相乘的 7 位数字相加并从最接近的 10 倍数中减去,这将使用给定的 7 位数字的第 8 位数字。
标签: list python-3.x integer undefined