0
Why won't this code work
age = 18 if age <18: print("You're younger than 18") if age >=18: print("You're 18 and over") So, I am beginner in python and coding in general, so I apologise in advance if this is a stupid question. I am currently learning about if statements. The code I wrote above doesn't seem to work, I specifically get no output. Is there a reason for this? Thank you very much.
4 Antworten
+ 4
the problem is with your indentation. in python defines a block. you have accidentally placed your second if block in the first if block which only gets executed when the age is less than 18. therefore the second if block never gets executed.
indentation block is often marked with four spaces. remove the spaces and it should work fine.
if age < 18:
// not an adult
if age >= 18:
// adult
+ 2
Thanks for the quick reply everyone, I gave it a try and it worked. I will be careful of the indentation next time.
Thanks!!
+ 1
Try this instead:
age = 18
if age < 18:
print("You're younger than 18")
if age >= 18:
print("You're 18 and over")
The subtle difference is the indentation. Your second if statement is indented which means it is still a part of your original if statement. Since that if returns False, it is ignored. That's why your second if is ignored.
+ 1
No problem.
Good luck and happy coding!