Learning Python

Conditions

Python supports the usual logical conditions from mathematics:

• Equals: a == b
• Not Equals: a != b
• Less than: a < b
• Less than or equal to: a <= b
• Greater than: a > b
• Greater than or equal to: a >= b
a = 33
b = 200
if b > a:
print("b is greater than a")


Indentation

a = 33
b = 200
if b > a:
print("b is greater than a") # you will get an error


if-then-elif

a = 33
b = 33
if b > a:
print("b is greater than a")
elif a == b:
print("a and b are equal")


if-then-else

a = 200
b = 33
if b > a:
print("b is greater than a")
else:
print("b is not greater than a")

a = 200
b = 33
if b > a:
print("b is greater than a")
elif a == b:
print("a and b are equal")
else:
print("a is greater than b")


Nested if-then-else

x = 41

if x > 10:
print("Above ten,")
if x > 20:
print("and also above 20!")
else:
print("but not above 20.")


Logical operators

And

a = 200
b = 33
c = 500
if a > b and c > a:
print("Both conditions are True")


Or

a = 200
b = 33
c = 500
if a > b or a > c:
print("At least one of the conditions is True")


Shorthand and Conditional Expressions

a = 2
b = 330
if a > b: print("a is greater than b")

a = 2
b = 330
print("A") if a > b else print("B")


Ternary Conditional Operator

a = 2
b = 330
print("A") if a > b else print("B")

b = 330
print("A") if a > b else print("=") if a == b else print("B")


Using Functions

def my_function():
print("Hello from a function")

def my_function():
print("Hello from a function")

def main():
my_function()

def my_function(fname):
print(fname + " Refsnes")

def main():
my_function("Emil")
my_function("Tobias")
my_function("Linus")

def my_function(x):
return 5 * x

def main():
print(my_function(3))
print(my_function(5))
print(my_function(9))

def my_function(country = "Norway"):
print("I am from " + country)

def main():
my_function("Sweden")
my_function("India")
my_function()
my_function("Brazil")