Python 2
Python 2
Simple Programs
I am beginning this book with a question. I am sure you will agree that a child
learns to speak first and then learn the grammar. So following this natural way
of learning I will introduce you to programs first and then explain what it is all
about.
Once you open the Python Interpreter you should see something like this: t To begin programming,
open a terminal by pressing
ap@ap:~\$ python3 crt + alt + t this will open
Python 3.6.9 (default, Apr 18 2020, 01:56:04) the terminal in Ubuntu
[GCC 8.4.0] on Linux
Type "help", "copyright", "credits" or "license" for more t Next type python3 and
information. press enter to open Python
>>> Interpreter
The Python prompt (>>>) is the place where you will type you commands for the
time being.
>>>print("Hello world") t Go ahead and try it. You
can print almost anything
Hello world
by putting them within the
inverted commas.
This is a simple command that will print the matter within the inverted commas.
You must be careful so that there is no spaces between the >>>and your command.
If you want to print Hello and world on two different lines then you can simply
insert \n between the two words. t \n stands for new line
9
Draft copy of PYTHON: for physics students ©Akhileshwar Prasad [Link]@[Link] Chapter 2 Simple Programs
2.2 Arithmetic
Let us try to perform some simple mathematical operations. Say we have two
numbers and we want to add, subtract, divide and multiply them. Well it cannot
get any simpler:
t You can use Python as a >>>2+5
simple calculator.
7
>>>2-5
t If you already know C or -3
C++ then don’t worry 2/5 >>>2/5
will be 0.4. Python takes
0.4
care of it.
>>>2*5
10
Till now we have dealt with numbers directly as we did in junior classes but you
certainly grew up and learnt algebra. Similar to algebra, we can assign a name to
the quantity of interest. Let us go back to the example in section 2.2
t Note that there is no output >>>a=2
for the assignment a=2, b=5
>>>b=5
and c=a+b. You can use
print statement to see the >>>a+b
output. ex. print(c) 7
>>>c= a+b
>>>
• Variable names are case sensitive. (Area, area, areA, ArEa are all different
variables)
Apart from these three rules there is one more restriction. There are 33 names
that cannot be used as variables and theses are known as keywords. To get the list
simply use the command help ("keywords").
>>>help ("keywords") t While it may be good to re-
member the keywords don’t
worry if you cannot. Note
Here is a list of the Python keywords. Enter any keyword to that there are no numbers
get more help. in the keywords. so if you
doubt whether area is a key-
False def if raise word or not just use area1
None del import return or area2.
True elif in try
and else is while
as except lambda with
assert finally nonlocal yield
break for not
class from or
continue global pass
>>>
t Still not sure whether veloc- You can use any variable name that you want but life will be easier if you variable
ity is a key word? well use
names clearly indicate what they represent. So aaa may be a valid variable name
velocity1.
but velocity is a better variable name to represent velocity.
L After getting a basic famil- There are many types of variables but as a physics students we are mainly in-
iarity with programming it trusted in three (integer, float and complex).
is strongly recommended
to read the section on data
type. Integer
t There is a built-in function As the name indicates, integer variables can take only integer values. Both positive
called type() which tells us and negative values are allowed. In Python 3, there is effectively no limit to how
the type of variable we are long an integer value can be. It is only constrained by the amount of memory the
dealing with. ex. type(2) computer has.
gives us <class ’int’>. (don’t
worry about the term class >>>a=3
in <class ’int’>. >>>type(a)
<class 'int'>
>>>a = 123456789012345678901234567890
>>>type(a)
<class 'int'>
>>>print(a*a)
15241578753238836750495351562536198787501905199875019052100
>>>
Float
t People have died because
someone failed to under- After reading the chapter data type in section Computer architecture and organi-
stand Float sation you will fully appreciate float. Hoverer, in a layman’s terms we can say a
float or a floating-point number,it is a number that has a decimal place. Floats are
used when we need a decimal number. Float may be written in scientific notation
using ’e’ or ’E’.
>>>b=3.4
>>>type(b)
<class 'float'>
>>>type(1.2e-14)
<class 'float'>
>>>
A little more detail: According to the IEEE 754 standard, almost all platforms t Don’t worry if you don’t un-
derstand in first go. Come
represent Python float values as 64-bit “double-precision” values. In that case, the
back to it later.
maximum value a floating-point number can have is approximately 1.8 × 10308 .
Python will indicate a number greater than that by the string inf: The magnitude
of the smallest non-zero number is approximately 5.0 × 10−324 . Anything smaller
than that is effectively zero: Floats are represented internally as fractions in binary
system. Hence, with finite number of digits, most of the decimal fractions cannot
be represented exactly as a binary fraction. The difference between the two is very
small for normal cases but special care needs to be taken for scientific computing.
I once again strongly recommend to get a proper understanding of floating point
representation before starting serious programming.
Complex
p
Python has an unbuilt complex data type. The number −1 which is written as
i in mathematics is represented as j in Python. Thus, 3+4j is a complex number
where 3 is the real part and 4 is the imaginary part.
>>>a=2+3j
>>>b=3+4j
>>>a+b
(5+7j)
>>>type(a)
<class 'complex'>
>>>
String
A sequence of characters is a string. In Python anything enclosed between the t Did I say three types of
variables?
single quote or double quote is a string. characters enclosed by three single or
double quote is also a string. ex """as123""" or ”’as123”’ are strings.
>>>a="abcd" t what will be the output of
the following:
>>>type(a)
<class 'str'> >>>a=’1234’
>>>b='abcd' >>>type(a)
>>>type(b)
<class 'str'>
Python has a very rich features to handle string and a separate discussion on
strings have been included in appendix.
Cannot we make life simpler by using only one type of variable? After all float and
integer seems to be a sub set of complex. We can, but it would take double the
memory space and computation speed will be almost half as compared to real. We
will come across cases where an integer say 1 is represented as 0.9999999999999.
This can lead to problems. So it is always advisable to keep an eye on the variable
type.
However the good news is that Python is dynamically typed. That means Python
doesn’t know about the type of the variable until the code is run. At while running
it assigns the proper type of variable. This is different from say C where you have
to declare the type of the variable before using it.
It may seem to make life easy as Python will take care but this feature drastically
reduces the computation speed. Also, if proper care is not taken you may end up
getting unexpected results.
If needed we can convert a variable from one type to another.
>>>a="2.3" #note the quotes makes "2.3" a string
>>>type(a)
<class 'str'>
>>>b = float(a) #we are converting string float
>>>type(b)
<class 'float'>
>>>c=int(a)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ValueError: invalid literal for int() with base 10: '2.3'
As you can see the attempt to convert string to int failed. If the string was not a
valid float within quotes say ‘2.3a’ then the float('2.3a') will also fail.
...... #continuing from previous code
>>>c=int(b)
>>>type(c)
<class 'int'>
>>>c
2
>>>
If you convert float to int the decimal part will be dropped. NOTE: it will not be
rounded. the decimal part simply vanishes.
Note
As you can see after some lines of code I have written some comments
in plain English starting with an #. The # symbol is used to add comment.
These comments are ignored by Python while running. However, it is very
important that you develop the habit of writing comments to explain your
codes so that you will save time later when you are trying to edit or reuse
the code.
Our first program in section 2.1 only printed some string on the screen. Now let
us solve some simple physics problems.
Say we want to calculate the area of a rectangle. We know area = length × breadth.
Read the following program line by line and with what we have discussed till now
you should be able to understand it fully.
>>>length=10 # assign the value 10 to variable length t Note the space in line one
and two. The only place
>>>breadth = 22.5 # assign the value 22.5 to variable breadth
where space matters is
>>>area = length*breadth # multiply length, breadth and assign immediately after >>>.
the value to a variable area
>>>print(area) #print the value of area on screen
225.0
That was nice. However,what is the use of the program if we have change it every t If you could not under-
stand the above code then
time the size of your rectangle changes? We need some command to get input
I strongly recommend that
from the user. The command is input. To underspent it lets use it first. you go back to Chapter ??
>>>length = input("please enter the length ") and read carefully.
please enter the length
If you type the first line and press enter key you will see the second line and
Python will wait till you enter something.
please enter the length 20
>>>type(length)
<class 'str'>
As you can see I have entered 20 and pressed the enter key. Everything was OK
but the type of length is string. In Python everything that you enter is stored as
string. If you need an integer or float then you can easily convert as discussed
earlier.
>>>length = float(input("please enter the length ")) #
converting the entered value to
float
please enter the length 12
>>>type(length)
<class 'float'>
In this example we used print command in a new way. Till now we had been
using print as print("string") or print(number) but in this case note how
multiple strings and numbers separated by commas have been printed using a
single print command. print("string1", number1, number2, "string2")
2.6 Grow up
Now that you have successfully written and executed your first functional pro-
grams we need to discuss a few things. We have been working at the Python
prompt in the terminal. This is a convenient way for very small tasks but no one
uses it anything more than a few lines. We have a few alternatives. The simplest
one is to write the codes in a text files and then execute them from the command
prompt.
t in Ubuntu press con-
trol+alternate+t key to- There are other options of using one of the various Integrated Development
gether. This will open the Environments (IDE) like spyder, pycharm or jupyter notebook. These have been
terminal. Now you can use covered in the Appendix. However, no matter what IDE you use Python will be
gedit (which is a text editor) the same. So for the time being you can learn the hard way and use text editor
by simply using the com- to type your programs and run them from the terminal. Once you have gained
mand ‘gedit &’ to type your sufficient fluency you can switch to an IDE.
program and save it with .py
extension.
Now that we have learnt how to get an input from the user and perform basic
calculations we can begin to write some simple codes to solve problems. We will
learn about new commands and features by working examples.
4. calculate acceleration.
output:
ap@ap:~/home/codes$ python3 [Link]
Please enter the force 12.4
Please enter the mass 24.7
Given
force = 12.400000
mass = 24.700000
After reading the code properly you should have noticed a few new things in
the print statement. Apart from the new line \n escape sequence a new escape
sequence \t and %f formatting statement have been used.
Escape Sequence
String formatting
%s String
%d Integers
%f Floating point numbers
%.<number of digits>f Floating point numbers with a fixed amount
of digits to the right of the dot.
%x/%X Integers in hex representation (lowercase/up-
percase)
Going back to our program in on acceleration ?? did you find any error?
What if we entered the value of mass as negative? In scientific programs you write
for yourself it is expected you will not make such mistakes but let us see how we
can avoid these if we want.
File name: [Link]
force = float(input("Please enter the force "))
mass = float(input("Please enter the mass "))
while mass<0:
mass = float(input("Please enter the positive mass "))
accleration = force/mass
print("Given \n\tforce = %f\n\tmass = %f\n"%(force, mass))
print("the accleration is %f"%accleration)
output:
ap@ap:~/home/codes$ python3 [Link]
Please enter the force 12
Please enter the mass -3
Please enter the positive mass 34
Given
force = 12.000000
mass = 34.000000
ap@ap:~/home/codes$
Here we see a new command while. Due to which the program will keep asking
for the mass till a positive value is entered. Did you notice the indention, that is a
blank space before mass in line 4. In Python this indention has a very important
meaning.
while loop
If you compare this with our program you see our condition was mass <
0, which is a comparison. All the statement that are to be inside the loop
must be indented equally (normally 4 whitespace is included before the
statement)
L Apart from comparison
more can be done in condi-
tion. Have patience....
Indenting Code
In program [Link], instead of asking for the mass till a positive value
was entered we could simply check if the value is negative and informs the user
about the same. Let us take a look at the following program.
File name:[Link]
force = float(input("Please enter the force "))
mass = float(input("Please enter the mass "))
if mass>0:
accleration = force/mass
print("Given \n\tforce = %f\n\tmass = %f\n"%(force, mass))
print("the accleration is %f"%accleration)
else:
print("Mass cannot be negative ")
output:
ap@ap:~/home/codes$ python3 [Link]
Please enter the force 12
Please enter the mass -4
Mass cannot be negative
ap@ap:~/home/codes$
How often do we hear these words in our day to day life. If you do this I will
do that else .... Well, in python its no different. Let us see the syntax
if condition:
statemen1 (executed if condition is true)
stetement2 (executed if condition is true)
.......... (executed if condition is true)
else:
statement3 (executed if condition false true)
statement4 (executed if condition false true)
........ (executed if condition false true)
statement (executed irrespective of the if else condition)
The if statement checks if the condition is true. If true it executes all the
statement that are indented. The else statement is optional and if needed
we can use only if. The else cannot be used alone. If the if statement is
followed by else statement then the indented statements after else are
executed only if the condition is false.
Going back to our program [Link]. What will you do if you have to
ensure that both force and mass is positive. Y you may use two if statements but
there are better ways. Study the code below.
File name: [Link]
force = float(input("Please enter the force "))
else:
print("Mass or force cannot be negative ")
Did you notice the condition in line 3. We have used a logical operator and to club
together two conditions. Multiple comparison can be clubbed together using
logical operators. The other logical operators are given in the table 2.4
Till now in all our programs we have used only “greater than” conditions. Other
comparison operators are given below in the table 2.5.
B Note: For comparing if
equal we are using == Table 2.5 Comparison Operators
which is different from =
which is for assignment. No. Operator Name Example
if x==5: compares if x is 1 == Equal x == y
equal to 5. if x=5: assigns 2 != Not equal x != y
the value 5 to x and will
3 > Greater than x>y
always be true.
4 < Less than x<y
5 >= Greater than or equal to x <= y
6 <= Less than or equal to x >= y
In Gregorian calendar, every fourth year has an additional day to keep it in syn-
chronized with the solar year.
To test a leap year we can use the algorithm below.
Algorithm:
output:
ap@ap:~/home/codes$ python3 leap_year.py
Please enter the year to be checked:1800
The year 1800 is not a leap year
ap@ap:~/home/codes$
One new thing that you should have noticed is how we are using if with else.
we are not writing else if we are writing elif.
elif
elif is a short for else if. In program leap_year.py if the condition (year
% 4 != 0 ) in line 2 is satisfied only line 4 will be executed. If however the t By using elif we can speed
up our code by skipping
condition in line 2 it is not satisfied then goes to the elif on line 4. If this
some condition checking
conation is also not satisfied then the next elif is [Link] all conditions but use it with care as un-
fails then the else block (if present) is executed. planned use may lead to cer-
tain conditions never being
tested. ADD AN EXERCISE
Does the code in leap_year.py look complicated. we can condense the code and TO SHOW THIS
write the same program as follows
File name: leap_year2.py
If you have made it till here then you certainly are hungry for more. Hoverer, have
patience. Solve the exercises below on your own and run them on any device you
have. It dosen’t matter even it is a smart phone. Once completed we meet in the
next chapter.
2.9 Exercises
a number of exercises