所以我的代碼(相關代碼):Python的倍增整數裏面「打印()」
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)
我希望它做的是打印華菱乘以2的值,但不知道如何要做到這一點!怎麼樣 ?
所以我的代碼(相關代碼):Python的倍增整數裏面「打印()」
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)
我希望它做的是打印華菱乘以2的值,但不知道如何要做到這一點!怎麼樣 ?
轉換輸入字符串到整數與int
:
valin = int(input("How much would you like to bet?: "))
然後如前繼續進行。
打印( 「如果它的土地上偶數,你就贏了%d」 %華菱* 2)
問題在於'valin'是其他人指出的'str'而不是'int'。 '''優先於'*'。你需要在'()'裏放置'valin * 2'。 – Avaris 2012-03-08 17:21:15
print("If it lands on an even number, you win %d" % (int(valin) * 2))
編輯:你可能想要做一些輸入驗證以確保從input
得到的是一個整數,或者可以解析爲一個整數,否則再次詢問。
編輯2:如果從larsmans的評論是正確的,你需要輸入解析到int
。固定在上面。
OP似乎在使用Python 3,其中'input'總是返回一個字符串(就像Python 2中的'raw_input')。 – 2012-03-08 17:09:00
我建議使用python-3首選的字符串格式化方法:'「如果它着陸在偶數上,則會贏{}」.format(int(valid)* 2)'。儘管如此,還是會出現同樣的情況。 – aquavitae 2012-03-09 06:17:17
你的問題是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)
你試過了什麼?當你嘗試時發生了什麼?你想要發生什麼?你爲什麼認爲發生了? – 2012-03-08 19:45:37