2013-09-21 83 views
2

我正在嘗試編寫一個程序來執行簡單的算術運算。 我希望程序提示用戶輸入兩個數字,然後計算5個 結果:Python 3:基本算術運算

  • 總和
  • 產物
  • 商根據兩個整數
  • 浮點除法。

現在,我記得在Python的2,存在的raw_input了絃樂和輸入對於一般的數字。 然而,我剛學的Python 3,並輸入默認的字符串,以及數字我必須指定祝數的類型有:即INT(輸入())或浮點數(輸入()) 。

因此,例如,讓我們假設我想有正是這個輸出(使用輸入4和2.5):

What is the first number? 4 
What is the second number? 2.5 
The sum is 6.5 
The difference is 1.5 
The product is 8.0 
The integer quotient is 2 
The floating-point quotient is 1.6 

我將在鍵入此代碼的Python 2

x=input ("What is the first number? ") 
y=input ("What is the second number? ") 

print "The sum is", x+y 
print "The difference is", x-y 
print "The product is", x*y 
print "The integer quotient is", int(x)/int(y) 
print "The floating-point quotient is", float(x)/float(y) 

但是,我不能讓它在的Python 3完成。這是我使用的(錯誤的)代碼:

x = int(input("What is the first number? ")) 
y = int(input("What is the second number? ")) 

print("The sum is: ", x+y) 
print("The difference is: ", x-y) 
print("The product is: ", x*y) 
print("The integer quotient is: ", x/y) 
print("The floating-point quotient is: ", x/y) 

很顯然,我得到一個錯誤消息,因爲我的第二個輸入(Y)等於4.5,這是定義一個浮動,而不是一個INT我的意見。我沒有把浮點數(浮點數)/浮點數(y)用於浮點商,因爲這也是矛盾的(因此是一個錯誤)。

我當然可以把漂浮的不是int這樣的:

x = float(input("What is the first number? ")) 
y = float(input("What is the second number? ")) 

但在這種情況下,我將獲得10.0我的產品(不是10),和我的整數商是一個浮動(1.6代替2)

我真的感到很沮喪的是在Python 3我不能要求輸入一個普通型號(而不必指定這是否是浮動或INT)。因此,我堅持這樣簡單的程序,並會非常感謝任何解決方案/解釋。

+1

'input()'不適用於「一般數字」,它適用於任何在Python解釋器中評估時返回對象的東西。在'input()'提示符中插入'1 if True else 2'將返回整數'1'。 – millimoose

+2

這也是一個可怕的不安全的想法,而不是你通常想要的,這就是他們改變它的原因。 – user2357112

+2

基本上,變化是你應該知道你期望的輸入,或者你應該檢查它,並確定自己該怎麼做。你仍然可以'自己'從'input()'得到的字符串'eval()',並採取適當的預防措施來防止它搞笑。更好的是,使用['ast.literal_eval()'](http://docs.python.org/3.3/library/ast.html#ast.literal_eval) - 這應該儘可能接近你所需要的,同時仍然安全。 – millimoose

回答

3

您可以嘗試解析輸入爲int,如果不工作,把它作爲一個float

def float_or_int(x): 
    try: 
     return int(x) 
    except ValueError: 
     return float(x) 

x = float_or_int(input("What's x?")) 
y = float_or_int(input("What's y?")) 

爲了讓地板師在Python 3,你必須明確地要求它與//操作:

print("The integer quotient is:", x//y) 

注意,這個「整數商」的運作並沒有真正用於浮點輸入感。

+0

謝謝你的幫助! 當然,有辦法解決這個問題。我只是認爲這樣一個簡單的程序不需要更多的代碼。 –