Introduction to Python
Program development, Variables, Expressions and Statements, Functions, Conditionals
and Recursion, Iteration, Strings, Lists, Dictionaries, Tuples, Files, Types of errors and
Debugging, Function Libraries, Numpy, Scipy, Matplotlib, Use of Scilab and R for
scientific programming
Dr. Santosh Prasad Gupta
Assistant Professor
Department of Physics
Patna University, Patna
12/5/2021 Department of Physics, PU: SP Gupta 1
Low and high level languages:
low-level languages, sometimes referred to as machine languages or assembly
languages. Loosely speaking, computers can only execute programs written in
low-level languages.
Low languages can convert to machine code without a compiler or interpreter.
second-generation programming languages use a simpler processor called
an assembler. For example: assembly and machine code
On the other hand high-level language such as and other high-level languages
you might have heard of are C, C++, Perl, and Java, have to be processed before
they can run.
Programs written in a high-level language take less time to write, they are
shorter and easier to read, and they are more likely to be correct. Second,
high-level languages are portable, meaning that they can run on different kinds
of computers with few or no modifications. Low-level programs can run on
only one kind of computer and have to be rewritten to run on another. Due to
these advantages, almost all programs are written in high-level languages. Low-
level languages are used only for a few specialized applications.
12/5/2021 Department of Physics, PU: SP Gupta 2
Two kinds of programs process high-level languages into low-level languages:
interpreters and compilers. An interpreter reads a high-level program and
executes it, meaning that it does what the program says. It processes the
program a little at a time, alternately reading lines and performing
computations.
A compiler reads the program and translates it completely before the program
starts running. In this case, the high-level program is called the source code,
and the translated program is called the object code or the executable. Once a
program is compiled, you can execute it repeatedly without further translation
Python is considered an interpreted language because Python programs
are executed by an interpreter.
12/5/2021 Department of Physics, PU: SP Gupta 3
History of Python:
Created in 1989 by Guido van Rossum and created as a scripting language for
administrative tasks Python is based on All Basic Code (ABC) and Modula-3.
Named after comic troupe Monty Python
Released publicly in 1991, and has growing community of Python developers
and evolved into well-supported programming language
Program :
Program is a sequence of instructions that specifies how to perform a
computation. The computation might be something mathematical, such as
solving a system of equations or finding the roots of a polynomial, but it can
also be a symbolic computation, such as searching and replacing text in a
document or (strangely enough) compiling a program.
Debugging :
Programming is a complex process, and because it is done by human beings, it
often leads to errors. For whimsical reasons, programming errors are called
bugs and the process of tracking them down and correcting them is called
debugging
12/5/2021 Department of Physics, PU: SP Gupta 4
Errors in a program:
Three kinds of errors can occur in a program: syntax errors, runtime errors, and
semantic errors. It is useful to distinguish between them in order to track them
down more quickly.
Errors in a program:
Three kinds of errors can occur in a program: syntax errors, runtime errors, and
semantic errors. It is useful to distinguish between them in order to track them
down more quickly.
VARIABLES, EXPRESSION AND STATEMENTS
Values and types:
A value is one of the fundamental things like a letter or a number that a
program manipulates. There are three different types of values; integer, float
and string.
Integer is integer type such as 1, 2, 3, 100, and numbers with a decimal point
belong to a type called float such as 10.7, 11.90, etc and strings are those which
are enclosed in quotation(double or single) marks such as “how are you”,
“hey”, “17”, „c‟.
12/5/2021 Department of Physics, PU: SP Gupta 5
Use type to know the details about the value type >>> type('Hello, World!')
<class 'str'>
>>> type(17)
<class 'int'>
>>> type(3.2)
<class 'float'>
What about values like '17' and '3.2'? They look like numbers, but they are in
quotation marks like strings. >>> type('17')
<type 'str'>
>>> type('3.2')
<type 'str'>
>>> print(1,000,000)
100
>>> print(10,000,00)
10 0 0
Python interprets 1,000,000 and 10,000,00 as a comma-separated list of three
integers, which it prints consecutively. This is the first example we have seen of a
semantic error: the code runs without producing an error message, but it doesn't do
the "right" thing
12/5/2021 Department of Physics, PU: SP Gupta 6
Variable
One of the most powerful features of a programming language is the ability to
manipulate variables. A variable is a name that refers to a value. The
assignment statement creates new variables and gives them values:
>>> message = („What are you doing?‟)
>>> n = 17
>>> pi =3.14159
This example makes three assignments. The first assigns the string „What are you
doing?‟ to a new variable named message. The second gives the integer 17 to n, and
the third gives the floating-point number 3.14159 to pi.
Notice that the first statement uses double quotes to enclose the string. In general,
single and double quotes do the same thing, but if the string contains a single quote or
an apostrophe, which is the same character, then you have to use double quotes to
enclose it.
>>> print (message)
What are you doing?
The print statement also works with variables.
>>> print (n)
17
>>> print (pi)
3.14159
12/5/2021 Department of Physics, PU: SP Gupta 7
Variable names and keywords
Programmers generally choose names for their variables that are meaningful they
document what the variable is used for. Variable names can be arbitrarily long.
They can contain both letters and numbers, but they have to begin with a letter.
Although it is legal to use uppercase letters, by convention we don't. If you do,
remember that case matters. Bruce and bruce are different variables. The
underscore character (_) can appear in a name. It is often used in names with
multiple words, such as my_name or price_of_tea_in_china.
>>> 76trombones = 'big parade'
SyntaxError: invalid syntax
>>> more$ = 1000000
SyntaxError: invalid syntax
>>> class = 'Computer Science 101'
SyntaxError: invalid syntax
76trombones is illegal because it does not begin with a letter. more$ is illegal
because it contains an illegal character, the dollar sign. But what's wrong with
class?
It turns out that class is one of the Python keywords. Keywords define the
language's rules and structure, and they cannot be used as variable names.
12/5/2021 Department of Physics, PU: SP Gupta 8
Python has twenty-nine keywords:
and def exec if not return assert del finally import or
try break elif for in pass while class else from is
print yield continue except global lambda raise
Statements
A statement is an instruction that the Python interpreter can execute.
We have seen two kinds of statements: print and assignment. When you type a
statement on the command line, Python executes it and displays the result, if
there is one.
The result of a print statement is a value. Assignment statements don't produce
a result. A script usually contains a sequence of statements. If there is more
than one statement, the results appear one at a time as the statements execute.
>>>print (1)
>>> 1
>>>x = 2
>>>print (x)
2
12/5/2021 Department of Physics, PU: SP Gupta 9
Evaluating expressions
An expression is a combination of values, variables, and operators. If you type an
expression on the command line, the interpreter evaluates it and displays the
result: >>> 1 + 1
2
Although expressions contain values, variables, and operators, not every
expression contains all of these elements. A value all by itself is considered an
expression, and so is a variable. >>> 17
17
Confusingly, evaluating an expression is not quite the same thing as printing a
value.
>>> message = ('Hello, World!')
>>> message
'Hello, World!'
>>> print (message)
Hello, World!
When the Python interpreter displays the value of an expression, it uses the
same format you would use to enter a value. In the case of strings, that means
that it includes the quotation marks. But if you use a print statement, Python
displays the contents of the string without the quotation marks.
12/5/2021 Department of Physics, PU: SP Gupta 10
Operators and operands
Operators are special symbols that represent computations like addition and
multiplication. The values the operator uses are called operands.
+, -, *, **, /, //, %
Order of operations
When more than one operator appears in an expression, the order of evaluation
depends on the rules of precedence. Python follows the same precedence rules for
its mathematical operators that mathematics does.
Parentheses have the highest precedence and can be used to force an expression
to evaluate in the order you want. Since expressions in parentheses are evaluated
first, 2 * (3-1) is 4, and (1+1)**(5-2) is 8.
Exponentiation has the next highest precedence, so 2**1+1 is 3 and not 4, and
3*1**3 is 3 and not 27.
Multiplication and Division have the same precedence, which is higher than
Addition and Subtraction, which also have the same precedence. So 2*3-1 yields
5 rather than 4, and 2//3-1 is -1, not 1.
Operators with the same precedence are evaluated from left to right. So in the
expression 59*100//60, the multiplication happens first, yielding 5900//60, which
in turn yields 98. If the operations had been evaluated from right to left, the result
would have been 59*1, which is 59, which is wrong.
12/5/2021 Department of Physics, PU: SP Gupta 11
Operations on strings
In general, you cannot perform mathematical operations on strings, even if the
strings look like numbers. The following are illegal, assuming that message has type
string:
message-1, 'Hello'/123. message*'Hello' , '15'+2
Interestingly, the + operator does work with strings, although it does not do exactly
what you might expect. For strings, the + operator represents concatenation, which
means joining the two operands by linking them end-to-end. For example:
>>>fruit = 'banana'
>>>baked = ' nut bread'
>>>print (fruit + baked)
Banana nut bread
The output of this program is banana nut bread. The space before the word nut is
part of the string, and is necessary to produce the space between the concatenated
strings.
The * operator also works on strings; it performs repetition. For example, 'Fun'*3 is
'FunFunFun'. One of the operands has to be a string; the other has to be an integer
12/5/2021 Department of Physics, PU: SP Gupta 12
Comments
As programs get bigger and more complicated, they get more difficult to read.
Formal languages are dense, and it is often difficult to look at a piece of code and
figure out what it is doing, or why. For this reason, it is a good idea to add notes to
your programs to explain in natural language what the program is doing. These
notes are called comments, and they are marked with the # symbol:
# computes the percentage of the hour that has elapsed
Percentage = (minute * 100) // 60
In this case, the comment appears on a line by itself. You can also put comments at
the end of a line:
Percentage = (minute * 100) / 60 # caution: integer division
12/5/2021 Department of Physics, PU: SP Gupta 13
Function
In the context of programming, a function is a named sequence of statements that
performs a desired operation. This operation is specified in a function definition.
Examples of inbuilt functions
>>> type ("32")
<class 'str'>
>>> id(3) # id is identifier
8791345055456
>>> betty = 3
>>> id (betty)
8791345055456
Type conversion
Python provides a collection of built-in functions that convert values from one type
to another. The int function takes any value and converts it to an integer, if
possible, or complains otherwise:
>>> int("32")
32
>>> int("Hello")
ValueError: invalid literal for int(): Hello
12/5/2021 Department of Physics, PU: SP Gupta 14
int can also convert floating-point values to integers, but remember that it truncates
the fractional part:
>>> int(3.99999)
3
>>> int(-2.3)
-2
The float function converts integers and strings to floating-point numbers:
>>> float(32)
32.0
>>> float("3.14159")
3.14159
Finally, the str function converts to type string:
>>> str(32)
'32'
>>> str(3.14149)
'3.14149'
12/5/2021 Department of Physics, PU: SP Gupta 15
Math Functions
Python has a math module that provides most of the familiar mathematical
functions. A module is a file that contains a collection of related functions
grouped together.
>>> import math import math
>>> math.log10(21) print(math.log10(21))
1.3222192947339193 1.3222192947339193
Adding new functions
Creating new functions to solve your particular problems is one of the most useful
things about a general-purpose programming [Link] syntax:
def NAME( LIST OF PARAMETERS ):
STATEMENTS
def twonewline(): This is first line
print()
print()
This is second line
print('This is first line')
twonewline()
print('This is second line')
twonewline()
twonewline() This is third line
print('This is third line')
12/5/2021 Department of Physics, PU: SP Gupta 16
Parameters and arguments
Some of the built-in functions you have used require arguments, the values that
control how the function does its job. For example, if you want to find the sine of
a number, you have to indicate what the number is.
>>> printTwice(5)
def printTwice(s): 5 ........ 5
print (s,'........', s) >>> printTwice('Hi hello')
Hi hello ........ Hi hello
CONDITIONALS AND RECURSION
Boolean expressions
A Boolean expression is an expression that is either true or false. One way to write
a Boolean expression is to use the operator ==, which compares two values and
produces a Boolean value:
>>> 5 == 5
True
>>> 5 == 6
False
12/5/2021 Department of Physics, PU: SP Gupta 17
The == operator is one of the comparison operators; the others are:
x != y # x is not equal to y
x>y # x is greater than y
x<y # x is less than y
x >= y # x is greater than or equal to y
x <= y # x is less than or equal to y
Although these operations are probably familiar to you, the Python symbols are
different from the mathematical symbols. A common error is to use a single
equal sign (=) instead of a double equal sign (==). Remember that = is an
assignment operator and == is a comparison operator. Also, there is no such
thing as =< or =>.
Logical operators
There are three logical operators: and, or, and not. The semantics meaning of
these operators is similar to their meaning in English. For example, x > 0 and x <
10 is true only if x is greater than 0 and less than 10.
n%2 == 0 or n%3 == 0 is true if either of the conditions is true, that is, if the
number is divisible by 2 or 3.
12/5/2021 Department of Physics, PU: SP Gupta 18
Conditional execution
In order to write useful programs, we almost always need the ability to check
conditions and change the behavior of the program accordingly. Conditional
statements give us this ability. The simplest form is the if statement:
if (x > 0):
print ("x is positive")
The Boolean expression after the if statement is called the condition. If it is true,
then the indented statement gets executed. If not, nothing happens.
Like other compound statements, the if statement is made up of a header and a
block of statements:
HEADER:
FIRST STATEMENT
...
LAST STATEMENT
The header begins on a new line and ends with a colon (:). The indented
statements that follow are called a block. The first unintended statement marks
the end of the block. A statement block inside a compound statement is called
the body of the statement.
12/5/2021 Department of Physics, PU: SP Gupta 19
Alternative execution
A second form of the if statement is alternative execution, in which there are two
possibilities and the condition determines which one gets executed. The syntax
looks like this: x=eval(input(„Enter the value of x:‟))
if x%2 == 0:
print (x, "is even")
else:
print (x, "is odd")
Chained conditionals
Sometimes there are more than two possibilities and we need more than two
branches. One way to express a computation like that is a chained conditional:
if x < y:
print (x, "is less than", y)
elif x > y:
print (x, "is greater than", y)
else:
print (x, "and", y, "are equal")
elif is an abbreviation of "else if." Again, exactly one branch will be executed. There
is no limit of the number of elif statements, but the last branch has to be an else
statement:
12/5/2021 Department of Physics, PU: SP Gupta 20
Nested conditionals
One conditional can also be nested within another. We could have written the
tracheotomy example as follows:
x=eval(input(„Enter the value of x:‟))
y=eval(input(„Enter the value of y:‟))
if x == y:
print (x, "and", y, "are equal")
else:
if x < y:
print (x, "is less than", y)
else:
print (x, "is greater than", y)
The outer conditional contains two branches. The first branch contains a simple output
statement. The second branch contains another if statement, which has two, branches of
its own.
12/5/2021 Department of Physics, PU: SP Gupta 21
12/5/2021 Department of Physics, PU: SP Gupta 22
12/5/2021 Department of Physics, PU: SP Gupta 23
12/5/2021 Department of Physics, PU: SP Gupta 24