Programming with Python

⌘K
  1. Home
  2. Docs
  3. Programming with Python
  4. Control Flow, Functions

Control Flow, Functions

Conditionals

  • Flow of execution of instruction can be controlled using conditional statements
  • Conditional statements have some Boolean expression
  • Boolean expression can have relational operators or logical operators or both

Boolean values and Operators

Boolean Data type

  • The Boolean data type is either True or False
  • In python, Boolean variables are defined by True and False keywords
  • In programming, one often need to know if an expression is True of False
  • When two values are compared, the expression is evaluated and python returns Boolean answer

Example,

>>> print(10>9)
True
  • Any string is True, except empty strings
  • Any number is true, except 0
  • Any list, tuple, set and dictionary are True, except empty ones
>>> bool(1)
True
>>> bool(0)
False
>>> True + True
2
>>> True + False
1
>>> False + False
0
>>> True * False
0
>>> True
True
>>> False
False
>>> bool(9)
True
>>> bool("Hello")
True
>>> bool("")
False
>>> bool(True + True)
True
>>> bool(True * False)
False

Comparison (Relational) Operators

  • Comparison Operators are used to compare values
  • It either returns true or false depending on the condition
  • Assume a = 3 and b = 2

Example

a = 3
b = 2
print("a==b = ", a==b)
print("a!=b =",a!=b)
print("a>b =",a>b)
print("a<b =",a<b)
print("a>=b=",a>=b)
print("a<=b = ", a<=b)

Output

('a==b = ', False)
('a!=b =', True)
('a>b =', True)
('a<b =', False)
('a>=b=', True)
('a<=b = ', False)

Logical Operators

Logical Operators are used to combine conditional statements

Example

a=5
b=10
print("a<5 and b <20", a<5 and b<20)
print("a<5 or b <20",a<5 or b<20)
print("not(a<5 and b<20)",not(a<5 and b<20))

Output

('a<5 and b <20', False)
('a<5 or b <20', True)
('not(a<5 and b<20)', True)

Loading

Views: 0

Articles

How can we help?

0 0 votes
Article Rating
Subscribe
Notify of
guest

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments