2017-08-26 56 views
0

我試圖做一個階乘計算器。如何確定輸入的類型?

輸入和預期輸出::如果用戶輸入是正整數,我希望程序給出結果。如果用戶輸入不是正整數(負整數,浮點數或字符串),我希望程序再次請求輸入。另外,我希望程序在用戶輸入爲0時結束。

問題:由於輸入總是被視爲字符串數據,因此我根據輸入類型進行編碼。

如果有人能夠給出解決這個問題的答案,這對我自己學習會有很大的幫助。

+0

這已在別處解答https://stackoverflow.com/a/43564344/2308683 .. https://stackoverflow.com/a/34797270/2308683 –

回答

1

如果你想確保它是一個正整數,如果你想繼續要求輸入在你的問題中指定,你需要一些更多的控制結構:

from math import factorial 

def get_input(): 
    while True: 
     try: 
      inp = int(input("Enter a positive integer> ")) 
      if inp < 0: 
       raise ValueError("not a positive integer") 
     except ValueError as ve: 
      print(ve) 
      continue 
     break 

    return inp 

print(factorial(get_input())) 

該作品以剛試圖將輸入轉換爲整數,如果失敗則重試。 continue聲明用於跳過breaktry/except結構捕獲錯誤(如果它不是整數),或者錯誤明確地在小於0時引發錯誤。它還使用exceptas功能來更好地指示錯誤。它封裝在一個函數中,使事情變得更加簡單 - 我發現factorial(get_input())非常具有表現力,並且具有更多的可重用性。

這目前當用戶輸入0,作爲0factorial一個完全有效的投入並沒有結束,儘管它應該是很容易適應這種與if聲明。

該程序可能會被這樣使用:

Enter a positive integer> abc 
invalid literal for int() with base 10: 'abc' 
Enter a positive integer> 0.2 
invalid literal for int() with base 10: '0.2' 
Enter a positive integer> -5 
not a positive integer 
Enter a positive integer> 6 
720 

順便提一下,根據EAFP此代碼的工作 - 它只是試圖轉換爲整數,並處理故障。這比Python第一次試圖確定它是否是一個整數(LBYL)更爲習慣。

如果您使用Python 2,則需要將input更改爲raw_input

+0

謝謝!正是我在找的東西:) – Gina

0

試着把它看作是一個算法問題,而不是Python問題,你可能會找到一個解決方案,因爲一般來說,每種語言都有它的功能,而且它們幾乎都只是用不同的名字。 在python中,它們是函數調用isnumeric(),如果每個單個字符都是數字,則返回true,否則返回false。

str.isnumeric() 

我們它就像如果

if str.isnumeric()==true // so it's numeric 
    // what to do!!!!! 

的最佳選擇是使用一段時間,如果

while true 
    //read data as string 
    if str.isnumeric()==true 
     break; // this to break the while loop 

希望這可以幫助你

+0

你的代碼並不是真正的Python .. Python註釋使用'#','true'布爾的Python文字是'True',你需要':'在縮進之前,而且比檢查'if condition == true',你可以使用'if condition'。 –

+0

是的我知道,我不是一個Python程序員,我說這就像一個算法問題,每種語言都有它自己的功能,對於這類問題, isnumeric()它是一個python函數。他可以使用它,而如果。 python沒有do..while條件,所以他需要像這樣使用它... if(cindition){break:} – shadow

+0

在這種情況下,作爲一種算法,這屬於LBYL。在Python,AFAIK中,通常認爲對這類問題使用[EAFP](https://docs.python.org/2/glossary.html#term-eafp)方法會更好,所以從某種意義上說它是'除了需要Python語法之外,還有一個Python問題,就是它的算法本質。 –

0

Check if input is positive integer檢查的語句條件連同上面的user @ cricket_007提供的鏈接一起鏈接。把這兩個信息結合起來應該能讓你朝着正確的方向前進。

相關問題