簡體   English   中英

錯誤地打破了Python的while循環?

[英]Incorrectly breaking out of a python while loop?

我正在嘗試構建一個Twitter篩選器應用程序,該應用程序可以從您選擇的關鍵字中搜索您關注的人/ RT的個人時間軸。 (這不是問題,這是背景...我還沒有做到這一點,我現在只是在玩API!)

我剛剛開始學習Python,以前是Java程序員,我想知道如何檢查用戶輸入是否有效...輸入!

我有一個編號菜單(當前只有2個菜單項),我希望用戶鍵入1或2,如果不輸入,則它會引發錯誤消息並循環回到輸入。 我目前收到以下錯誤消息:

Traceback (most recent call last):
  File "Filtwer.py", line 31, in <module>
    if "1" in menuselect:
TypeError: argument of type 'int' is not iterable

第31行是下面代碼塊中if語句的開始。 我不確定我是否想念什么? 例如,是否沒有正確打破while循環? 任何幫助將非常感激!

謝謝 :)

import twitter
api = twitter.Api(consumer_key='<redacted>',
                  consumer_secret='<redacted>',
                  access_token_key='<redacted>',
                  access_token_secret='<redacted>')

while True:
    menuselect = input("1. Tweet\n2. Get Tweets\n...: ")
    if menuselect == 1 or 2: break
    print "Please enter a valid entry!"

if "1" in menuselect:
    statusinput = raw_input("Tweet: ")
    status = api.PostUpdate(statusinput)
    print "Sucessfully tweeted!"

else:
    timeline5 = api.GetUserTimeline(user_id=<my_twitter_ID>, screen_name='<my_twitter_screenname>', count=5, include_rts='true')
    print [s.text for s in timeline5]

編輯:

使它像這樣工作(包括注釋,以顯示我的答案與我選擇的答案有何不同。感謝您的幫助!))

while True:
#try:
    menuselect = raw_input("1. Tweet\n2. Get Tweets\n...: ")
    if menuselect == "1" or menuselect == "2": break
#catch ValueError:
#   pass
#finally:
    print "Please enter a valid entry!"

if "1" == menuselect:
[...]

要檢查menuselect是否為1 ,應in運算符中使用==運算符NOT。 (因為in運算符來檢查成員的存在)

if 1 == menuselect:

注意:另外,出於安全考慮,不要在Python 2.x中使用input功能來獲取用戶輸入。 改用raw_input並將結果手動轉換為int ,就像這樣

menuselect = int(raw_input("1. Tweet\n2. Get Tweets\n...: "))

注意2:您可能想在break條件下使用in運算符(此處正確,因為您正在檢查menuselect的值是否是可能的值之一),像這樣

if menuselect in (1, 2): break

因為

if menuselect == 1 or 2:

將始終評估為True ,因為其評估為(menuselect == 1) or 2 ,即使menuselect不為2部分也會使表達式評估為Truthy。

編輯:要解決異常部分,當輸入字符串而不是整數時,可以使用try..except這樣的

while True:
    try:
        menuselect = input("1. Tweet\n2. Get Tweets\n...: ")
        if menuselect int (1, 2): break
    catch ValueError:
        pass
    finally:
        print "Please enter a valid entry!"

您遇到的另一個問題是此行:

if menuselect == 1 or 2: break

Python將其解釋為

if (menuselect == 1) or 2: break

這意味着它檢查menuselect是否為1,如果為false,則檢查2是否為true。 在python中,非零數字將解釋為true,因此此條件將始終為true。

將此更改為

if menuselect in [1, 2]: break

或更長

if menuselect == 1 or menuselect == 2: break

暫無
暫無

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

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