When X is C, A, and B, is it possible to output certain alphabets?
For example, I wanted to make sure that A is output when X=A is output and B is output when X=B is output, but X=A alone needs to define A, so how should I define it?
try:
X = "A"
print(A)
except:
try:
X = "B"
print(B)
except:
try:
X = "C"
print(C)
except:
D = "D"
print(D)
It is not clear what "when X is C, A, or B" at the beginning of the question, but it is the if
statement that determines these conditions.
8.1.if statement
4.Other control flow tools -4.1.if statement
Conditional branching using if statements
Conditional determination/branching can be nested, but it is easier to see if elif
is used to continue with the same indentation.
if...elif...else
if conditional expression 1:
sequence of execution sentences
elif conditional expression 2:
sequence of execution sentences
elif conditional expression 3:
sequence of execution sentences
else:
sequence of execution sentences
Nested if
if conditional expression 1:
sequence of execution sentences
else:
If conditional expression 2:
sequence of execution sentences
else:
If conditional expression 3:
sequence of execution sentences
else:
sequence of execution sentences
So if you apply it to the source of the question, it will look like this:
A="a"####################################################
B = "b"##### Same as below
C = "c"
D = "d"
if X == "A": #### Conditional determination
print(A)#### You can specify the characters you want to print as print("a") directly.
elif X=="B":
print(B)
elif X=="C":
print(C)
else:
print(D)
Also, the source of the question is a substitute statement and exception handling, so it is different from conditional judgment.
7. Simple statement -7.2. Assignment statement
Defining variables and substituting values
8. compound statement-8.4.try statement
Python exception handling!Explain try-except in an easy-to-understand way!
© 2024 OneMinuteCode. All rights reserved.