var1=20
if var1>18:
print("you can drive")
if var1==18:
print("you can too drive")
if var1 > 30:
print("your age is more")
else:
print("you cannot drive ")
CodePudding user response:
You likely meant to use some elif
s. As it stands, let's add some breaks to show how your code looks to the interpreter: three separate conditional statements rather than one.
var1 = 20
if var1 > 18:
print("you can drive")
###################################
if var1 == 18:
print("you can too drive")
###################################
if var1 > 30:
print("your age is more")
else:
print("you cannot drive ")
If var1
is less than or equal to 30
, "your cannot drive"
will print.
You want:
var1 = 20
if var1 > 18:
print("you can drive")
elif var1 == 18:
print("you can too drive")
elif var1 > 30:
print("your age is more")
else:
print("you cannot drive ")
Now it's all one statement.
CodePudding user response:
As per your comment, if you only want to use if and not elif, then this might be a solution:
var1=20
if var1>18:
if var1>30:
print("your age is more")
else:
print("you can drive")
if var1==18:
print("you can drive too")
if var1<18:
print("you cannot drive ")
Result:
input: 20
you can drive
input: 31
your age is more
CodePudding user response:
After correcting the syntax errors, you are getting two outputs because the else is considered for the last if condition, not the first one. I think what you want to implement though looks like this:
var1=20
if var1>18: print("you can drive")
elif var1==18: print("you can too drive")
elif var1 > 30: print("your age is more")
else: print("you cannot drive ")