Today we introduce the Python (think “Monty”, not the reptile) computing language. Python is an interpreted language. We shall see it is a powerful and generally user-friendly.
A useful link is www.python.org. Note that we will be using Python version 3.4 in this course. You may find this tutorial useful.
Remember we created a hello.py file in our last class. Copy it into your working directory.
You can run the lines inside the hello.py in python interactively.
Simply type python3. This command opens an interactive Python session with Python version 3.
Python 3.4.5 (default, Dec 11 2017, 16:57:19)
[GCC 4.4.7 20120313 (Red Hat 4.4.7-18)] on linux
Type "help", "copyright", "credits" or "license" for more information.
At the prompt, type print('Hello, world!').
To exit interactive mode, type CTRL-D or type quit() or exit() on the interpreter command line.
Of course, we're doing scientific computing so we're particularly interested in what we can do with numbers. You can start by using python interactively as a calculator. A few things to note.
1. The power of ten are input using e.
>>> 1e4 + 5e-3
2. The expression 23-4*3 is interpreted as 23-(4*3) not as (23-4)*3. Simply include parentheses ( ) if your aim is to calculate (23-4)*3.
Now try division. For example 1-7/3 .. How is this interpreted. Is it (1-7)/3 or 1-(7/3)? What about 6/2*3. Is it (6/2)*3 or 6/(2*3)?
3. What does the ** operator do?
>>> i = 5**4
>>> print ("the value of i is", i)
the value of i is 625
4. The % operator (modulus division): remainder of the division of left operand by the right.
Example: Lets say you have a pie with 10 slices and only 3 people. The pie is to be divided evenly across 3 people. How many slices left?
The day is divided into two 12 hours. Currently the time in 24 hour clock is 15:00 pm .. What is the time in 12 hour clock (for example 2:00 pm).
What about 18:00 pm? 23:00 pm ?
Comparison operator either return True or False. This will be particularly useful in while, conditional statements that we will learn in next class.
> Greater Than
< Less Than
!= Not Equal
>= Greater than or Equal to
<= Less than or Equal
start an emacs editor and create the file comp-ope.py to your directory. You will notice two variable x and y. Each is assigned a number. You will also notice print statements that include the comparison operators just mentioned. run you program.
Now try to add "Equal to" and "Not equal to" operators and print if that was true or false for this example. Change the values of the variables y and x and see how the results change?
Explore what the following operands do.
x += y
x -= y
x *= y
x /= y
Simply add one of these lines one at a time and print (x).
You can do this within the comp-ope.py file.
and (&) True if both operands are true
or (|) True if either operands are true
start an emacs editor and create the file log-ope.py to your directory and run it.
Assume that you are trying to convert from centigrade (Tc) to fahrenheit (Tf).
You know the formula is
Tf = (9/5)*Tc + 32
>>> Tc = 40
>>> Tf = (9/5)*Tc + 32
>>> print (Tf)
From a programming perspective it would be better to define a function that would calculate the temperature. At this point it is useful to do this in a python file. Create a file called convert.py containing the following lines:
#Convert from Centigrade to Fahrenheit
ratio = 9/5
constant = 32
Tf = ratio*Tc + constant
myTc = 40
mTf = convertF(myTc)
a - Now do the conversion for several centigrade temprature values (45, 62, -10).
b - You can write your program to require you to enter the values of temprature in C from the command line. This is done by adding the line
myTc =eval ( input("Enter Temp in C: "))
Now run your code, Type the value for example 45 and hit Enter. Does it work.. Test again for 62 and -10. Do you get what you expect?
"#" are very useful. They are used to comment out a line. In this example for comments or comment out a variable value.
Comments are very important in your programs. They are used to tell you what something does in English (you will be amazed how quickly you forget the details of your program).
Indentation is important in python. You will see several examples of it in python. In this particular example is the function convertF(). The lines in the function are a separate code block. The block of code in our example are indented four spaces (hit Tab), which is a typical amount of indentation for Python.
python function/method requires () even if there are no arguments, that is what distinguishes it as a function. Also why one has to type "quit()" rather than "quit" to exit interactive mode.
The variables "ratio" and "constant" are forgotten as soon as the function is finsihed. Try to print them out .. Notice that unlike (Tf) (which you access the value of with convertF(myTc) ), the variables (ratio and constant) are internal variables and you will get complains from python that the variable is not defined. Meaning python does not know the values of ratio and constant after the function has done its work.
In the previous example we converted from centigrade (Tc) to fahrenheit (Tf) for one value at a time. Suppose you would like to do the same for 40 values (i.e. 0,1,2,3,4 ... 40)
So in this example you probably can enter them one by one. Fortunately there is a more effective way of doing this by using a for-loop. A for-loop allows us to loop through a list of values for a given variable. The for loop in this example uses the range function range function
#Convert from centigrade to Fahrenheit
Tf = 9/5.0*Tc + 32.0
# The following are examples of for-loops.
# Generate 40 values from 0 to 40 with a step of 1
# range(first, last, step)
for i in range(0,41,1):
Tc = i
print (Tc, Tf)
Note the importance of indentation in the for-loop as well. Explore what the following range functions do range(4), range (10,20), range (-10,-50,-10).
Suppose you would like to use power and logarithmic functions, trigonometric functions, hyperbolic functions..
Many of these functions are available in the math module.
You can use all the math built in constants and functions by importing math at the begenning of your module either by typing:
>> import math as ma
and later on in your program calling ma.cos(0) for example.
>> from math import *
here we are importing all elements from the math module.
In this excercie figure out what the following functions in math do:
atan2(x,y), hypot(x,y), degrees(x), radians(x).
There are other very useful packages for scientfic computing like NumPy and SciPy to name a few.. We will get to explore the advantage of using in later labs.
Assignment due next Monday by noon
Write a python file that will calculate where x goes from 0 to 180 in steps of 10 degrees. Let your program print out all the values of x and sin(x) in degrees. Submit the code sin.py
Write a script that contains two functions. One that would convert cartesian to polar coordinates.
You would give it (x,y) and it will return (r,phi). The other will converts polar to cartesian coordinates this time you will feed it (r, phi) and it will return (x,y). test your code if it works. Submit a code called polcar.py .
what does the function fc do.
b = 1
for a in range(1,n+1):
submit your answer in a file called function.txt .
Problem 4 (BONUS).
Write a script that calculates the mass of a sphere given a radius r and mass density according to the formula
Assume to be 8.05 g/cm3.
Your script will define a function as shown in the lab exercises.
Use the script to find the mass of a sphere of radius r = 1 mm. Let your program require you to enter the value of r from the command line in units of mm. The output of your code should be the mass in g. Print out the mass including the unit. Submit code mass_sphere.py .
Back to main Physics 2235 page