2016-04-17 36 views
0

我需要的是,我要求用戶輸入像1/2如何1/2轉換爲2蟒蛇3.5

例如:i=input("Input the half; if one-sixteenth enter 1/16")

我需要的是採取的16條中1/16並用於計算。

數學

,我們可以很容易地使用1 /(1/16),但在python我得到一個數據類型的錯誤嘗試ASIGN和使用小數值是這樣做的計算時,

任何幫助高度評價

+1

你得到了什麼錯誤 – Ashish

+4

顯示引發錯誤和實際錯誤的實際代碼。([MCVE](http://stackoverflow.com/help/mcve))我假設python並不多像'str'一樣劃分? –

+3

um ...'「1/2」'雖然可以轉換爲['fractions.Fraction'],但不能轉換爲'int'(https://docs.python.org/2/library /fractions.html) –

回答

7

我不完全明白你的問題,但是Python不理解分數 - 見https://docs.python.org/3/library/fractions.html

一個好處的,這是你通過捕捉ValueError例外檢查無效的輸入。

from fractions import Fraction 


f = None 

while(f is None): 
    n = input("Enter a fraction: ") 

    try: 
     f = Fraction(n) 
    except ValueError: 
     print(n, "isn't a valid fraction") 

print(f) 
print(float(f)) 
print(f.denominator) 

# input 1/6 gives: 
# 1/6 
# 0.166666666667 
# 6 
0

您可以計算x = 1/16;然後計算y = 1/x。希望它可以幫助

1
i=input("Input the half; if one-sixteenth enter 1/16") 
k = i.split("/") 

K [1]將分母

int(k[1]) 

將它作爲一個數

0

你可以使用fractions模塊。但我如果正確理解你的問題,你的用戶在這個分數形式中輸入1/16,你想要16

x = input("Fraction: ") # Fraction: 1/16 or 1/16 or 1/ 16, whatever 
n = int(x.split("/")[-1].strip()) # 16 (int) 

如果它現在是你想要的,然後請評論。