2014-11-16 20 views
-1
if use == '1': 
    n1 = input("Enter first number:    ") 
    if n1.isdigit() or n1 == float: 
     print("" + n1) 
     m = input("Enter method (+ -/*):   ") 
    else: 
     print("That is not a valid number!") 

此代碼歸類爲一個有效輸入允許整數穿過並且如果輸入不是一個數字輸出消息,但它並不通過讓浮點數。我能做些什麼來解決這個問題?爲什麼浮點數沒有被在該Python代碼

回答

0

你可以嘗試這樣,

if n1.replace('.','').replace('-','').isdigit(): 

def isfloat(value): 
    try: 
    float(value) 
    return True 
    except ValueError: 
    return False 
+1

感謝它現在的作品,真的很欣賞快速反應 – matt54

+0

我將如何改變做它的第一種方式,以便它也可以尋找負浮動? – matt54

+0

想想爲什麼給定的解決方案適用於小數,然後您可以將其應用於負數。 – SethMMorton

0

你不能n1 == float檢查對象的類型,你可以使用isinstance()

isinstance(n1,float) 

也作爲input結果在Python 3是一個string,你需要n1轉換成合適的格式進行檢查,像float(n1)和檢查,但在這種情況下,我建議改變你的if到:

try: 
    if if n1.isdigit() or float(n1) : 
     print("" + n1) 
     m = input("Enter method (+ -/*):   ") 
    except ValueErorr: 
     print("That is not a valid number!") 
+0

還是說,這是一個無效的號碼 – matt54

+0

@Kasra'input'只返回'string' –

+0

@ matt54我編輯的答案! – Kasramvd

相關問題