簡體   English   中英

Python 2.7.2 if / or意外行為

[英]Python 2.7.2 if/or unexpected behaviour

我目前正在學習Python,但遇到了一個問題。 遵守以下代碼:

while 1:
    print "How many lines do you want to add to this file?"

    number_of_lines = raw_input(">").strip()

    if not(number_of_lines.isdigit()) or number_of_lines > 10:
        print "Please try a number between 1 and 10 inclusive."
        continue

該代碼要求用戶輸入數字,並檢查其有效性。 但是,由於某些原因,即使用戶輸入的有效數字小於10,代碼也始終顯示錯誤。

我可能在某個地方犯了一個小錯誤,但我無法弄清楚...成為python新手!

希望能對您有所幫助! 提前致謝。

raw_input返回時,您的number_of_lines變量是一個字符串 您需要先將其轉換為整數,然后再與10進行比較:

not(number_of_lines.isdigit()) or int(number_of_lines) > 10

我會嘗試首先將字符串轉換為整數,如果它們放入其他內容,則會捕獲錯誤。 這也讓您放棄isdigit呼叫。 像這樣:

while 1:
    print "How many lines do you want to add to this file?"

    try:
        number_of_lines = int(raw_input(">").strip())
    except ValueError:
        print "Please input a valid number."
        continue

    if number_of_lines > 10:
        print "Please try a number between 1 and 10 inclusive."
        continue

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM