Python Programming (very fast) Introduction#
Importing modules#
Python has an extensive standard library (https://docs.python.org/3/library/) to perform several task in optimized and easy-to-use way. For basic mathematical operations you can just use the normal operators, but for other standard functions, like sin
, you could import the standard math
module, or , much better, use either numpy
or scipy
modules
import math as m # imports the math module with an alias m
# import math # imports math module but you need to use math.sin or math.cos
# from math import * # DO NOT do this: exposes all inners from math
x = 5.2
y = m.sin(x)
print(x, y)
# YOUR CODE HERE
raise NotImplementedError()
---------------------------------------------------------------------------
NotImplementedError Traceback (most recent call last)
Cell In[1], line 2
1 # YOUR CODE HERE
----> 2 raise NotImplementedError()
NotImplementedError:
# YOUR CODE HERE
raise NotImplementedError()
Looking for help#
What are the units of the argument for the sin
function? Are there any other functions provided by the numpy
module? Check the documentation using either google or, inside a notebook
help(np.sin)
help(np)
np.sin?
import numpy as np
help(np.sin)
Printing and reading to and from the screen#
You have already seen how to print to the screen. To read, you can use the function call input
. Try it:
var = input("Please write something :\t")
print("You have written : " + var)
print(f"You have written : {var}") # uses a f-string: https://realpython.com/python-f-strings/
You can also format the printing string, like you have done in c/c++ . For example, you can write something like
x = 5
y = 2.34
print("x = %04d \t y = %.1f \n y=%20.16e\n"%(x, y, y))
print(f"x = {x:04d} \t y = {y:.1f} \n y={y:20.16e}")
Note: if you need to manipulate strings and numbers, you should cast the number to string by using str
, as in str(x)
.
x = 32.6
y = -4.7
# YOUR CODE HERE
raise NotImplementedError()
Selection structures : if
, if else
#
This is a simple example on how to use if to select from several options
m = 5
if m < 1:
print (f"{m} is smaller than 1")
elif 1 <= m <= 4:
print (f"{m} is in between 1 and 4")
else :
print (f"{m} is larger than 4")
You can also compare values directly, or even compare several values
print(2 == 3)
print(2 == 2 and 3 > 9)
print([2, 3] == [3, 2])
print([2, 3] == [2, 2])
print([2, 3] == [2, 3])
# YOUR CODE HERE
raise NotImplementedError()
Loop structures: for and while#
N = 5
i = 0
while i < N:
print (i, end=" ")
i = i+1
for ii in range(1, 10):
print(f"{ii}", end=" ")
name = "My name" # a string is an array for characters
for c in name:
print (c, end="-")
print()
print(name[0])
print(name[-1])
# ii = 0.0
# while ii < 1.0:
# print(ii)
# ii = ii + 0.05
# YOUR CODE HERE
raise NotImplementedError()
# YOUR CODE HERE
raise NotImplementedError()
How to declare functions#
Functions are the next construct necessary for the a good program design. A function should be defined by using the keyword def
.
def my_function() :
print ("I am the function")
my_function() # this calls the function
# this shows how to pass arguments
def my_function(x):
print (f"Value of argument is {x}")
#my_function() # error, requires argument
my_function(-3)
my_function(0.9)
# this shows how to pass arguments, and assign default values
def my_function(x = 0):
print (f"Value of argument is {x}")
my_function() # no longer an error
my_function(-3)
# this shows how to pass arguments, assign default values, and also calls by named arguments
def my_function(x = 0, y = 1):
print ("Calling my_function")
print ("x " + str(x))
print ("y " + str(y))
my_function() # no longer an error
my_function(-3, 2) # x = -3, y = -2
my_function(y=-3, x=2) # x = 2, y = -3
Exercises#
Convert from Farenheit to Celcius#
Write a function that receives a temperature in F and prints it in C
def FtoC(f):
# YOUR CODE HERE
raise NotImplementedError()
assert FtoC(0) == "The temperature 0 F is equivalent to -17.78 C"
assert FtoC(10.3) == "The temperature 10.3 F is equivalent to -12.06 C"
Triangle vertexes#
The coordinates for the vertexes of a given triangle are written into a file in the form \begin{align*}x_1\ \ \ y_1\x_2\ \ \ y_2\x_3\ \ \ y_3 \end{align*} Write a program that reads this values, and computes the area of the triangle, defined as $\( A = \frac{1}{2}[x_2y_3 - x_3y_2 - x_1y_3 + x_3y_1 + x_1y_2 - x_2y_1]\)$. Use functions.
RC circuit#
Write a Python program that uses a loop to simulate the behavior of an RC circuit. The program should ask the user for the resistance and capacitance values of the circuit and should calculate the voltage across the capacitor as a function of time. The program should then create a plot of the voltage across the capacitor versus time.
Spring system#
Write a Python program that uses a loop to simulate the motion of a mass-spring system. The program should ask the user for the mass of the object, the spring constant, and the initial displacement from equilibrium. The program should then calculate the position of the object as a function of time and create a plot of the position versus time.
Projectile#
Write a Python program that uses a loop to simulate the motion of a projectile under the influence of gravity. The program should ask the user for the initial velocity and launch angle of the projectile, and should calculate the trajectory of the projectile over time. The program should then create a plot of the trajectory of the projectile. Use the Euler integration algorithm to compute the next position and velocity. Compare adding a damping linear force with air.
Random numbers#
Write a Python program that reads three integers N, lower, upper, and generates a list of N random integers between lower and upper, inclusive. The program should then print out the number of integers in the list that are even and the number of integers that are odd. Finally, the program should create a bar chart that shows the number of even and odd integers in the list. Then create 4 plots with increasing N showing that limit distribution of even and odd numbers.
Heatmap#
Write a Python function that takes an integer n as input and returns a NumPy array of size n x n, where the elements of the array are random integers between lower and upper, which are also arguments of the function. Write a second function that takes the NumPy array as input and creates a heatmap of the array. Use these functions to create a program that generates a mxm NumPy array of random integers and displays it as a heatmap. Use several m
Fitting with scipy#
Here we will learn how to perform a non-linear fit. To do so, we will generate some random data and then fit it. First, create a function that represents the theoretical trend that you want to fit. Now create two numpy arrays, xdata and ydata. For xdata use the linspace function on the range you are interested in. For ydata use the theoretical function and add a gaussian noise for each point. Now use the scipy.curve_fit function to fit the data, and print the fit parameters and their errors. Plot both the data and the fit.