Python Conditionals¶
- Keywords
ifelifelse
- Conditionals
- ==, !=, <, <=, >, >=,
and, or, not - Keywords:
TrueandFalse
- ==, !=, <, <=, >, >=,
Examples
In [1]:
x = 55
In [2]:
if x < 10: # note the ":"
print("x < 10")
# do more code here
In [3]:
if x < 3 :
print("x < 3")
else : # note the "else"
print("x >= 3")
x >= 3
In [4]:
if x < 3 :
print("x < 3")
elif x < 4 : # note the "elif"
print("x < 4")
In [5]:
x = 1
if x < 3:
print("stuff")
if x < 5:
print("stuff")
stuff stuff
In [6]:
if x < 3 :
print("x < 3")
elif x < 4 :
print("x < 4")
else: # else to cap it off
print("x >= 4")
x < 3
In [7]:
if x < 3 :
print("x<3")
elif x < 5 : # multiple elif
print("x<5")
elif x > 5 :
print("x>5")
else :
print("something else")
x<3
In [8]:
x = 5.5
if (x > 3 and x < 6) or x <= 1 :
print("made it")
print("Doing some more stuff in here")
print("Can have multiple lines. ")
print("Blank lines don't matter.") # note the use of the single and double quotes
print("Indent all lines inside the block at the same level")
made it Doing some more stuff in here Can have multiple lines. Blank lines don't matter. Indent all lines inside the block at the same level
Can use variables or expressions in if statements
In [9]:
Tmin = 298.15
T = 500
if T < Tmin :
print("Warning, T<Tmin")
if T > Tmin*10 :
print("Warning, T>10*Tmin")
if Tmin <= T and T <= 10*Tmin:
print("All is well with T, nice work.")
All is well with T, nice work.
Scope: variables declared outside the if statement can be seen inside.
In [10]:
Tmin = 298.15
T = 500
if T> Tmin:
print("T =", T)
T = 500
Here is a condensed if statement:
In [11]:
T = 298.15 if x<5.0 else 500.0 # single line if statement
print("x=", x, ", T=", T)# note: sep='' changes the separation character
x= 5.5 , T= 500.0
Example
Take the the square root, and make the argument positive if its negative:
In [12]:
x = -9
print(x**0.5)
y = (x if x>=0 else -x)**0.5
print("y = ", y)
(1.8369701987210297e-16+3j) y = 3.0
In [13]:
print(x)
torf = x>5.5
if torf:
print("stuff")
print(torf)
-9 False
In [14]:
type(torf)
Out[14]:
bool
In [15]:
type(x)
Out[15]:
int
In [16]:
a = 3.3
type(a)
Out[16]:
float
In [17]:
def sqrt(x):
if x >= 0:
print(x**0.5)
return True
else:
return False
In [18]:
x = 55
if x==0:
a/(x+1E-16)
else:
a/x
In [19]:
x = 5.
type(x)
Out[19]:
float
In [20]:
x = True
type(x)
Out[20]:
bool
In [ ]:
In [ ]: