我需要把其他数字乘以3,但不知道我做错了什么

2024-06-25 06:46:38 发布

您现在位置:Python中文网/ 问答频道 /正文

print("Welcome")
barcode1 = input("Please enter your first digit")
barcode2 = input("Please enter your second digit")
barcode3 = input("Please enter your third digit")
barcode4 = input("Please enter your fourth digit")
barcode5 = input("Please enter your fifth digit")
barcode6 = input("Please enter your sixth digit")
barcode7 = input("Please enter your seventh digit")
barcode1 = barcode1*3
print(barcode1)

这个数不是乘以3,而是111


Tags: inputyourfirstprintentersecondpleasedigit
3条回答

这里令人困惑的现象是python支持字符串乘法和整数乘法!对于没有经验的人来说,这看起来很混乱,但实际上这是一个很好的特性。可以执行以下操作:

>>> string = 'hi!'
>>> multiplied_string = string * 4
>>> multiplied_string
"hi!hi!hi!hi!"

如您所见,将字符串相乘会将其内容重复n次,其中n是它相乘的数字。你知道吗

在本例中,您希望将一个数值相乘,但是input函数返回的是一个字符串值而不是一个数值。这意味着当您对它进行乘法时,python将执行字符串乘法,而不是执行数字乘法。你知道吗

只需使用int方法将input的结果转换为整数。或者,您甚至可以编写一个函数来接受用户的数字输入。你知道吗

def input_int(msg):
    '''
    Repeatedly asks the user for a valid integer input until a validly
    formatted input is provided.
    '''
    while True:
        try:
            return int(input(msg))
        except:
            print('Please enter a numeric input.')

print("Welcome")
barcode1 = input_int("Please enter your first digit")
barcode2 = input_int("Please enter your second digit")
"........"
print(barcode1 * 3)

你可以这样做:

codes = []
i = 0
while True:
    try:
        codes.append(int(input("Please input your Barcode {}: ".format(i))) * 3)
        if i == 6: break
        i += 1
    except ValueError:
        print("Something went wrong!")

print(codes)

在它周围添加一个try-catch语句,并尝试将您的输入转换为int。你知道吗

barcode1从字符串更改为整数,例如:

b1 = int(barcode1)*3
print(b1)

相关问题 更多 >