亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

while 循環似乎無法正常運行

while 循環似乎無法正常運行

森欄 2023-06-20 14:37:50
我正在開發一個使用while循環的 python 項目。獨特的東西。但是,我無法讓循環為我完成它的工作。我的代碼:with open("accounts.txt", "r") as account_file:    while account == "":        account = str(input("Enter a username: ") + " ")        if account not in account_file.read():            print("That username was not found.")            account = ""當我運行它時,它會提示我輸入用戶名,如果可以在其中找到我輸入的字符串(加上添加的空格),accounts.txt我將被告知可以找到我的用戶名。如果我輸入了一個無效的用戶名,程序應該會告訴我它找不到我輸入的用戶名然后讓我再試一次——除非我在下次嘗試時輸入正確的用戶名,程序仍然會告訴我我的用戶名找不到。我嘗試進行此更改:if account in account_file.read():    account = accountelse:    print("That username was not found.")    account = ""而且它仍然無法正常工作。誰能告訴我為什么?我只是在尋找一個簡單的解決方案。
查看完整描述

1 回答

?
www說

TA貢獻1775條經驗 獲得超8個贊

我假設你想找到文件中用戶名所在的文件行。如果您對查找用戶名所在的特定行不感興趣,而只想繼續循環直到輸入有效的用戶名,那么您應該知道您只能在文件打開后調用一次read()。


考慮這樣做:


while account == "":

? ? account = str(input("Enter a username: ") + " ")

? ? with open("accounts.txt", "r") as account_file:

? ? ? ? if account not in account_file.read():

? ? ? ? ? ? print("That username was not found.")

? ? ? ? ? ? account = ""

如果您確實想要用戶名所在的行,您可能需要這樣的東西:


with open("accounts.txt", "r") as account_file:

? ? account = str(input("Enter a username: ") + " ")

? ? for line in account_file:

? ? ? ? if account in line:

? ? ? ? ? ? print("Found username")

? ? ? ? ? ? break


查看完整回答
反對 回復 2023-06-20
  • 1 回答
  • 0 關注
  • 159 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號