Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
6 views

Python Unit 1

Uploaded by

Padma Saple
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
6 views

Python Unit 1

Uploaded by

Padma Saple
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 19

UNIT 1

Chapter 1
1.1 Introduction:

1. The Python Programming Language:


 Python is an example of a high-level language; other high-level languages you might
have heard of are C++, PHP, and Java.

 As you might infer from the name high-level language, there are also low-level
languages, sometimes referred to as machine languages or assembly languages.
Loosely speaking, computers can only execute programs written in low-level
languages. Thus, programs written in a high-level language have to be processed before
they can run. This extra processing takes some time, which is a small disadvantage of
high-level languages.

 But the advantages are enormous.

• First, it is much easier to program in a high-level language.


• 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.
• 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.

 Two kinds of applications 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.

INTERPRETER
SOURCE OUTPUT
CODE

 A compiler reads the program and translates it into a low-level program, which can
then be run.
 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.

SOURCE COMPILER OBJECT EXECUTOR OUTPUT


CODE CODE
There are two ways to use the Python interpreter: shell mode and script mode.

1) In shell mode, you type Python statements into the Python shell and the
interpreter immediately prints the result.
2) In this course, we will be using an IDE (Integrated Development and learning
Environment) called IDLE. When you first start IDLE it will open an
interpreter window.

One has to write when one observers >>>, which is the Python prompt. The
interpreter uses the prompt to indicate that it is ready for instructions.
If we type print 1 + 1 the interpreter will reply 2 and give us another prompt.
>>> print 1 + 1
output
2
Alternatively, you can write a program in a file and use the interpreter to execute the
contents of the file. Such a file is called a script.

Interactive/shell
mode

Script mode

By convention, files that contain Python programs have names that end with .py.
To execute the program run the program

History of Python:
 Python was developed by Guido van Rossum in the late eighties and early nineties
at the National Research Institute for Mathematics and Computer Science in the
Netherlands.
 Python is derived from many other languages, including ABC, Modula-3, C, C++,
Algol-68, SmallTalk, and Unix shell and other scripting languages.
 Python is copyrighted. Like Perl, Python source code is now available under the
GNU General Public License (GPL).
 Python is now maintained by a core development team at the institute, although
Guido van Rossum still holds a vital role in directing its progress.

 FEATURES OF PYTHON
 Easy-to-learn: Python has few keywords, simple structure, and a clearly defined syntax. This
allows a student to pick up the language quickly.
 Easy-to-read: Python code is more clearly defined and visible to the eyes.
 Easy-to-maintain: Python's source code is fairly easy-to-maintain.
 A broad standard library: Python's bulk of the library is very portable and cross platform
compatible on UNIX, Windows, and Macintosh.
 Interactive Mode: Python has support for an interactive mode, which allows interactive
testing and debugging of snippets of code
 Portable: Python can run on a wide variety of hardware platforms and has the same interface
on all platforms.
 Extendable: You can add low-level modules to the Python interpreter. These modules enable
programmers to add to or customize their tools to be more efficient.
 GUI Programming: Python supports GUI applications that can be created and ported
 Scalable: Python provides a better structure and support for large programs than shell
scripting.

Installing python
Windows platform
 Binaries of latest version of Python 3 (Python 3.5.1) are available on download page The
following different installation options are available.
 Windows x86-64 embeddable zip file
 Windows x86-64 executable installer
 Windows x86-64 web-based installer
 Windows x86 embeddable zip file
 Windows x86 executable installer
 Windows x86 web-based installer

 Note:In order to install Python 3.5.1, minimum OS requirements are Windows 7 with SP1. For
versions 3.0 to 3.4.x, Windows XP is acceptable.

Python Official Website : http://www.python.org/


You can download Python documentation from the following site. The documentation is
available in HTML, PDF and PostScript formats.

Debugging:

Programming is a complex process, and because it is done by human beings, programs


often contain errors. For whimsical reasons, programming errors are called bugs and the
process of tracking them down and correcting them is called debugging.
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.
Syntax errors
Python can only execute a program if the program is syntactically correct; otherwise,
the process fails and returns an error message. Syntax refers to the structure of a
program and the rules about that structure. For example, in English, a sentence must
begin with a capital letter and end with a period. this sentence contains a syntax error.

Eg if you declare a variable name as :


My val =10
It will show error which comes under syntax error as it should be myval .
Similarly
Myval =”hello ‘ is also syntax error

Runtime errors
The second type of error is a runtime error, so called because the error does not
appear until you run the program. These errors are also called exceptions because
they usually indicate that something exceptional (and bad) has happened. Runtime
errors are rare in the simple programs you will see in the first few chapters, so it
might be a while before you encounter one.

Eg
myval=10
a=my val + 10;

error as my val doesn’t exist

Semantic errors
The third type of error is the semantic error. If there is a semantic error in your program, it will run
successfully, in the sense that the computer will not generate any error messages, but it will not do the right
thing. It will do something else. Specifically, it will do what you told it to do

Formal and Natural Languages:


Natural languages are the languages that people speak, such as English, Spanish, and French. They were not
designed by people (although people try to impose some order on them); they evolved naturally.
Formal languages are languages that are designed by people for specific applications. For example, the notation
that mathematicians use is a formal language that is particularly good at denoting relationships among numbers
and symbols. Chemists use a formal language
Formal languages tend to have strict rules about syntax. For example, 3+3=6 is a syntactically correct
mathematical statement, but 3=+6$ is not. H2O is a syntactically correct chemical name, but 2Zz is not.

Disadvantages of natural languages :


Ambiguity: Natural languages are full of ambiguity, which people deal with by using contextual clues and
other information. Formal languages are designed to be nearly or completely unambiguous, which means that
any statement has exactly one meaning, regardless of context.
Redundancy: In order to make up for ambiguity and reduce misunderstandings, natural languages employ
lots of redundancy. As a result, they are often verbose. Formal languages are less redundant and more
concise.
Literalness: Natural languages are full of idiom and metaphor. If someone says, “The penny dropped”, there
is probably no penny and nothing dropped. Formal languages mean exactly what they say.
The Difference Between Brackets, Braces, and Parentheses: (MORE ON IT IN COMING UNITS )
1) Brackets ie [] are used to index into an array.
It is used also to represent list . eg a[3] a is array of three elements
2) Parenthesis () : they are used for two purposes : to control the order of operations in an expression
, and to supply parameters to a constructor or method
Eg (2+4)*3 and abc(2,3,4)
3) Braces : braces are used to group statements together . eg
if a>b
{statement 1;
Statement 2;….
}
In coming units we will be using them as list , tuple and dictionary resp.
UNIT 1 Chapter 2

Variables and Expressions

Values and types :


A value is one of the fundamental things—like a letter or a number—that a program
manipulates. The values we have seen so far are 2 (the result when we added 1 + 1), and
“Hello, World!”. These values belong to different types: 2 is an integer, and “Hello, World!”
is a string. You (and the interpreter) can identify strings because they are enclosed in
quotation marks.
The print statement also works for integers.
>>>print(4)

Strings belong to the type str and integers belong to the type int. Less obviously, numbers
with a decimal point belong to a type called float, because these numbers are represented in
a format called floating-point.
>>> 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")
<class ’str’>

>>> type("3.2")
<class ‘str’> They’re strings. Strings in Python can be enclosed in either single quotes (’) or
double quotes (”):

>>> type(’This is a string.’)


<class ’str’>
VARIABLES :
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 assigns them values:

>>> message = "What’s your name?"


>>> n = 17
>>> pi = 3.14159

This example makes three assignments. The first assigns the string "What’s your name?" to
a new variable named message. The second assigns the
integer 17 to n, and the third assigns the floating-point number 3.14159 to pi. The
assignment operator,
=, should not be confused with an equals sign (even though it uses the same character).
Assignment operators link a name, on the left hand side of the operator, with a value, on the

6
right hand side. This is why you will get an error if you enter:
>>> 17 = n

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.
The rules for naming the variables in Python are
 Variable names must start with a letter or an underscore eg
o _sname
o Sname_
 The remainder of your variable name may consist of letters , numbers and underscores
o Yy123
o V2y
o Yz_g
 Names are case sensitive
o Sname, SNAME , SnaME are different variables

KEYWORDS : these are predefined , reserved words used in programming that have special
meaning .

and del from not while


as elif global or with
assert else if pass yield
break except import print
class exec in raise
continue finally is return
def for lambda try

STATEMENTS :
A statement is a unit of code that the python interpreter can execute .
Eg :
>>>print(1)
1
>>>x=2
>>>print(x)
2
ASSIGNMENT STATEMENTS
A assignment statement creates a new variable and gives it a value
>>>myval=”hello”
>>>y=4
This example makes assignment :
Myval assigns hello , y assigns value 4

7
Python datatypes :

The data stored in memory can be of many types. For example, a person's age is stored
as a numeric value and his or her address is stored as alphanumeric characters. Python
has various standard data types that are used to define the operations possible on them
and the storage method for each of them.
Python has five standard data types-
 Numbers
 String (unit 2)
 List (unit 3)
 Tuple (unit 3)
 Dictionary (unit 3)

Python Numbers
Number data types store numeric values. Number objects are created when you assign a
value to them. For example
var1= 1
var2 = 10

Python supports three different numerical types −


 int (signed integers)
 float (floating point real values)
 complex (complex numbers)

Note : Remaining types we will see as per the unit

Type Conversion
Sometimes it's necessary to perform conversions between the built-in types. To convert
between types you simply use the type name as a function. In addition, several built-in
functions are supplied to perform special kinds of conversions. All of these functions return a
new object representing the converted value.
Function Converting what to what Example
>>> int('2014') 2014
int() string, floating point → integer >>> int(3.141592) 3
>>> float('1.99') 1.99
float() string, integer → floating point >>> float(5) 5.0
number
>>> str(3.141592) '3.141592'
str() integer, float, list, tuple, dictionary >>> str([1,2,3,4]) '[1, 2, 3, 4]'
→ string

8
OPERATORS AND OPERANDS

Operators are special symbols that represent computations like addition and multiplication.
The values the operator uses are called operands. The following are all legal Python
expressions whose meaning is more or less clear

20 + 32 hour - 1 hour * 60 + minute minute / 60


5 ** 2
(5 + 9) * (15 - 7)

The symbols +, -, *, /, have the usual mathematical meanings. The symbol, **, is the exponentiation
operator. The statement, 5 ** 2, means 5 to the power of 2, or 5 squared in this case. Python also uses
parentheses for grouping, so we can force operations to be done in a certain order just like we can in
mathematics.
When a variable name appears in the place of an operand, it is replaced with its value before the
operation is performed. Addition, subtraction, multiplication, and exponentiation all do what you
expect, but you might be surprised by division. The following operation has an unexpected result:

>>> minute = 59
>>> minute / 60
0 .9833333333333333

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
>>>a=b+c+10
Types of Operator

Python language supports the following types of operators.

1. Arithmetic Operators
2. Comparison (Relational) Operators
3. Assignment Operators
4. Logical Operators
5. Bitwise Operators
6. Membership Operators
7. Identity Operators
Let us have a look on all operators one by one.

1) Arithmetic Operators : These operators are used for doing calculations


Operator Description Example
+ Addition Adds values on either side of the operator. a + b = 30
- Subtraction Subtracts right hand operand from left hand operand. a – b = -10

9
* Multiplies values on either side of the operator a * b = 200
Multiplication
/ Division Divides left hand operand by right hand operand b/a=2
% Modulus Divides left hand operand by right hand operand and b%a=0
returns remainder
** Exponent Performs exponential (power) calculation on operators a**b =10 to the
power 20
// Floor Division - The division of operands where the 9//2 = 4 and
result is the quotient in which the digits after the 9.0//2.0 = 4.0, -
decimal point are removed. But if one of the operands 11//3 = -4, -
is negative, the result is floored, i.e., rounded away 11.0//3 = -4.0
from zero (towards negative infinity):
2) Python Comparison Operators : These operators compare the values on either sides of them
and decide the relation among them. They are also called Relational operators.

Assume variable a holds 10 and variable b holds 20, then −


Operator Description Example
== If the values of two operands are equal, then the condition becomes (a == b) is not
true. true.
!= If values of two operands are not equal, then condition becomes true.
> If the value of left operand is greater than the value of right operand, (a > b) is not
then condition becomes true. true.
< If the value of left operand is less than the value of right operand, (a < b) is true.
then condition becomes true.
>= If the value of left operand is greater than or equal to the value of (a >= b) is not
right operand, then condition becomes true. true.
<= If the value of left operand is less than or equal to the value of right (a <= b) is
operand, then condition becomes true. true.

3) Python Assignment Operators : Assume variable a holds 10 and variable b holds 20, then
Operator Description Example
= Assigns values from right side operands to left side c = a + b assigns
operand value of a + b
into c
+= Add It adds right operand to the left operand and assign the c += a is
result to left operand equivalent to c =
c+a
-= Subtract It subtracts right operand from the left operand and c -= a is
assign the result to left operand equivalent to c =
c-a
*= Multiply It multiplies right operand with the left operand and c *= a is
assign the result to left operand equivalent to c =
c*a
/= Divide It divides left operand with the right operand and c /= a is
assign the result to left operand equivalent to c =
c / ac /= a is
equivalent to c =
c/a
%= Modulus It takes modulus using two operands and assign the c %= a is
result to left operand equivalent to c =
c%a
10
**= Exponent Performs exponential (power) calculation on c **= a is
operators and assign value to the left operand equivalent to c =
c ** a
//= Floor It performs floor division on operators and assign c //= a is
Division value to the left operand equivalent to c =
c // a
4) Python Bitwise Operators
Bitwise operator works on bits and performs bit by bit operation. Assume if a = 60; and b =
13; Now in binary format they will be as follows −

a = 0011 1100
b = 0000 1101
-----------------
a&b = 0000 1100
a|b = 0011 1101
a^b = 0011 0001
~a = 1100 0011
There are following Bitwise operators supported by Python language

Operator Description Example


& Binary AND Operator copies a bit to the result if (a & b) (means 0000
it exists in both operands 1100)
| Binary OR It copies a bit if it exists in either (a | b) = 61 (means 0011
operand. 1101)
^ Binary XOR It copies the bit if it is set in one (a ^ b) = 49 (means
operand but not both. 0011 0001)
~ Binary Ones It is unary and has the effect of (~a ) = -61 (means 1100
Complement 'flipping' bits. 0011 in 2's complement
form due to a signed
binary number.
<< Binary Left Shift The left operands value is moved left a << = 240 (means 1111
by the number of bits specified by 0000)
the right operand.
>> Binary Right Shift The left operands value is moved a >> = 15 (means 0000
right by the number of bits specified 1111)
by the right operand.
5) Python Logical Operators
There are following logical operators supported by Python language. Assume variable a holds
10 and variable b holds 20 then :

Operator Description Example


and Logical If both the operands are true then condition becomes (a and b) is true.
AND true.
or Logical OR If any of the two operands are non-zero then condition (a or b) is true.
becomes true.
not Logical Used to reverse the logical state of its operand. Not(a and b) is
NOT false.
6) Python Membership Operators :Python’s membership operators test for membership in a
sequence, such as strings, lists, or tuples. There are two membership operators as explained
below

11
Operator Description Example
in Evaluates to true if it finds a variable in the x in y, here in results in a 1 if
specified sequence and false otherwise. x is a member of sequence y.
not in Evaluates to true if it does not finds a variable x not in y, here not in results
in the specified sequence and false otherwise. in a 1 if x is not a member of
sequence y.
7) Python Identity Operators :Identity operators compare the memory locations of two objects.
There are two Identity operators explained below:
Operator Description Example
is Evaluates to true if the variables on either side of the x is y, here is results in
operator point to the same object and false otherwise. 1 if id(x) equals id(y).
is not Evaluates to false if the variables on either side of the x is not y, here is
operator point to the same object and true otherwise. not results in 1 if id(x)
is not equal to id(y).

Python Operators Precedence : The following table lists all operators from highest precedence
to lowest.
Operator Description
** Exponentiation (raise to the power)
~+- Complement, unary plus and minus (method names for the last
two are +@ and -@)
* / % // Multiply, divide, modulo and floor division
+- Addition and subtraction
>> << Right and left bitwise shift
& Bitwise 'AND'
^| Bitwise exclusive `OR' and regular `OR'
<= < > >= Comparison operators
<> == != Equality operators
= %= /= //= -= += *= Assignment operators
**=
is is not Identity operators
in not in Membership operators
not or and Logical operators

Interactive mode and script mode


One of the benefits of working with an interpreted language is that you can test bits of code in
interactive mode before you put them in a script. But there are differences between interactive
mode and script mode that can be confusing.
For example, if you are using Python as a calculator, you might type
>>> miles = 26.2
>>> miles * 1.61
42.182

The first line assigns a value to miles, but it has no visible effect. The second line is an
expression, so the interpreter evaluates it and displays the result. So we learn that a marathon
is about 42 kilometers.

12
But if you type the same code into a script and run it, you get no output at all. In script mode
an expression, all by itself, has no visible effect. Python actually evaluates the expression, but
it doesn’t display the value unless you tell it to:
miles = 26.2 print miles * 1.61

Script mode:
In script mode, however, Python doesn't automatically display results.you save your file with
py extension and then execute it.

In order to see output from a Python script, we'll introduce the print statement. This statement
takes a list of values and prints their string representation on the standard output file. The
standard output is typically directed to the Terminal window. We'll revisit this in depth
in The printStatement.

print "PI = ", 355.0/113.0

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. The acronym PEMDAS is a useful way to remember the order of
operations:

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. You can also use parentheses to make an expression easier to read, as in
(minute*100)/60, even though it doesn’t change the result.
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 (remember that in integer division, 2/3=0).

Comments
Comments are nothing but self=-descibing text that helps programmer to get the information
about the code block
Single line comment :The hash-mark # symbol:
Eg
# compute the percentage of the hour that has elapsed
percentage = (minute * 100) / 60
v = 5 # assign 5 to v

13
This comment contains useful information that is not in the code:
v = 5 # velocity in meters/second.

Multiline comments : the three double quotes eg “””

“””
A
B
C
“””
UNIT 1 Chapter 3 : Conditional ,looping and control statements
1) if statement:
The IF statement is similar to that of other languages. The if statement contains a logical
expression using which the data is compared and a decision is made based on the result of the
comparison.

Syntax
if expression:
statement(s)

If the boolean expression evaluates to TRUE, then the block of statement(s) inside the if
statement is executed. In Python, statements in a block are uniformly indented after the :
symbol. If boolean expression evaluates to FALSE, then the first set of code after the end of
block is executed.

Eg
n=15
print(n)
if (n>0):
print("Positive number")

output
15
Positive number

2. if else Statements
An else statement can be combined with an if statement. An else statement contains a
block of code that executes if the conditional expression in the if statement resolves to 0 or
a FALSE value.
The else statement is an optional statement and there could be at the most only one else
14
statement following if.

Syntax
The syntax of the if...else statement is-
if expression:
statement(s)
else:
statement(s)

eg :
num = 3
if num >= 0:
print("Positive or Zero")
else:
print("Negative number")

output : Positive or zero

3. Nested IF -ELSE Statements


There may be a situation when you want to check for another condition after a
condition resolves to true. In such a situation, you can use the nested if construct.
In a nested if construct, you can have an if...elif...else construct inside another if...elif...else
construct.

Syntax
The syntax of the nested if...elif...else construct may if expression1:
if expression 1
statement(s)

elif expression2:
statement(s)
else:

statement(s)

eg
s=4
t=4
print("s=",s,"t=",t)
15
if (s>t) :
print("s is greater than t")
elif (t>s) :
print("t is greater")
else :
print("s and t are equal")

output :
s= 4 t= 4
s and t are equal

Looping statements:

For loop :

The for loop in Python is used to iterate over a sequence (list, tuple, string) or other iterable
objects. Iterating over a sequence is called traversal.

Syntax of for Loop

for val in sequence:


statement(S)

Here, val is the variable that takes the value of the item inside the sequence on each
iteration.

Eg

n=[1,2,3,4]
for i in n:
print(i)

Output
1
2
3
4

The range() function :


The range() function is used to generat a sequence of numbers.
Eg range(5) means 5 numbers from 0 to 4 .
We can also define start ,stop and step size as range(start , stop ,step size)
By default the step size is 1

Eg

for i in range(5):

16
print(i)

output
0
1
2
3
4

Eg 2:
for i in range(2,10,2):
print(i)

Output
2
4
6
8

While Loop

The while loop in Python is used to iterate over a block of code as long as the test
expression (condition) is true.

We generally use this loop when we don't know beforehand, the number of times to iterate.

Syntax of while Loop in Python

while test_expression:

Statement(s)

Eg
i=1
while(i<=5):
print(i)
i=i+1

Output
1
2
3
4
5

Control statements:
Terminating loops:
The break statement terminates the loop containing it. Control of the program flows to the
17
statement immediately after the body of the loop.
If break statement is inside a nested loop (loop inside another loop), break will
terminate the innermost loop.

Syntax :
break

eg
for val in "string":
if val == "i":
break
print(val)
print("The end")
output
s
t
r
the end
Skipping specific conditions
The continue statement is used to skip the rest of the code inside a loop for the current
iteration only. Loop does not terminate but continues on with the next iteration.

Syntax
continue

eg

for i in range(4):
if(i==2):
continue
print(i)

output

0
1
3

Pass statement
It is used when a statement is required syntactically but you do not want any command or
code to execute . the pass statement is null operation , nothing happens when it executes ,

18
for letter in 'Python':
if letter == 'h':
pass
print ('This is pass block')
print ('Current Letter :', letter)

print ("Good bye!")

This will produce following result:


Current Letter : P
Current Letter : y
Current Letter : t
This is pass block
Current Letter : h
Current Letter : o
Current Letter : n
Good bye

19

You might also like