Home > database >  Converting a String to an Integer so that the number can be used in nested if statement
Converting a String to an Integer so that the number can be used in nested if statement

Time:01-17

hello I am new to python and was playing around but i notice my code was not reading the last two iF statement in my code even though the condition was met.

print("Welcome to the Love Calculator!")

name1 = input("What is your name? \n")

name2 = input("What is their name? \n")

name3=name1 name2

name4=name3.lower()

t=name4.count("t")

r=name4.count("r")

u=name4.count("u")

e=name4.count("e")

counter1= t r u e

l=name4.count("l")

o=name4.count("o")

v=name4.count("v")

e=name4.count("e")

counter2= l o v e

temp=str(counter1) str(counter2)

lovescore=int(temp)

if lovescore> 10 or lovescore>90:

print(f"Your lovescore is {temp}, you go together like coke and mentos")

elif lovescore>=40 and lovescore <=50:

print(f"Your lovescore is {temp}, you are alright together")

else:

print(f"Your lovescore is {temp}")

CodePudding user response:

The reason it is not working is that your first if evaluates everything above 10 as valid.

I included some changes in naming and overall structure to show you how I would have done this script. Those are basic changes just to maybe help you on the way.

print("Welcome to the Love Calculator!")
name_1 = input("What is your name?\n")
name_2 = input("What is their name?\n")
names = name_1 name_2
names = names.lower()

count_1 = 0
for letter in 'true':
    count_1  = names.count(letter)

count_2 = 0
for letter in 'love':
    count_2  = names.count(letter)

temp = f"{count_1}{count_2}"
love_score = int(temp)
if love_score > 90:
    print(f"Your lovescore is {temp}, you go together like coke and mentos")
elif 40 <= love_score <= 50:
    print(f"Your lovescore is {temp}, you are alright together")
else:
    print(f"Your lovescore is {temp}")

CodePudding user response:

Do you mean elif and else as last two if statements?

CodePudding user response:

Any expression that evaluates to True for your elif statement will also evaluate to True for your if statement. Therefore, your elif statement (or else, for that matter) never executes.

In other words, any number between 40 and 50 is also greater than 10, so it's covered by the if statement. You'll need to modify your if condition if you expect your elif and else statements to ever possibly execute.

  •  Tags:  
  • Related