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

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

python即使條件為假也會執行if語句

python即使條件為假也會執行if語句

達令說 2023-03-30 16:51:14
這個函數的目標是計算元音,但是在所有情況下都執行 if 語句這是代碼:def count_vowels(txt):  count=0  txt = txt.lower()  for char in txt:        if char == "a" or "e" or "i" or "o" or "u":       count = count+1      print(count)count_vowels(mark)它必須打印 1 但它正在打印 4
查看完整描述

1 回答

?
函數式編程

TA貢獻1807條經驗 獲得超9個贊

問題是您將 char 與 'a' 進行比較,然后僅檢查字符串值是否存在,這是一個值并且在這種情況下始終為真。


def count_vowels(txt):

  count=0

  txt = txt.lower()

  for char in txt:

    

    if char == "a" or "e" or "i" or "o" or "u":

       count = count+1

    

  print(count)


count_vowels(mark)

你需要做:


def count_vowels(txt):

  count=0

  txt = txt.lower()

  for char in txt:

    

    if char == "a" or char == "e" or char == "i" or char == "o" or char == "u":

       count = count+1

    

  print(count)


count_vowels(mark)

或者更清潔的選擇:


def count_vowels(txt):

  count=0

  txt = txt.lower()

  for char in txt:

    

    if char in ['a', 'e', 'i', 'o', 'u']:

       count = count+1

    

  print(count)


count_vowels(mark)


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

添加回答

舉報

0/150
提交
取消
微信客服

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

幫助反饋 APP下載

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

公眾號

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