2: Python Basics - Variables and Functions#
1. Variables and Operations#
There are 4 main types of variables
int (integer)
float (decimal number)
string (string of characters)
bool (boolean)
x = 3 # type int
y = 2.5 # type float
first_name = 'Amine' # type string
z = True # type Bool
# Arithmetic operations
print('x + y =', x + y)
print('x - y =', x - y)
print('x / y =', x / y)
print('x // y =', x // y) # integer division (very useful for Numpy tables)
print('x * y =', x * y)
print('x ^ y =', x ** y) # x power y
x + y = 5.5
x - y = 0.5
x / y = 1.2
x // y = 1.0
x * y = 7.5
x ^ y = 15.588457268119896
# Comparison operations
print('equality:', x == y)
print('inequality:', x != y)
print('less than or equal to:', x <= y)
print('greater or equal:', x >= y)
equality: False
inequality: True
less than or equal to: False
greater or equal: True
# Opérations Logiques
print('AND :', False and True)
print('OR :', False or True)
print('XOR :', False ^ True)
AND : False
OR : True
XOR : True
Note: Comparison and logic operations used together allow to build basic algorithmic structures (if/esle, while, …)
2. Functions#
An anonymous function is a function created with lambda. This type of function is basic and is useful to be integrated in the middle of control structures or other functions. It is rarely used.
Show code cell content
# Exemple of a lambda function f(x) = x^2
f = lambda x : x**2
print(f(3))
9
# Exemple2: g(x, y) = x^2 - y^2
g = lambda x, y : x**2 - y**2
print(g(4, 2))
12
The best way to create a function is to use the following structure: def
# Exemple: a function has a name, takes inputs (arguments) and transforms them to return a result
def function_name(argument_1, argument_2):
result = argument_1 + argument_2
return result
function_name(3, 2)
5
# Concrete example : function that calculates the potential energy of a body
def e_potential(mass, height, g=9.81):
energy = mass * height * g
return energy
# here g has a default value so we don't have to give it a value
e_potential(mass=10, height=10)
981.0
3. Exercise and Solution#
Modify the e_potential function defined above to return a value indicating whether the computed energy is greater or less than a limit_energy passed as the 4th argument
Solution :#
Show code cell content
def e_potential(mass, height, e_limit, g=9.81):
energy = mass * height * g
return energy > e_limit
e_potential(mass=10, height=10, e_limit=800)
True