简体   繁体   中英

Python Multiplying Integers inside “print()”

So I have the code (Relevant code):

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)

What I want it to do is print the value of valin multiplied by 2, but have no idea how to do that! How ?

Convert the input string to an integer with int :

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

then proceed as before.

Your issue is that the result of input() will be a str , not an int , and multiplication has a different meaning for strings. Here is an example:

>>> 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

You need to do as larsmans suggested, and convert it to an int before the multiplication. Here is a version with some extra validation:

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)

Use Python String Formatting :

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

Edit: You might want to do some input validation to make sure that what you get from input is an integer, or can be parsed as an integer, and otherwise ask again.

Edit 2: If the comment from larsmans is correct, you need to parse the input to an int . Fixed above.

print(“如果落在偶数上,您将赢得%d”%valin * 2)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM