I'm new on python. I'm learning it from internet. As we know in the case of short hand if-else we can change a multiline code into just a single line code and it's really awesome! but i can't understand how to do it in case of nesting inside elif statement? either it's possible or not? if yes, then how? and does it make sense to nest inside a elif statement? here's the code i want to convert into a single line code-
m = ["b", "c"]
a = input()
if a=="a":
x = "a"
elif a in m:
if a=="b":
x = "b"
else:
x = "c"
else:
x = "unknown"
print(x)
please help me : (
CodePudding user response:
elif and else: done by nesting a conditional expression into the else clause of the main conditional.
You should add lots of parentheses to ensure that the grouping of the conditionals is clear.
x = "a" if a == "a" else (("b" if a == "b" else "c") if a in m else "unknown")
I don't recommend writing like this, as it's hard to read.
CodePudding user response:
x = "a" if a == "a" else "b" if a == "b" else "c" if a == "c" else "unknown"
As mentioned earlier, this kind of expression is bad practice. It is not readable there's simpler ways.
CodePudding user response:
I'm sure your trivial solution glosses over much more complicated steps, but I wanted to point out an alternate way I often try to use to accomplish setting a value based on multiple potential conditions.
I recommend taking a look at how a dictionary might be used...
lookup = {
"a": "A",
"b": "B",
"c": "C"
}
user_input = input("enter a single lowercase letter: ")
x = lookup.get(user_input, "unknown")
print(x)
I find it much easier to understand even as a golfy single line:
user_input = input("enter a single lowercase letter: ")
x = {"a": "A", "b": "B", "c": "C"}.get(user_input, "unknown")
print(x)
