Python Logiska Operatorer
I verkliga livet uttrycker nästan alla sina tankar med fraser som "Ja eller Nej", "Definitivt Inte", "Ja, ja och ja!". Python-språket tillåter dig att göra nästan samma sak, men det använder mer formella fraser baserade på uttalandena and
, or
och not
. X
och Y
kan vara vilket logiskt uttalande som helst (True
eller False
):
Låt oss titta på koden nedan för att förstå logiken för varje operator:
99
1
2
3
4
5
6
7
8
9
10
11
12
13
# Example of `and` operator
x = True
y = False
result = x and y
print('Result of x and y:', result) # Output: False
# Example of `or` operator
result = x or y
print('Result of x or y:', result) # Output: True
# Example of `not` operator
result = not x
print('Result of not x:', result) # Output: False
12345678910111213# Example of `and` operator x = True y = False result = x and y print('Result of x and y:', result) # Output: False # Example of `or` operator result = x or y print('Result of x or y:', result) # Output: True # Example of `not` operator result = not x print('Result of not x:', result) # Output: False
Uppgift
Swipe to start coding
Föreställ dig att du är en revisor som kontrollerar statusen för en finansiell rapport. Ersätt ___
med True
eller False
för att matcha följande villkor:
- Variabeln
report_is_valid
ska vara True endast om rapporten lämnades in i tid och undertecknades av chefen. - Variabeln
report_is_rejected
ska varaFalse
om rapporten inte lämnades in eller inte granskades av revisorn.
Lösning
9
1
2
3
4
5
6
7
8
9
# The report was submitted on time and signed by the manager
report_is_valid = True and True
# The report was not submitted or not reviewed by the accountant
report_is_rejected = False or False
# Print results
print(report_is_valid)
print(report_is_rejected)
Var allt tydligt?
Tack för dina kommentarer!
Avsnitt 2. Kapitel 3
single
9
1
2
3
4
5
6
7
8
9
# The report was submitted on time and signed by the manager
report_is_valid = True and ___
# The report was not submitted or not reviewed by the accountant
report_is_rejected = False or ___
# Print results
print(report_is_valid)
print(report_is_rejected)
Fråga AI
Fråga AI
Fråga vad du vill eller prova någon av de föreslagna frågorna för att starta vårt samtal