【问题标题】:I need to multiply every other number by 3 but dont know what i'm doing wrong我需要将每个其他数字乘以 3,但不知道我做错了什么
【发布时间】:2016-02-25 18:57:24
【问题描述】:
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

【问题讨论】:

  • 请在您的问题中添加更多详细信息。你在纠结什么?
  • 您能否阅读编辑并格式化您的问题?
  • barcode1 的输入是什么?
  • 输入是 1,我在某处读到它是 111,因为它是一个字符串而不是整数,但我不知道如何更改它
  • @LPK 抱歉忘记给你加标签

标签: python math numbers


【解决方案1】:

你可以这样做:

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。这样你也可以输入一个字符串,但你的脚本不会崩溃。

【讨论】:

    【解决方案2】:

    这里令人困惑的现象是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)
    

    【讨论】:

      【解决方案3】:

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

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

      【讨论】:

      • 成功了,现在是 3 而不是 111,谢谢
      猜你喜欢
      • 2014-02-16
      • 1970-01-01
      • 1970-01-01
      • 2021-01-05
      • 2021-04-13
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多