我正在尝试学习 python,但我对 if 语句有疑问。我收到字符串形式的输入,要求您猜测输出句子中的单词/字符。我正在尝试为其获得两个不同的输出。一个输出是“字符 x 出现/未出现在输出句子中”,另一个输出是“单词 x 出现/未出现在输出句子中”。我设置了一个变量来检查输入的长度并确定它是字符还是单词。我可以得到输出来区分字符和单词,但我无法让它说“...没有出现在输出句子中”。代码如下,请帮助我,我想了解python是如何工作的。
name = input("What's your name?: ")
name_charcount = len(name)
birth_year = input("Birth year: ")
age_years = 2024 - int(birth_year)
age_months = 12 * int(age_years)
age_days = 365.3 * int(age_years)
weight_kg = input("Weight in kg: ")
weight_lbs = float(weight_kg) * 2.20462262
welcome_message = "Welcome back " + name + ", you are " + str(age_years) + " years old (approximately " + str(age_months) + " months or " + str(age_days) + " days) and weigh " + str(weight_lbs) + " lbs"
find_word = input("Guess a word or a character in the output sentence: ")
find_character_length = len(find_word) <=1
find_word_length = len(find_word) >=2
find_years = find_word in welcome_message
print(welcome_message)
if find_character_length:
print("Character " + find_word + (str(find_years).replace('True',' does appear in the output sentence')))
elif find_word_length:
print("Word " + find_word + (str(find_years).replace('True', ' does appear in the output sentence')))
else:
print("Character/Word " + find_word + (str(find_years).replace('False','does not appear in the output sentence')))
这里是一个简单的演示
if..elif..else
-
find_word = input("Guess a word or a character")
find_word_length = len(find_word)
if find_word_length == 0:
print("Please enter a character or word")
elif length == 1:
if find_word in welcome_message:
print("character " + find_word + " not found")
else:
print("character " + find_word + " found")
else:
if find_word in welcome_message:
print("word " + find_word + " not found")
else:
print("word " + find_word + " found")
替代使用
match..case
-
find_word = input("Guess a word or a character")
match len(find_word):
case 0:
print("Please enter a character or word")
case 1:
if find_word in welcome_message:
print("character " + find_word + " not found")
else:
print("character " + find_word + " found")
case _:
if find_word in welcome_message:
print("word " + find_word + " not found")
else:
print("word " + find_word + " found")
使用内联三元的替代方案
..if..else..
-
find_word = input("Guess a word or a character")
find_word_length = len(find_word)
if find_word_length == 0:
print("Please enter a character or word")
print(
"character" if find_word_length == 1 else "word",
find_word,
"found" if find_word in welcome_message else "not found",
)