Python-Ref > Basic usage > Operators > Logical operators - common mistakes
 
 

<-^^
Klíčová slova
Moduly
Knihovní funkce

Logical operators - common mistakes

Mistakes that people often make when combining questions.
When combining several sub-questions into one, beginners often tend to translate the questions too literally from the human language. This often leads to unexpected results.
The following code should print only the names starting wiht "A", "B", or "C".
Expand/Shrink
Zdroj: (operators4-1.py)
  1   # I would like to print only names that start with "A","B" or "C"
  2   
  3   names = ["Anthony", "Joseph", "David", "Anne", "Christopher", "Brutus", "John"]
  4   
  5   for name in names:
  6     if name[0] == "A" or "B" or "C":  # from english "is name[0] equal to A or B or C?"
  7       print name
stdout:
Anthony
Joseph
David
Anne
Christopher
Brutus
John
Doba běhu: 22.1 ms
However it does not work (all names are printed). This is because "or" is used to combine logical expressions - either True or False. Lets look deeper into the example.
Expand/Shrink
Zdroj: (operators4-2.py)
  1   # I would like to print only names that start with "A","B" or "C"
  2   
  3   names = ["Anthony", "Joseph", "David", "Anne", "Christopher", "Brutus", "John"]
  4   
  5   for name in names:
  6     print " A", bool( name[0] == "A")
  7     print " B", bool( "B")
  8     print " C", bool( "C")
  9     # brackets show how the expression is evaluated
 10     if (name[0] == "A") or ("B") or ("C"):
 11       print name
stdout:
 A True
 B True
 C True
Anthony
 A False
 B True
 C True
Joseph
 A False
 B True
 C True
David
 A True
 B True
 C True
Anne
 A False
 B True
 C True
Christopher
 A False
 B True
 C True
Brutus
 A False
 B True
 C True
John
Doba běhu: 21.3 ms
It is now obvious that "B" and "C" translated into boolean values are always True, thus the result of the whole logical expression is always True as well.
Expand/Shrink
Zdroj: (operators4-3.py)
  1   # I would like to print only names that start with "A","B" or "C"
  2   
  3   names = ["Anthony", "Joseph", "David", "Anne", "Christopher", "Brutus", "John"]
  4   
  5   for name in names:
  6     # brackets show how the expression is evaluated
  7     if (name[0] == "A") or (name[0] == "B") or (name[0] == "C"):
  8       print name
stdout:
Anthony
Anne
Christopher
Brutus
Doba běhu: 21.2 ms