0
Can you make this code into oneline if-else comprehensive statement?
5 Respuestas
+ 4
Reniel Galang
x = int(input())
print("Help me Batman" if 5<=x<=10 else "Good Luck out there!" if x >10 else "I got this!")
+ 2
# Hi, Reniel Galang !
msg_1 = "I got this!"
msg_2 = "Help me Batman"
msg_3 = "Good Luck out there!"
x = int(input())
if x < 5:
print(msg_1)
elif 5 <= x <= 10:
print(msg_2)
else: # x > 10
print(msg_3)
# This above is the same as:
print(msg_1) if x < 5 else print(msg_2) if 5 <= x <= 10 else print(msg_3)
# So: What comes after the first else is running if not (x < 5).
# Maybe its more easy to see it in this way:
if x < 5:
print(msg_1)
else:
if 5 <= x <= 10:
print(msg_2)
else: # x > 10
print(msg_3)
+ 1
Scott D
# however, the last line of code here is working...
food = input().split()
pts = 0
for i in food:
if i == "Carrot":
pts += 4
elif i == "Mango":
pts += 9
elif i == "Lettuce":
pts += 5
else:
pts += 0
print("Come on Down!" if pts >= 10 else "Time to wait")
# so i was just thinking if this kind of syntax can handle three or more statements...
+ 1
Reniel Galang it can be done as a true one-liner without an if statement. This is not recommended due to obscured logic.
print({0:"I got this!", 1:"Help me Batman"}.get((int(input()) + 1)//6, "Good Luck out there!"))
Here I found a way to convert the ranges of inputs to single digits for dictionary lookup: 0-4 becomes 0, 5-10 becomes 1, 11 and greater become 2 and greater.
When the lookup fails to find 0 or 1, the default parameter in the get method handles 2 or greater.