Python Basics
Instructions
- This page focuses on getting started with Python and performing basic calculations.
- The concept video includes instructions for installing and getting started with Python. Note this video may be slightly out-of-date. The video mentions this calclab page with the instructions for installing the software.
- For each video, you can see the problem being solved, as well as the Python code used.
- You can also open the link to the Python Notebook file. You can click File>Download to download the notebook file to run on your own computer.
- Each video has a link to the full video page. These pages include links to related videos covering the same topics.
Learning Objectives
- Installing Python
- Using symbols and functions in Python
- Solving equations numerically
- Plotting functions
Concept Video(s)
Exercises
1.
Python Code:
from sympy import *
#Find area of triangle with side lengths 100, 150, and 200 cm
a=100
b=150
c=200
s=(a+b+c)/2
# Area = square root of s(s-a)(s-b)(s-c)
Area=sqrt(s*(s-a)*(s-b)*(s-c))
print('The area of the triangle is', Area, 'square centimeters')
Open Python Notebook File
2.
Python Code: from sympy import * #Evaluate ln(5)*e^1.4 (ln(5)*exp(1.4)).evalf() Open Python Notebook File
3.
Python Code:
from sympy import *
x=symbols('x')
f=x**4+5*x**3+8*x**2+x-15
print(f.factor())
f_factor=f.factor()
print(f_factor.expand())
g=f/(x**2-1)
print(g.simplify())
print(g.subs(x,1))
print(g.simplify().subs(x,1))
Open Python Notebook File
4.
Python Code:
from sympy import *
theta=symbols('theta')
LHS=50*tan(theta)-13.61/(cos(theta))**2
thsol=solve(LHS,theta)
angle1=re(thsol[2])
angle2=re(thsol[3])
print(angle1*180/pi.evalf(),angle2*180/pi.evalf())
Open Python Notebook File
5.
Python Code:
from sympy import *
matplotlib notebook
theta=symbols('theta')
LHS=50*tan(theta)-13.61/(cos(theta))**2
plot(LHS,(theta,0,1.5),ylim=[-20,20])
angle1=nsolve(LHS,theta,0.3)
angle2=nsolve(LHS,theta,1.3)
print('The angle needed is',angle1*180/pi.evalf(),'or',angle2*180/pi.evalf(),'degrees')
Open Python Notebook File
from sympy import *
matplotlib notebook
theta=symbols('theta')
LHS=50*tan(theta)-13.61/(cos(theta))**2
plot(LHS,(theta,0,1.5),ylim=[-20,20])
angle1=nsolve(LHS,theta,0.3)
angle2=nsolve(LHS,theta,1.3)
print('The angle needed is',angle1*180/pi.evalf(),'or',angle2*180/pi.evalf(),'degrees')
Open Python Notebook File
6.
Python Code:
from sympy import *
matplotlib notebook
x=symbols('x')
f1=2*x+6
f2=x**2
plotf=plot((f1,(x,-5,-2)),(f2,(x,-2,3)),show=False)
plotf[1].line_color='red'
plotf.show()
Open Python Notebook File
from sympy import *
matplotlib notebook
x=symbols('x')
f1=2*x+6
f2=x**2
plotf=plot((f1,(x,-5,-2)),(f2,(x,-2,3)),show=False)
plotf[1].line_color='red'
plotf.show()
Open Python Notebook File
