0

Can you make this code into oneline if-else comprehensive statement?

https://code.sololearn.com/ckH4DfpYH2PR/?ref=app

21st Jan 2023, 7:11 AM
Reniel Galang
Reniel Galang - avatar
4 Respostas
+ 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!")
21st Jan 2023, 8:05 AM
Mozzy
Mozzy - avatar
+ 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)
21st Jan 2023, 8:18 AM
Per Bratthammar
Per Bratthammar - avatar
+ 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...
21st Jan 2023, 7:56 AM
Reniel Galang
Reniel Galang - avatar
+ 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.
21st Jan 2023, 4:46 PM
Brian
Brian - avatar