10 times 25 = 250
PHOT 110: Introduction to programming
LECTURE 02
Michaël Barbier, Spring semester (2023-2024)
A Python script is a sequence of statements (algorithm steps), and definitions (functions, classes, …)
Executing a program:
Execute statements one by one in the Python Console
Useful for:
Statements stored in a script file
10 times 25 = 250
Useful for:
Data objects can be scalar:
Type | Description | (Example) values |
---|---|---|
bool |
Boolean value | True , False |
int |
Integer numbers | .. , -2 , -1 , 0 , -1 , -2 , .. |
float |
Floating point | 3.56 , 23e-3 , 0.0079 |
NoneType |
Indicates no object | None |
<class 'float'>
it_is_raining = True
print(type(it_is_raining))
an_integer = int(it_is_raining)
print(type(an_integer))
<class 'bool'>
<class 'int'>
float
<= int * float
float
<= int + float
float
<= int / int
a = 4
b = 0.357
print( f"Type of (a * b) = {type(a * b)}" )
print( f"Type of (a / b) = {type(a / b)}" )
print( f"Type of (a + b) = {type(a + b)}" )
print( f"Type of (a / 25) = {type(a / 25)}" )
Type of (a * b) = <class 'float'>
Type of (a / b) = <class 'float'>
Type of (a + b) = <class 'float'>
Type of (a / 25) = <class 'float'>
A variable is a name bound to an object:
In python assignment operator is the “=” sign:
The variable can be re-assigned another value or object:
Objects can be combined by operators in expressions
Most used arithmetic operators:
symbol | description | example |
---|---|---|
** | Power | 3**2 = 9 |
/ | Division | 5 / 4 = 1.25 |
* | Multiplication | 3 * 4 = 12 |
+ | Addition | 5 + 7 = 12 |
- | Subtraction | 6 - 9 = -3 |
% | modulo | 34 % 6 = 4 |
Most used logic operators:
symbol | description | example |
---|---|---|
< , > |
smaller/larger than | 5 > 4 \(\rightarrow\) True |
== |
is equal to | 3 == 6 \(\rightarrow\) False |
<= , >= |
smaller/larger or equal | 5 <= 5 \(\rightarrow\) True |
and |
boolean AND | True and False \(\rightarrow\) False |
or |
boolean OR | True or False \(\rightarrow\) True |
not |
boolean NOT | not True \(\rightarrow\) False |
An expression can be built with following rules:
<expression>
\(\overset{def}{=}\) <object>
(an object is an expression)<expression>
\(\overset{def}{=}\) <operator> <expression>
<expression>
\(\overset{def}{=}\) <expression> <operator> <expression>
Expressions result into values and can be assigned to variables:
The value of y = 39
Precedence of operators is similar to mathematics.
List of precedence of operators can be found on the python.org website: https://docs.python.org/3/reference/expressions.html#operator-precedence
Round brackets can be used to give priority
The value of y = 1.0
Text objects are called strings: the type is str
A string is defined by using single or double quotes:
Strings can also cover multiple lines, for that we use triple quotes:
Also triple single quotes work as well.
Appending one string to another with the “+” operator:
The balloonflies
The balloon flies
Multiplying strings:
balloon balloon balloon balloon balloon
Casting a string to a number and vice versa:
500
50505050505050505050
A formatted string is a string with prefix f
or F
:
A circle with radius 25 m
More complex formatting:
a = 1/6; b = 0.0145; c = 23e-6
print(f"The product {a} x {b} = {a * b}")
# Use format {variable:No_space.No_sign_digits}
print(f"{a:8.2} x {b:8.2} = {a * b:8.2}")
print(f"{a:8.2} x {c:8.2} = {a * c:8.2}")
The product 0.16666666666666666 x 0.0145 = 0.002416666666666667
0.17 x 0.015 = 0.0024
0.17 x 2.3e-05 = 3.8e-06
['False', 'None', 'True', 'and', 'as', 'assert', 'async', 'await', 'break', 'class', 'continue', 'def', 'del', 'elif', 'else', 'except', 'finally', 'for', 'from', 'global', 'if', 'import', 'in', 'is', 'lambda', 'nonlocal', 'not', 'or', 'pass', 'raise', 'return', 'try', 'while', 'with', 'yield']
input()
can be used to ask user text inputprint()
can be used to output text# parameters
pizza_price = 200
extra_cheese_price = 20
# input accepts a string parameter
n_pizza = input("How many pizza's do you want: ")
extra_cheese = input("""Do you want extra cheese?\n
For yes press [1]\n
For no press [0]\n
Enter your choice""")
# Output to the user
print("Total cost: {int(n_pizza * (pizza_price + extra_cheese)}")
IndentationError: unexpected indent
IndentationError: unexpected indent (3759259151.py, line 3)
Python packages can be imported in multiple ways
# import the package with its name
import math
area = 3**2 * math.pi
print(f"Area of a circle with radius 3 = {area}")
# import functions of the package separately
from math import sin, cos, pi, sqrt
angle = 23/180*pi
formula = sqrt(2/3) * sin(angle) + cos(angle)
# import packages or functions and rename them
from math import sqrt as sr
print(f"The square root of 2 = {sr(2)}")
Multi-line strings can be used as comments, but
__doc__
variable__doc__
variableThis module provides access to the mathematical functions
defined by the C standard.
__doc__
variable__doc__
variableHelp on built-in function sin in module math:
sin(x, /)
Return the sine of x (measured in radians).
Different types of errors can be encountered
NameError: name 'uint' is not defined
IndentationError: unexpected indent (3752930843.py, line 2)
SyntaxError: invalid syntax (173182802.py, line 1)
ZeroDivisionError: division by zero
TypeError: can only concatenate str (not "float") to str
The trajectory is a parabola (no air):
\[ \begin{aligned} x &= x_0 + v_{x,0} t\\ y &= y_0 + v_{y,0} t - \frac{1}{2}g t^2 \end{aligned} \] The ball will hit the ground at time \(t_e\):
\[ t_{e,\pm} = \frac{-b \pm \sqrt{b^2-4ac}}{2a} = \frac{v_{y,0} \mp \sqrt{v_{y,0}^2+2gy_0}}{g} \]
# Loading packages for sin, cos, pi, sqrt
import math
# Parameters of the trajectory
y0 = 1.20; x0 = 0
v0 = 8
alpha0 = 37 * (math.pi / 180) # Angle
g = 9.81
# compute the time that the ball will hit the ground
vy0 = v0 * math.sin(alpha0)
vx0 = v0 * math.cos(alpha0)
te = (vy0 + math.sqrt(vy0**2 + 2*g*y0)) / g
print(f"The ball falls at time: {te} s")
The ball falls at time: 1.1875623706903884 s
The trajectory is a parabola (no air):
\[ \begin{aligned} x &= x_0 + v_{x,0} t\\ y &= y_0 + v_{y,0} t - \frac{1}{2}g t^2 \end{aligned} \]
The equation for the parabola can be found by substitution. If \(x_0 = 0\) then \(t = x/v_{x,0} = x / (v_0 \cos(\alpha))\) and we obtain:
\[ y = y_0 + \tan(\alpha) \, x - \frac{1}{2}\frac{g\, x^2}{v_0^2\cos^2(\alpha)} \]
Let’s start from the equation of the parabola:
\[ y = y_0 + \tan(\alpha) \, x - \frac{1}{2}\frac{g\, x^2}{v_0^2\cos^2(\alpha)} \]
When solving this quadratic equation for \(x\) we find:
\[ x_{e,\pm} = \frac{-b \pm \sqrt{b^2-4ac}}{2a} = \frac{\tan\alpha \mp \sqrt{\tan^2\alpha+2gy_0/(v_0\cos\alpha)^2}}{g / (v_0 \cos\alpha)^2} \] Where the largest root is the throwing distance.
# Loading packages for sin, cos, pi, sqrt
from math import sin, cos, pi, sqrt, tan
# Parameters of the trajectory
y0 = 1.20; x0 = 0
v0 = 8
alpha0 = 37 * (pi / 180) # Angle in radians
g = 9.81
# compute the time that the ball will hit the ground
vy0 = v0 * sin(alpha0)
vx0 = v0 * cos(alpha0)
xe_num = (tan(alpha0) + sqrt(tan(alpha0)**2 + 2*g*y0 / (v0*cos(alpha0))**2))
xe_den = (g / (v0 * cos(alpha0))**2)
xe = xe_num / xe_den
print(f"The ball falls at x: {xe} m")
The ball falls at x: 7.587435837034325 m
# Loading packages for plotting and numeric calc.
import matplotlib
import matplotlib.pyplot as plt
import numpy as np
# Computing x and y coordinates for the trajectory
ts = np.linspace(0, te, 10)
xs = vx0 * ts
ys = y0 + (vy0 * ts) - (g*ts**2)/2
# Plotting the trajectory of the ball
matplotlib.rcParams.update({'font.size': 20})
plt.plot(xs, ys, "-", color="red")
plt.plot(xs, ys, ".", color="blue")
ax = plt.gca()
ax.set_xlabel("x (in m)")
ax.set_ylabel("y (in m)")
ax.set_aspect('equal', 'box')
Lecture 02: Python basics
Comment lines
Comments can explain the next line of code
Or the comment can start after a statement