Python在“print()”中乘以整数

时间:2012-03-08 16:54:49

标签: python python-3.x multiplication

所以我有代码(相关代码):

print("You have chosen to bet on the even numbers")
valin = input("How much would you like to bet?: ")
print("If it lands on an even number, you win", valin*2)

我想要它做的是打印valin的值乘以2,但不知道如何做到这一点!怎么样?

4 个答案:

答案 0 :(得分:4)

将输入字符串转换为int的整数:

valin = int(input("How much would you like to bet?: "))

然后像以前一样继续。

答案 1 :(得分:3)

您的问题是,input()的结果将是str,而不是int,并且乘法对字符串具有不同的含义。这是一个例子:

>>> valin = input("How much would you like to bet?: ")
How much would you like to bet?: 20
>>> type(valin)      # valin is a string!
<type 'str'>
>>> valin * 2        # multiplication will concatenate the string to itself
'2020'
>>> int(valin) * 2   # first convert it to an int, then multiply
40

你需要像larsmans建议的那样做,并在乘法之前将其转换为int。这是一个带有一些额外验证的版本:

print("You have chosen to bet on the even numbers")
while True:
    try:
        valin = int(input("How much would you like to bet?: "))
        break
    except ValueError:
        print("Invalid input, please enter an integer")
print("If it lands on an even number, you win", valin*2)

答案 2 :(得分:2)

使用Python String Formatting

print("If it lands on an even number, you win %d" % (int(valin) * 2))

编辑:您可能需要进行一些输入验证,以确保从input获得的是一个整数,或者可以解析为整数,否则再次询问。

编辑2:如果来自larsmans的评论正确,则需要将输入解析为int。修正如上。

答案 3 :(得分:0)

print(“如果它落在偶数上,你就赢了%d”%valin * 2)