2016-10-21 30 views
0

Python初學者在這裏。我正在編寫一個使用無限循環的程序,並允許用戶輸入關鍵術語來訪問不同的「工具」或「模塊」。將輸入()識別爲str,float或int並相應地執行

在這些「模塊」中的一箇中,用戶可以輸入一個值並將其轉換爲二進制。我想:

  1. 允許程序識別,如果值是該值以二進制
  2. 轉換允許程序識別,如果輸入的值是一個int或 浮動,然後運行代碼str和str表示'返回',其中當前循環將退出。

據我所知,這個問題發生輸入()轉換無論是自動輸入到STR(由於:http://anh.cs.luc.edu/python/hands-on/3.1/handsonHtml/io.html「首先,它打印你給作爲參數字符串」)。

如何讓下面的代碼識別輸入是str,float還是int,然後執行相關的if語句?目前,我的代碼的這部分可以接受'返回'退出循環,但會將任何整數或浮點值作爲str,使程序提示用戶再次輸入十進制值。

#decimal to binary 
    while search == "d2b": 
     dec2bin = input("\nDecimal Value: ") 
     if type(dec2bin) == int: 
      print("Binary Value: " + "{0:b}".format(dec2bin)) 
     elif type (dec2bin) == str: 
      if dec2bin == "back": 
       search = 0 
     elif type (dec2bin) == float: 
       #code for float to binary goes here 

編輯:不一樣,這個線程(Python: Analyzing input to see if its an integer, float, or string),作爲一個列表用於有超過輸入() E2:似乎無法使用重複的建議作爲解決問題。然而,弗朗西斯科在此主題中的評論有解決方案

+0

標記爲重複的問題並不是真的。那就是如何在列表中找到對象的類型 - 而不是可以將字符串轉換成的類型。 – dawg

回答

1

使用異常!當它們不能轉換傳遞的值時,intfloat函數會拋出ValueError異常。

while search == "d2b": 
    dec2bin = input("\nDecimal Value: ") 
    try: 
     dec2bin = int(dec2bin) 
    except ValueError: 
     pass 
    else: 
     print("Binary Value: " + "{0:b}".format(dec2bin)) 
     continue 

    try: 
     dec2bin = float(dec2bin) 
    except ValueError: 
     pass 
    else: 
     #code for float to binary goes here 
     continue 

    if dec2bin == "back": 
     search = 0 

在您嘗試轉換的順序很重要,因爲傳遞給int每個值是有效的與float,並傳遞給float每個值是一個有效的傳遞到str

+0

這似乎在我的代碼中正常工作,謝謝。如果你不介意,可以使用類似的方式將浮動格式化爲二進制格式,以便如何輸入?現在我正在做一些嘗試,瞭解我對格式化和獲取錯誤的知識。 –

+0

@CharlieWebb取決於你將'float'轉換爲二進制的意思,也許[this](https://stackoverflow.com/questions/16444726/binary-representation-of-float-in-python-bits-not-十六進制)回答你的問題。 –

+0

所以目前 –

0

您可以使用str.isalpha()str.isdigit()來實現這一點。因此,您的代碼如下:

while search == "d2b": 
    dec2bin = input("\nDecimal Value: ") 
    if dec2bin.lstrip("-").isdigit(): 
     print("Binary Value: " + "{0:b}".format(int(dec2bin))) # OR, simply bin(int(dec2bin)) 
    elif dec2bin.isalpha(): # OR, isalnum() based on the requirement 
     if dec2bin == "back": 
      search = 0 
    else: 
     try: 
      _ = float(dec2bin) 
     except: 
      pass 
     else: 
      #code for float to binary goes here 

在這裏,我使用str.lstrip()從字符串的開始刪除-作爲.isdigit()無法檢查負數的字符串。

請參閱Python 3: String Methods以獲取與str對象一起使用的完整方法列表。

+1

你可以得到一個負數 –

+0

@PadraicCunningham:更新了答案。感謝您的注意。 –

+0

我沒票了,所以不能+1,你也許想看看什麼是十進制;) –

相關問題