簡體   English   中英

盡管有一個有效值作為輸入,程序仍拒絕運行“if”語句

[英]Program refuses to run 'if' statement despite having a valid value as an input

我對計算機編程非常陌生,目前正在 PyCharm 社區中編寫一個程序,當給出我學校的一個學生的名字時,它將打印出從學校到該學生家的路線。

一切都進行得很順利,昨晚我的基礎工作已經開始了。 今天我打開我的電腦,由於某種原因,我的程序拒絕運行我的“if”/“elif”語句,並且只會運行 else 語句,即使它被賦予了一個滿足“if”/“elif”語句的值。

我試過重寫程序,多次重啟PyCharm,確保空格和制表符一致,並確保我的變量都可以相互通信。 我在這里和其他網站上挖了一段時間,我只是看不出為什么我的代碼昨天可以工作,但現在除了 else 語句之外拒絕運行任何東西。

這是我的代碼,它會問用戶“你想去哪里 go?” 然后將收到“房子”的輸入。 一旦收到它,它將打印出他們的方向。 取而代之的是,它每次都運行“else”語句。

# Storing the names and directions of users:
David = "Directions to David's home from T... \n East on X, \n South on Y.," \
            " \n West on Z., \n South on A., \n first white house on the right."

Caroline = "Directions to Caroline's home from T... \n East on x, \n South on y.," \
        " \n East on z., \n South on p., \n East on q," \
        " \n West on t., \n last brick house in the cul-de-sac."

William = "Directions to Will's home from T... \n East on x, \n South on y.," \
        " \n West on z., \n South on Fa., \n West on b., \n first house on the right."

Bannon = "<Insert directions to Bannon's house>"

# User gives a specific name and then receives a location:
while True:
    destination = input("Where would you like to go? ")

    if destination.casefold() == 'Davids house':
        print(David)
        continue

    elif destination.casefold() == 'Carolines house':
        print(Caroline)
        continue

    elif destination.casefold() == 'Wills house':
        print(William)
        continue

    elif destination.casefold() == 'Bannons house':
        print(Bannon)
        continue

    # If an invalid location is given, this code will run:
    else:
        print("Sorry, that location wasn't found! Please try again.")
        continue

casefold將字符串轉換為小寫,並且您的參考字符串包括大寫字符。

作為一個簡單的修復,您可以將“大衛之家”更改為“大衛之家”等。

從長遠來看,您可能希望實現一個稍微不那么脆弱的比較,但這是一個很大的練習,並且取決於您的程序將如何使用以及解析失敗的后果是什么。

為了糾正錯字並支持用戶做的事情會破壞測試,下面是一個使用字符串相似性比較來確定輸入是否接近任何用戶名的示例:

import difflib
# Storing the names and directions of users: 
#This is called a dictionary. More info here https://www.w3schools.com/python/python_dictionaries.asp
directions= {
    "David": "Directions to David's home from T... \n East on X, \n South on Y.," \
            " \n West on Z., \n South on A., \n first white house on the right.",

    "Caroline": "Directions to Caroline's home from T... \n East on x, \n South on y.," \
        " \n East on z., \n South on p., \n East on q," \
        " \n West on t., \n last brick house in the cul-de-sac.",

    "William":"Directions to Will's home from T... \n East on x, \n South on y.," \
        " \n West on z., \n South on Fa., \n West on b., \n first house on the right.",

    "Bannon":"<Insert directions to Bannon's house>"
}

# User gives a specific name and then receives a location:
while True:
    destination = input("Where would you like to go? ")

    highest = 0 #highest score between the user name and input
    user_key = "" #name of the user who most closely matches the input
    for user in directions: #iterate through all the user's names in the directions dictionary
      similarity = difflib.SequenceMatcher( #for each user's name, compare it to the input
          None, destination, user).ratio()
      if(similarity > highest): #if the similarity score is greater than the highest recorded score, update the score
        highest = similarity
        user_key = user
    
    #Code that runs if a match is too low are not found
    if(highest < 0.5): #adjust this based on how close you want the match to be. highest will always be between 0.0 and 1.0
      print("Sorry, that location wasn't found! Please try again.")
      continue

    #Print user's directions
    else:
      print('\n\nGetting directions to ' + user_key + '\'s house\n\n')
      print(directions[user_key] + "\n\n\n")

因此,如果您輸入“William's house”、“William”、“William's house”、“William”或接近“William”的名稱,您將獲得前往 William's house 的路線。

在線運行: https://repl.it/@marsnebulasoup/UprightMutedSymbol

最小化程序和測試。 您發布了比演示問題所需的更多代碼。 一旦你得到類似if destination.casefold() == 'Davids house': not working 的東西,盡量減少罐頭數據的問題

destination = "david's house"
if not destination.casefold() == "Davids house":
    print(repr(destination), "failed")

這打印

"david's house" failed

casefold的幫助說返回適合無大小寫比較的字符串版本。 . 啊,就是這樣。 你需要把兩邊都折疊起來。 然后是那個討厭的撇號。 也許您需要更多規范化,例如擺脫非字母字符。

通過最小化,您為您的代碼編寫了一個很好的測試。 您可以編寫一個小的比較 function 來進行 casefold 和其他規范化。 然后,您可以對該 function 編寫十幾個測試來測試所有邊緣情況。

暫無
暫無

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

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