4

我是新來的整個編碼的東西......所以這裏。 只是試圖寫一個簡單的數字猜測遊戲,但也做輸入驗證。所以只有整數才被接受爲輸入。我已經想出瞭如何去除字母字符,所以我可以將數字轉換爲整數。當我輸入一個浮點數時,我遇到了麻煩。我無法得到它將浮點數轉換爲整數。任何幫助表示讚賞。正如我所說的,我正在談論這個編碼事物的第3天,所以試着理解我的小知識。提前致謝。如何將浮點字符串轉換爲python中的整數3

這是我主程序中的功能。

def validateInput(): 
    while True: 
     global userGuess 
     userGuess = input("Please enter a number from 1 to 100. ") 
     if userGuess.isalpha() == False: 
      userGuess = int(userGuess) 
      print(type(userGuess), "at 'isalpha() == False'") 
      break 
     elif userGuess.isalpha() == True: 
      print("Please enter whole numbers only, no words.") 
      print(type(userGuess), "at 'isalpha() == True'") 
    return userGuess 

這是我得到的錯誤,如果我使用4.3(或任何浮點數)作爲輸入。

Traceback (most recent call last): 
File "C:\\*******.py\line 58, in <module> 
validateInput() 
File "C:\\*******.py\line 28, in validateInput 
userGuess = int(userGuess) 
ValueError: invalid literal for int() with base 10: '4.3' 
+0

您可以嘗試使用try-except來鏈接轉換。如果你的int()轉換產生一個ValueError異常,你可以嘗試使用float()轉換輸入,然後將你的浮點值舍入或截斷爲整數。 – nullop 2014-11-20 20:24:16

+0

幾個方面的說明:你幾乎從不想檢查'如果垃圾郵件==假:',只是'如果不是垃圾郵件:'。在'elif'中,你不需要重新檢查'if'測試的反面 - 你已經知道'isalpha'是真的,因爲你知道它不是假的。所以,只需使用'else:'。如果你從這個函數返回'userGuess',你幾乎可以肯定不需要它是'global'。最後,你不需要爲了「返回」而「休息」;你可以在'if'塊中直接返回'userGuess'。 – abarnert 2014-11-20 20:27:39

回答

4

實際上int()函數需要一個整數字符串浮子,但不是一個浮子串。如果浮動字符串給你需要將其轉換爲float第一再到int爲:

int(float(userGuess)) 
0

首先,你爲什麼要浮動字符串轉換爲整數?您是否想將4.7視爲用戶猜測的含義4?或者5?或者一個合法但自動無效的猜測?或者實際上值4.7(在這種情況下,你根本不需要整數)?要麼…?


其次,你接近這種方式是錯誤的。 userGuess.isalpha()只告訴你猜測完全是由字母組成的。這意味着你仍然會將"Hello!"視爲一個數字,因爲它至少有一個非字母。

如果你想知道一個字符串是否是一個有效的整數,只需調用它int,並使用try/except處理的情況下是不是:

def validateInput(): 
    while True: 
     global userGuess 
     userGuess = input("Please enter a number from 1 to 100. ") 
     try: 
      userGuess = int(userGuess) 
      print(type(userGuess), "after int succeeeded") 
      break 
     except ValueError: 
      print("Please enter whole numbers only, no words.") 
      print(type(userGuess), "after int failed") 
    return userGuess 

如果你想處理與其他類型故障不同的實際字詞,例如,因此您可以打印更具體的錯誤信息,然後您可以在except子句中檢查isalpha

如果要處理檢查它是否爲浮點數,以便發出不同的錯誤,請執行同樣的操作-以調用float(userGuess)-位於except子句的內部。或者,如果要截斷浮動,請將int(userGuess)更改爲int(float(userGuess))

即使在try零件中也可能需要其他檢查。例如,如果他們輸入-23178會怎麼樣?這些都是整數,但他們不是1和100

顯然之間的數字,你需要更多的驗證,更多的代碼需要,因爲每個測試是另一行代碼。因此,您可能需要考慮將驗證移出循環輸入的單獨函數,以使其更具可讀性。

0

請勿使用isalpha來篩選輸出。 EAFP - 將其轉換並處理該異常。 ValueError正是你想要的,因爲你可以處理它並告訴用戶糾正他們的輸入。或者出於某種奇怪的原因,你想默默地將他們的輸入從「4.3」修改爲「4」。

def validateInput(): 
    while True: 
     global userGuess 
     userGuess = input("Please enter a number from 1 to 100. ") 
     try: 
      int(userGuess) 
      return userGuess # you shouldn't really keep this string... 
     except ValueError as e: 
      print("Please enter whole numbers only, no words.") 
相關問題