Why do the else run after the first if run too? | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
0

Why do the else run after the first if run too?

print("Hello, welcome to the temperature converter") t=int(input("Which one you want to do? For F->C type 1, for C->F type 2")) if t == 1: f=float(input("What's the temperature?")) c=5*(f-32)/9 print(c) if t == 2: c=float(input("Whats the temperature?")) f=c*1.8+32 print(f) else: print("Invalid option") As you can see there are 3 options on it, two "if" and one "else". But the problem that I dont understand is why when the first "if" in the top run then the "else" runs too.

27th Feb 2017, 8:22 PM
print (Xx_Lycis_xX)
print (Xx_Lycis_xX) - avatar
4 Answers
+ 3
having only two possible inputs check if (input>2){ prompt for invalid option }else{ if input==1 do something else do something else } in your code you do the input check twice for every input. so when you type 1 the first if condition is met (input ==1) and also the second else condition is met (input !=2) if your input is 2 the first else condition is met (input!=1) and the second if condition is met (input==2).
27th Feb 2017, 8:34 PM
seamiki
seamiki - avatar
+ 2
Your else run coz of a second if. Change it to elif) When you have 2 if'es in your code with else: one if your if'es can be triggered, but the second mb cant, so the esle block will come))
27th Feb 2017, 8:27 PM
Leshark
Leshark - avatar
+ 1
you might need an if-elif-else Statement instead of two if Statements. and the conditions may not be ambiguious
27th Feb 2017, 8:25 PM
Anissa Fuger
Anissa Fuger - avatar
0
Ohh thanks guys. Since I'm still learning python I didnt know this "elif". I will search how to use it as well. This is one of my very first codes. And if you guys have any ideia how I could improve it that you want to share I would really appreciate it =)
27th Feb 2017, 8:33 PM
print (Xx_Lycis_xX)
print (Xx_Lycis_xX) - avatar