Module 1 Pip Note
Module 1 Pip Note
1
Features and Applications:
1. Easy to learn:- It has few keywords, simple structure and clearly defined
syntax.
2. Easy to read:- It is clearly defined.
3. Easy to maintain:- It is fairly easy to maintain.
4. Portable:- It can run wide variety of hardware platforms and has the same
interface on all platforms.
5. Databases:- It provides interfaces to all major commercial databases.
6. Extendable:- Adding of low level modules to python is possible.
7. Scalable:- It provides a better structure and support for larger programs.
8. It supports functional and structured programming.
9. It can be used as scripting language and can be compiled to byte code to form
largerapplications.
11. It can be easily integrated with other programming languages like c,c++, java
• You can download Python, its documentation, and related materials from
[Link].
• Python does not come preinstalled on Windows systems.
• Therefore, you must download the Windows installer from
[Link] The installer might then run
automatically, or you might have to double click an icon for the installer to
2
launch it. The installer automatically puts Python into a folder and inserts
various command options on the All Programs menu.
• Python that comes preinstalled on Mac OS X, Unix and Linux but the user
might need to update the version of Python.
3
• A shell window contains an opening message followed by the special symbol
>>>, called a shell prompt. The cursor at the shell prompt waits for you to
enter a Python command.
• When you enter an expression or statement, Python evaluates it and displays
its result, if there is one, followed by a new prompt. To quit the Python shell,
you can either select the window’s close box or press the Control+D key
combination.
• Most useful programs accept inputs from some source, process these inputs,
and then finally output results to some destination. In terminal-based
interactive programs, the input source is the keyboard, and the output
destination is the terminal display.
Print Function
• The programmer can also force the output of a value by using the print
function. The basic syntax (or grammatical rule) for using the print function:
print(<expression>)
• When running the print function, Python first evaluates the expression and
then displays its value.
1. print was used to display some text. In Python code, a string is
always enclosed in quotation marks. However, the print function
displays a string without the quotation marks.
4
Eg: print("Hi there")
2. You can also write a print function that includes two or more
expressions separated by commas. In such a case, the print function
evaluates the expressions and displays their results, separated by
single spaces, on one line.
Input Function
• As you create programs in Python, you’ll often want your programs to ask the
user for input. You can do this by using the input function. This function
causes the program to stop and wait for the user to enter a value from the
keyboard.
• When the user presses the return or enter key, the function accepts the input
value and makes it available to the program.
• The form of an assignment statement with the input function is the following:
5
<variable identifier>=input(<a string prompt>)
• A variable identifier, or variable for short, is just a name for a value. When
a variable receives its value in an input statement, the variable then refers to
this value.
Type conversion
• The input function always builds a string from the user’s keystrokes and
returns it to the program. After inputting strings that represent numbers, the
programmer must convert them from strings to the appropriate numeric types.
• In Python, there are two type conversion functions for this purpose, called
int (for integers) and float (for floating point numbers).
Example:
6
Editing, Saving and Running a Script
7
4. To run this file of code as a Python script, select Run Module from the
Run menu or press the F5 key (Windows) or the Control+F5 key (Mac
or Linux).
1. The interpreter reads a Python expression or statement, also called the source
code, and verifies that it is well formed. In this step, the interpreter behaves
like a strict English teacher who rejects any sentence that does not
8
adhere to the grammar rules, or syntax, of the language. As soon as the
interpreter encounters such an error, it halts translation with an error message.
2. If a Python expression is well formed, the interpreter then translates it to an
equivalent form in a low-level language called byte code. When the
interpreter runs a script, it completely translates it to byte code.
3. This byte code is next sent to another software component, called the Python
virtual machine (PVM), where it is executed. If another error occurs during
this step, execution also halts with an error message.
9
• The first statement assigns an input value to the variable length. The next
statement attempts to print the value of the variable lenth. Python responds
that this name is not defined.
• In this error message, Python explains that this line of code is unexpectedly
indented. In fact, there is an extra space before the word print.
• Indentation is significant in Python code. Each line of code entered at a shell
prompt or in a script must begin in the leftmost column, with no leading
spaces. The only exception to this rule occurs in control statements and
definitions, where nested statements must be indented one or more spaces.
10
1. Customer request—In this phase, the programmers receive a broad
statement of a problem .This step is also called the user requirements
phase.
2. Analysis—The programmers determine what the program will do. This is
sometimes viewed as a process of clarifying the specifications for the
problem.
3. Design—The programmers determine how the program will do its task.
4. Implementation—The programmers write the program. This step is also
called the coding phase.
5. Integration—Large programs have many parts. In the integration phase,
these parts are brought together into a smoothly functioning whole, usually
not an easy task.
6. Maintenance—Programs usually have a long life; a life span of 5 to 15
years is common for software. During this time, requirements change,
errors are detected, and minor or major modifications are made.
11
• The figure resembles a waterfall, in which the results of each phase flow down
to the next.
• However, a mistake detected in one phase often requires the developer to back
up and redo some of the work in the previous phase. Modifications made
during maintenance also require backing up to earlier phases. Taken together,
these phases are also called the software development life cycle.
• Modern software development is usually incremental and iterative. This
means that analysis and design may produce a rough draft, skeletal version,
or prototype of a system for coding, and then back up to earlier phases to fill
in more details after some testing.
• Keep in mind that mistakes found early are much less expensive to correct
than those found late. These are not just financial costs but also costs in time
and effort.
Data Types
• A data type consists of a set of values and a set of operations that can
be performed on those values.
• A literal is the way a value of a data type looks to a programmer. The
programmer can use a literal in a program to mention a data value.
12
String Literals
13
Escape Sequences
• Escape sequences are the way Python expresses special characters, such
as the tab, the newline, and the backspace (delete key), as literals.
String Concatenation
• We can join two or more strings to form a new string using the
concatenation operator +.
14
' Python'
Assignment Statements
• The Python interpreter first evaluates the expression on the right side
of the assignment symbol and then binds the variable name on the
left side to this value. When this happens to the variable name for
the first time, it is called defining or initializing the variable.
15
• The author of a program can include his or her name and a brief
statement about the program’s purpose at the beginning of the
program file. This type of comment, called a docstring.
"""
Program: [Link]
Author: Ken Lambert
Last date modified: 10/10/17
• Integers - the integers include 0, all of the positive whole numbers, and all
of the negative whole numbers.
16
• Floating - Point Numbers - A real number in mathematics, such as the value
of pi (3.1416…), consists of a whole number, a decimal point, and a fractional
part.
Character Sets
• All data and instructions in a program are translated to binary numbers before
being run on a real computer. To support this translation, the characters in a
string each map to an integer value. This mapping is defined in character
sets, among them the ASCII set and the Unicode set
• The term ASCII stands for American Standard Code for Information
Interchange. In the 1960s, the original ASCII set encoded each keyboard
character and several control characters using the integers from 0 through 127.
17
• The digits in the left column represent the leftmost digits of an ASCII code,
and the digits in the top row are the rightmost digits. Thus, the ASCII code of
the character 'R' at row 8, column 2 is 82.
• Python’s ord() and chr() functions convert characters to their numeric ASCII
codes and back again, respectively.
>>> ord('a')
97
>>> ord('A')
65
>>> chr(65)
'A'
>>> chr(66)
'B'
Expression
Arithmetic Expressions
18
Precedence rules
19
Mixed-Mode Arithmetic and Type Conversions
>>> 3.14 * 3 ** 2
28.26
• You must use a type conversion function when working with the input of
numbers.
• A type conversion function is a function with the same name as the data type
to which it converts. Because the input function returns a string as its value,
20
you must use the function int or float to convert the string to a number
before performing arithmetic, as in the following
Example:
>>> radius = input("Enter the radius: ")
Enter the radius: 3.2
>>> radius
'3.2'
>>> float(radius)
3.2
>>> float(radius) ** 2 * 3.14
32.153600000000004
21
Using Functions and Modules
abs(4-5) returns 1
Math Module
• The math module includes several functions that perform basic mathematical
operations.
• This list of function names includes some familiar trigonometric functions as
well as Python’s most exact estimates of the constants pi and e.
Ex: 'sin' , 'sinh' , 'sqrt' , 'tan' , 'tanh' , 'tau' , 'trunc'. .... etc.
22
Syntax for using specific function from math module
Ex:
>>>>import math
>>>>[Link]
3.1415926535897931
>>>>[Link](2)
1.4142135623730951
Ex:
from math import pi, sqrt
>>> print(pi, sqrt(2))
3.14159265359 1.41421356237
Ex:
• Start with an introductory comment stating the author’s name, the purpose of
the program, and other relevant information. This information should be in
the form of a docstring.
• Then, include statements that do the following:
23
o Import any modules needed by the program.
o Initialize important variables, suitably commented.
o Prompt the user for input data and save the input data in
variables.
o Process the inputs to produce the results.
o Display the results.
Control statements
Iteration Structure
24
• The first line of code in a loop is sometimes called the loop header.
• Integer expression in the header denotes the number of iterations that the
loop performs.
• The colon (:) ends the loop header.
• he loop body comprises the statements in the remaining lines of code, below
the header. Note that the statements in the loop body must be indented and
aligned in the same column. These statements are executed in sequence on
each pass through the loop.
• Example1:
25
• Example 3: When Python executes the type of for loop, it actually counts from
0 to the value of the header’s integer expression minus 1.
• Loops that count through a range of numbers are also called count controlled
loops. The value of the count on each pass is often used in computations.
Example 4: factorial of 4
26
• To count from an explicit lower bound, the programmer can supply a second
integer expression in the loop header. When two arguments are supplied to
range, the count ranges from the first argument to the second argument minus
1.
• The next code segment uses this variation to simplify the code in the loop
body:
27
• Some programs might want a loop to skip some numbers
• A variant of Python’s range function expects a third argument that allows
you to nicely skip some numbers. The third argument specifies a step value,
or the interval between the numbers used in the range, as shown in the
examples that follow:
• Example: compute the sum of the even numbers between 1 and 10.
• The loop fails to perform the expected number of iterations. Because this
number is typically off by one, the error is called an off-by-one error.
• For the most part, off-by-one errors result when the programmer incorrectly
specifies the upper bound of the loop.
• The programmer might intend the following loop to count from 1 through 4,
but it counts from 1 through 3:
28
Loops That Count Down
• All of our loops until now have counted up from a lower bound to an upper
bound. Once in a while, a problem calls for counting in the opposite direction,
from the upper bound down to the lower bound.
• Example:
• Clearly, something eventually has to happen within the body of the loop to
make the loop’s continuation condition become false. Otherwise, the loop will
continue forever, an error known as an infinite loop. At least one
29
statement in the body of the loop must update a variable that affects the
value of the condition.
• The while loop is also called an entry-control loop, because its condition is
tested at the top of the loop. This implies that the statements within the loop
can execute zero or more times.
theSum = 0.0
while True:
if data == "":
break
number = float(data)
30
theSum += number
• The first thing to note is that the loop’s entry condition is the Boolean value
True.
• Within this body, the input datum is received. It is then tested for the loop’s
termination condition in a one-way selection statement. If the user wants to
quit, the input will equal the empty string, and the break statement will cause
an exit from the loop.
• Otherwise, control continues beyond the selection statement to the next two
statements that process the input.
If-else Statements:
31
• The condition in the if-else statement must be a Boolean expression—that is,
an expression that evaluates to either true or false.
• The two possible actions each consist of a sequence of statements.
• Note that each sequence must be indented at least one space beyond the
symbols if and else.
• Lastly, note the use of the colon (:) following the condition and the word
else.
• A flow diagram of the semantics of the if-else statement is given below:
32
If statement:
• This type of control statement is also called a one-way selection statement,
because it consists of a condition and just a single sequence of statements.
• If the condition is True, the sequence of statements is run. Otherwise, control
proceeds to the next statement following the entire selection statement.
• Here is the syntax for the if statement:
Multi-Way if Statements:
33
• The syntax of the multi-way if statement is the following:
• Example:
Switch statements
34
Syntax of Switch Statement
switcher=
{
key_1: value_1/method_1(),
key_2: value_2/method_2(),
key_3: value_3/method_3(),
::
key_n: value_n/method_n(),
35
key = N
def get_week_day(argument):
switcher =
0: "Sunday" ,
1: "Monday" ,
2: "Tuesday" ,
3: "Wednesday" ,
4: "Thursday" ,
5: "Friday" ,
6: "Saturday"
}
return [Link](argument, "Invalid day")
print (get_week_day(6))
print (get_week_day(8))
print (get_week_day(0))
36
Augmented Assignment
• Examples:
a = 17
s = "hi"
a += 3 # Equivalent to a = a + 3
a -= 3 # Equivalent to a = a - 3
a *= 3 # Equivalent to a = a * 3
a /= 3 # Equivalent to a = a / 3
a %= 3 # Equivalent to a = a % 3
s += " there" # Equivalent to s = s + " there"
• The next session shows how to right-justify and left-justify the string four
within a field width of 6:
38
• The first line of code right-justifies the string by padding it with two spaces
to its left. The next line of code left-justifies by placing two spaces to the
string’s right.
• The simplest form of this operation is the following:
• This version contains a format string, the format operator %, and a single
data value to be formatted.
• The format string can contain string data and other information about the
format of the datum.
• To format the string data value in our example, we used the notation
%<field width>s in the format string.
• When the field width is positive, the datum is right-justified; when
the fieldwidth is negative, you get left-justification.
• If the field width is less than or equal to the datum’s print length in
characters, no justification is added.
• The % operator works with this information to build and return a
formatted string.
• To format integers, you use the letter d instead of s.
• To format a sequence of data values, you construct a format string that
includes a format code for each datum and place the data values in a tuple
following the % operator.
39
• Example:
• The format information for a data value of type float has the form:
Lazy evaluation
d=a+b*c
40
In Python, once these statements are evaluated, the calculation is immediately
(or strictly) carried out, setting the value of d to 30. In another programming
paradigm, such as in a pure functional programming language like Haskell, the
value of d might not be evaluated until it is actually used elsewhere. The idea of
deferring computations in this way is commonly known as lazy evaluation.
Python, on the other hand, is a very strict (or eager) language. Nearly all of the
time, computations and expressions are evaluated immediately. Even in the
above simple expression, the result of b * c is computed as a separate step before
adding it to a. There are Python techniques, especially using iterators and
generators, which can be used to achieve laziness. When performing very
expensive computations which are only necessary some of the time, this can be
an important technique in data- intensive applications.
Short-Circuit Evaluation
• The Python virtual machine sometimes knows the value of a Boolean
expression before it has evaluated all of its operands.
• For instance, in the expression A and B, if A is false, there is no need to
evaluate B. Likewise, in the expression A or B, if A is true, there is no need
to evaluate B.
• This approach, in which evaluation stops as soon as possible, is called short-
circuit evaluation.
41
else:
print("count = 0 or average <=10‖)
Operators
42
Comparison Operator
43
Logical Operators
Identity Operators
Membership Operators
44
Bitwise Operators
45