I'm trying to learn python and I have an issue with an if statement. I'm getting an input in string form that asks you to guess a word/character in the output sentence. I'm trying to get two different outputs for it. One output would be "Character x does/doesn't appear in the output sentence" and the other is "Word x does/doesn't appear in the output sentence". I set up a variable that checks the length of the input and decides if it's a character or a word. I can get the output to differentiate between characters and words but i cant get it to say "... doesn't appear in the output sentence". Code is below, please help me, I'm trying to understand how python works.
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')))
Mistakes:
as mulan pointed out, str(boolean).replace("True",something)
and etc. is worser as boolean can directly be used to do things with if, converting it to string and replacing it costs higher, so you can use the below code:
.
.
.
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)
#Changes
thing = "Character " if find_character_length else "Word "
print(thing + find_word + (' does appear in the output sentence' if find_years else ' doesn\'t appear in the output sentence'))
Look at changed part of code I used oneliner for elegance