我正在编写一段代码,需要将数字乘以不同的值,所有用于输入和验证7位数字的代码都有效,但乘法不起作用。这是我的代码。
while True:
try:
num = int(input("enter a 7 digit number: "))
check = len(str(num))
if check == 7:
print("This code is valid")
break
else:
num = int(input("enter a number that is only 7 digits: "))
except ValueError:
print("you must enter an integer")
num = int(num)
def multiplication():
num[0]*3
num[1]*1
num[2]*3
num[3]*1
num[4]*3
num[5]*1
num[6]*3
return total
multiplication()
当我运行它时,我收到以下错误:
Traceback (most recent call last): File "\\hpdl3802\stuhomefolders$\12waj066\Year 10\Computing\A453\Code\Test v2.py", line 29, in <module> multiplication() File "\\hpdl3802\stuhomefolders$\12waj066\Year 10\Computing\A453\Code\Test v2.py", line 20, in multiplication num[0]*3 TypeError: 'int' object is not subscriptable
欢迎任何反馈
答案 0 :(得分:2)
当然,您的代码可能会以多种方式编写,并进行优化(请查看@Kasravand回答,这很棒),但只需付出最少的努力,这就是我得到的:
while True:
try:
num = input("enter a 7 digit number: ")
check = len(num)
int(num) # will trigger ValueError if not a number
if check == 7:
print("This code is valid")
break
else:
print("bad length, try again")
except ValueError:
print("you must enter an integer")
def multiplication(num):
total = int(num[0])*3
total += int(num[1])*1
total += int(num[2])*3
total += int(num[3])*1
total += int(num[4])*3
total += int(num[5])*1
total += int(num[6])*3
return total
print("Answer: ", multiplication(num))
答案 1 :(得分:1)
当您将输入数字转换为整数时,您无法在该对象上使用索引,因为整数不支持索引。如果要将数字乘以特定数字,最好在转换为整数之前执行此操作。
首先,请更换以下部分:
num = int(input("enter a number that is only 7 digits: "))
使用:
num = input("enter a number that is only 7 digits: ")
您可以使用repeat
模块中的chain
和itertools
函数来创建重复的数字,然后使用列表推导来计算乘法:
>>> from itertools import repeat, chain
>>> N = 7
>>> li = list(chain.from_iterable(repeat([3, 1], N/2 + 1)))
>>> num = '1290286'
>>> [i * j for i, j in zip(map(int, num), li)]
[3, 2, 27, 0, 6, 8, 18]
答案 2 :(得分:1)
如果您必须使用整数而不是输入的列表,则可以执行以下操作之一:
您可以使用整数除法和模数的组合来访问各个数字,例如:
first_digit = num // 1000000 * 3
second_digit = num // 100000 % 10 * 1
# and so on
或者您可以将输入作为字符串获取并访问并转换各个数字:
# [...]
num = input("enter a number that is only 7 digits: ")
# [...]
first_digit = int(num[0]) * 3
second_digit = int(num[1]) * 3
答案 3 :(得分:0)
此代码将起作用:
while True:
try:
num = int(input("enter a 7 digit number: "))
except ValueError:
print("you must enter an integer")
else:
if len(str(num)) != 7:
print("enter a number that is only 7 digits")
else:
break
num = str(num)
def multiplication():
total = 0
for i,m in enumerate([3,1,3,1,3,1,3]):
total += int(num[i])*m # transform the index of text into a integer
return total
print(multiplication())
答案 4 :(得分:0)
这应该有帮助
num = ''
check = 0
while True:
try:
num = raw_input("enter a 7 digit number: ")
check = len(num)
if check == 7:
print("This code is valid")
break
else:
print "enter a number that is only 7 digits"
except ValueError:
print("you must enter an integer")
def multiplication():
total = 0
for i in range(check):
if i % 2 == 0:
total += int(num[i]) * 3
else:
total += int(num[i]) * 1
print total
multiplication()