Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                

Unit 1 - Notes FINAL

Download as pdf or txt
Download as pdf or txt
You are on page 1of 19

Unit - 1

Basics of Python Programming: History of Python-Features of Python-Literal-Constants-


Variables - Identifiers–Keywords-Built-in Data Types- Output Statements –Input Statements-
Comments –Indentation- Operators-Expressions-Type conversions. Python Arrays: Defining and
Processing Arrays–Array methods.

History of Python.

Python was first developed by Guido van Rossum in the late 80‟s and early 90’s at the
National Research Institute for Mathematics and Computer Science in the Netherlands.
It has been derived from many languages such as ABC, Modula-3, C, C++, Algol- 68,
SmallTalk, UNIX shell and other scripting languages.
Since early 90’s Python has been improved tremendously. Its version 1.0 was released in
1991, which introduced several new functional programming tools.
While version 2.0included list comprehension was released in 2000 by the Be Open
Python Labs team.
Python 2.7 which is still used today will be supported till 2020.
Currently Python 3.6.4 is already available. The newer versions have better features like
flexible string representation e.t.c,
Although Python is copyrighted, its source code is available under GNU General Public
License (GPL) like that Perl.

Applications of Python:
Embedded scripting language: Python is used as an embedded scripting language for
various testing/ building/ deployment/ monitoring frameworks, scientific apps, and quick scripts.

3D Software: 3D software like Maya uses Python for automating small user tasks, or for
doing more complex integration such as talking to databases and asset management systems.

Web development: Python is an easily extensible language that provides good integration
with database and other web standards.

GUI-based desktop applications: Simple syntax, modular architecture, rich text processing
tools and the ability to work on multiple operating systems makes Python a preferred choice
for developing desktop-based applications.
Image processing and graphic design applications: Python is used to make 2D imaging
software such as Inkscape, GIMP, Paint Shop Pro and Scribus. It is also used to make 3D
animation packages, like Blender, 3ds Max, Cinema 4D, Houdini, Light wave and Maya.
Scientific and Computational applications: Features like high speed, productivity and
availability of tools, such as Scientific Python and Numeric Python, have made Python a
preferred language to perform computation and processing of scientific data. 3D modeling
software, such as FreeCAD, and finite element method software, like Abaqus, are coded in
Python.

Games: Python has various modules, libraries, and platforms that support development of
games. Games like Civilization-IV, Disney's Toontown Online, Vega Strike, etc. are coded using
Python.
Enterprise and Business applications: Simple and reliable syntax, modules and
libraries, extensibility, scalability together make Python a suitable coding language for
customizing larger applications. For example, Reddit which was originally written in
Common Lips, was rewritten in Python in 2005. A large part of Youtube code is also
written in Python.
Operating Systems: Python forms an integral part of Linux distributions.

Features of Python

 Simple: Reading a program written in Python feels almost like reading english. The main strength

of Python which allows programmer to concentrate on the solution to the problem rather than
language itself.

 Easy to Learn: Python program is clearly defined and easily readable. The structure of the
program is simple. It uses few keywords and clearly defined syntax.
 Versatile: Python supports development of wide range of applications such as simple text
processing, WWW browsers and games etc.
 Free and Open Source: It is a Open Source Software. So, anyone can freely distribute it, read
the source code, edit it, and even use the code to write new (free) programs.
 High-level Language: While writing programs in Python, the low-level details like managing
memory used by the program are not considered much.
 Interactive: Programs in Python work in interactive mode which allows interactive testing
and debugging of pieces of code. Programmer can easily interact with the interpreter directly
at the python prompt to write their programs.
 Portable: It is a portable language and hence the programs behave the same on wide variety of
hardware platforms with different operating systems.
 Object Oriented: Python supports object-oriented as well as procedure-oriented style of
programming .While object-oriented technique encapsulates data and functionality with in objects,
Procedure oriented at other hand, builds programs around procedure or functions.
 Interpreted: Python is processed at runtime by interpreter. So, there is no need to compile a
program before executing it. You can simply run the program. Basically python converts
source program into intermediate form called byte code.

 Dynamic and strongly typed language: Python is strongly typed as the interpreter keeps track
of all variables types. It's also very dynamic as it rarely uses what it knows to limit variable
usage.
 Extensible: Since Python is an open source software, anyone can add low-level modules to the
python interpreter. These modules enable programmers to add to or customize their tools to work
more efficiently.
Keyword
Keywords are the reserved words in Python. We cannot use a keyword as variable name,
function name or any other identifier.
Here's a list of all keywords in Python Programming.

KeywordsinPythonProgrammingLanguage
False class finally is return
None continue for lambda try
True def from nonlocal while
and del global not with
as elif if or yield
assert else import pass break
except in raise

There are 33 keywords in Python 3.3. This number can vary slightly in course of time.

All the keywords except True, False and None are in lowercase and they must be written
as it is.

Constants

 A constant is a special type of variable but its value cannot be modified or changed in the
course of the program execution.
 But variable value can be changed whenever required. But that is not possible for a
constant. Once defined, a constant cannot allow changing its value.
 For example, in Mathematics, „pi‟ value is 22/7 which never changes and hence it is a
constant.
 Constants are written in all capital letters. For example, MAX_VALUE is a constant. But
its value can be changed.
Variables

 Variable means its value can vary. It is used to store piece of information in a variable.
 Variables are nothing but just parts of your computer’s memory where information is stored.
 To identify a variable easily, each variable is given an appropriate name.
 In other words, variables are the container that holds a value under a specific name.
 Ex: a=20 here, a is variable name and holds the value as 20, its data type is number
(integer)

Identifiers

 Identifiers are names given to identify something.


 It can be a variable, function, class, module or other object.
 For naming any identifier, there are some basic rules such as:
The first character of an identifier must be an underscore ('_') or a letter (upper or

lowercase).
The rest of the identifier name can be underscores ('_'), letters (upper or lowercase), or digits
(0-9).
Identifier names are case-sensitive. For example, myvar and myVar are not the same.
Special characters such as @, $, and % are not allowed within identifiers.
Examples of valid identifier names are sum, my_var, num1, r, var_20, First, etc.
Examples of invalid identifier names are 1num, my-var, %check, Basic Sal, H#R&A

Data types

 The variables can hold values of different type called Data Type.
 Data type is a set of values and the allowable operations on those values.
 Python has a great set of useful data types. Python's data types are built in the core of the
language.
 Python has various standard data types to define the operations possible on them and storage
method for each of them.
 Python supports the following five standard data types
1.Numbers
2.Strings
3.Lists
4.Tuple
5.Dictionary
1. Numbers
In Python, numeric data type is used to hold numeric values.

Integers, floating-point numbers and complex numbers fall under Python numbers category. They
are defined as int, float and complex classes in Python.
int - holds signed integers of non-limited length.
float - holds floating decimal points and it's accurate up to 15 decimal places.
complex - holds complex numbers.
2. Strings

 The sequence of characters in the quotation marks can be used to describe the string.

 A string can be defined in Python using single (‘ ‘) , double (“ “), or triple quotes (‘ ‘ ‘ ‘ ‘ ‘).

 The operator + is used in the string to concatenate two strings

 The operator * is used to repeat the string values


Output
 Ex:
str1 = 'hello hai’ he
str2 = ' how are you' o
print (str1[0:2]) hello haihello hai
print (str1[4])
hello haihow are you
print (str1*2)
print (str1 + str2)

3. Lists

 Lists are the most versatile data type of Python language.


 A list consist of items separated by commas and enclosed within square brackets
 The values stored in a list are accessed using indexes.
 The values in the list can be changed at anytime throughout the program.
 The index of the first element being 0 and n-1 as thatof the last element, where n is the total
number of elements in the list.

 Example:
Output

78
list = ['a', 'bc', 78, 1.23]
list1 = ['d', 78]
print(list[2])
list[2]=12
print(list[2])
print(list)
print(list[0])
print(list[1:3])
print(list[2:])
print(list * 2)
print(list + list1)

4. Tuples

 Tuple is an ordered sequence of items same as a list. The only difference is that tuples are
immutable. Tuples once created cannot be modified.
 In Python, tuple is denoted using parentheses () to store items.
 Ex: Output
tup = ("hi", "Python", 2) ('hi', 'Python', 2)
print (tup) ('Python', 2)
('hi',)
print (tup[1:]) ('hi', 'Python', 2, 'hi', 'Python', 2)
print (tup[0:1]) ('hi', 'Python', 2, 'hi', 'Python', 2, 'hi', 'Python', 2)
print (tup + tup) Traceback (most recent call last):
File "main.py", line 14, in <module>
print (tup * 3) t[2] = "hi";
t[2] = "hi" TypeError: 'tuple' object does not support item
assignment

5. Dictionary

 Python’s dictionaries stores data in key-value pairs.


 The key values are usually strings and value can be of any data type. The key value pairs
are enclosed with curly braces { }.
 Each key value pair separated from the other using a colon (:).
 To access any value in the dictionary, specify its key in square braces [].
 Basically dictionaries are used for fast retrieval of data.
 Ex : d = {1:'John', 2:'Alex', 3:'jeni', 4:'meena'}
print (d) Output:
print("1st name is "+d[1]) {1: 'John', 2: 'Alex', 3: 'jeni', 4: 'meena'}
print("2nd name is "+ d[4]) 1st name is John
2nd name is meena
dict_keys([1, 2, 3, 4])
print (d.keys())
print (d.values())

Operators
Operators are special symbols in Python that carry out arithmetic or logical computation. The
value that the operator operates on is called the operand.
For example: >>> 2+3
5
Here, + is the operator that performs addition. 2 and 3 are the operands and 5 is the output of the
operation.

Python supports the following operators


1. Arithmetic operators
2. Assignment operators
3. Comparison (Relational) operators
4. Bitwise operators
5. Logical Operators
6. Membership Operators
7. Identity Operators
1. Arithmetic operators

 Arithmetic operators are used to perform mathematical


operations like addition, subtraction, multiplication etc.
 This operator will work on two operands.
 Example: If a=100 and b=200, the result of arithmetic operations.
2. Assignment operators

 Assignment operators are used in Python to assign values to variables.

 a = 5 is a simple assignment operator that assigns the value 5 on the right to the variable a on the left.

 There are various compound operators in Python like a += 5 that adds to the variable and later assigns
the same. It is equivalent to a = a + 5.

Operator Example Equivalentto


= x=5 x=5
+= x += 5 x=x+5
-= x -= 5 x=x-5
*= x *= 5 x=x*5
/= x /= 5 x=x/5
%= x %= 5 x=x%5
//= x //= 5 x = x // 5
**= x **= 5 x = x ** 5
&= x &= 5 x=x&5
|= x |= 5 x=x|5
^= x ^= 5 x=x^5

>>= x >>= 5 x = x >> 5

3. Comparison (Relational) operators

 A Relational or Comparison operator checks the relationship between two operands.

 If the relation is true, it returns 1; if the relation is false, it returns value 0

 For Example assuming a=100 and b=2000


4. Bitwise operators

 Bitwiseoperatorsperformoperationsatthebitlevel.
 These operators include bitwise AND, bitwise OR, bitwise XOR, and shift
operators.
 Bitwise operators expect their operands to be of integers and treat them as a
sequence of bits.
 The truth tables of these bitwise operators are given below.

Example: If a=60 and b=13 then the result of Bitwise operations are as follows.

Operator Description Example

& Operator copies a bit to the result if it (a & b) =12


Binary AND exists in both operands (means 0000 1100)
| (a | b) = 61
It copies a bit if it exists in either operand.
Binary OR (means 0011 1101)
^ It copies the bit if it is set in one operand (a ^ b) = 49
Binary XOR but not both. (means 0011 0001)
(~a ) = -61
~
(means 1100 0011 in
Binary Ones It is unary and has the effect of 'flipping'
2's complement form
Complement bits.
due to a signed binary
<< The left operands value is moved left by
a << 2 = 240
Binary Left the number of bits specified by the right
(means 1111 0000)
Shift operand.

>> The left operands value is moved right by


a >> 2 = 15
Binary Right the number of bits specified by the right
(means 0000 1111)
Shift operand.
5. Logical Operators

 Logical operators are used to simultaneously evaluate two conditions or expressions with
relational operators.
 Logical AND (and) If expressions on both the sides (left and right side) of the logical
operator are true, then the whole expression is true.
 For example, If we have an expression (a>b) and (b>c), then the whole expression is true
only if both expressions are true. That is, if b is greater than a and c.

 Logical OR (or) operator is used to simultaneously evaluate two conditions or expressions


with relational operators. If one or both the expressions of the logical operator is true, then
the whole expression is true.
 For example, If we have an expression (a>b) or (b>c), then the whole expression is true if
either b is greater than a or b is greater than c.
 Logical NOT (not) operator takes a single expression and negates the value of the
expression. Logical NOT produces a zero if the expression evaluates to a non-zero value and
produces a 1 if the expression produces a zero. In other words, it just reverses the value of the
expression.

 For example, a = 10; b = not a; Now, the value of b = 0.

6. Membership Operators

Python supports two types of membership operators–in and not in. These operators, test
for membership in a sequence such as strings, lists, or tuples.

 in Operator: The operator returns true if a variable is found in the specified sequence and
false otherwise. For example, a in nums returns 1, if a is a member of nums.
 not in Operator: The operator returns true if a variable is not found in the specified
sequence and false otherwise. For example, a not in nums returns 1, if a is not a member
of nums.

 Example :
a=1
b = 20 Output:
list = [1, 2, 3, 4, 5 ]; a is available in the given list
if ( a in list ): b is not available in the given list
print " a is available in the given list"
else:
print " a is not available in the given list"
if ( b not in list ):
print " b is not available in the given list"
else:
print " b is available in the given list"

7. Identity Operators

 is Operator: Returns true if operands or values on both sides of the operator point to the
same object and false otherwise. For example, if a is b returns 1, if id(a) is same as id(b).
 is not Operator: Returns true if operands or values on both sides of the operator does
not point to the same object and false otherwise. For example, if a is not b returns 1, if id(a)
is not same as id(b).

 Example:
a = 20
b = 20
if ( a is b ): Output:
print " a and b have same identity" a and b have same identity
else:
a and b have same identity
print " a and b do not have same identity"
if ( id(a) == id(b) ):
print " a and b have same identity"
else:
print "a and b do not have same identity"

Operator Precedence

Operators Meaning
() Parentheses
** Exponent
+x,-x,~x Unary plus, Unary minus, Bitwise NOT
Multiplication, Division, Floor
*,/, //, %
division, Modulus
+,- Addition, Subtraction
<<,>> Bitwise shift operators
& Bitwise AND
^ Bitwise XOR
| Bitwise OR
Comparison, Identity, Membership operators
==,!=,>,>=,<,<=,is, is not, in, not in

The operator precedence in Python are listed in the following table. It is in descending order,
upper group has higher precedence than the lower ones.

Input and Output Statements

 A program needs to interact with the user to accomplish the desired task; this can be
achieved using Input-Output functions.
 The input() function helps to enter data at run time by the user and the output
function print() is used to display the result of the program on the screen after
execution.

Output Statement:
 print() is used to display the result
 The Syntax of the print function is
print (“string to be displayed as output ” )
print (variable )
print (“String to be displayed as output ”, variable)
print (“String1 ”, variable, “String 2”, variable, “String 3” ……)

 Example
>>>print (“Welcome to Python Programming”) Welcome to Python Programming
>>>x = 5
>>>y = 6
>>>z = x + y
>>>print (z)
11
>>> print (“The sum = ”, z)
The sum = 11
>>> print (“The sum of ”, x, “ and ”, y, “ is ”, z)
The sum of 5 and 6 is 11
The print ( ) evaluates the expression before printing it on the monitor. The print () displays an entire
statement which is specified within print ( ). Comma ( , ) is used as a separator in print ( ) to print
more than one item.

Input Statement:

 input( ) function is used to accept data as input at run time.


 The syntax for input() function is,
Variable = input (“prompt string”)
 Where, prompt string in the syntax is a statement or message to the user, to know what input can
be given.
 If a prompt string is used, it is displayed on the monitor; the user can provide expected data from
the input device.
 The input( ) takes whatever is typed from the keyboard and stores the entered data in the given
variable.
 If prompt string is not given in input( ) no message is displayed on the screen, thus, the user will
not know what is to be typed as input.

Example 1:input( ) with prompt string


>>>city=input (“Enter Your City: ”)
Enter Your City:Madurai
>>>print (“I am from “, city)
I am from Madurai
Example 2:input( ) without prompt string
>>>city=input()
Ram
>>>print (I am from", city)
I am from Ram
Note that in example-2, the input( ) is not having any prompt string, thus the user will not know what
is to be typed as input. If the user inputs irrelevant data as given in the above example, then the output
will be unexpected. So, to make the program more interactive, provide prompt string with input( ).
 The input ( ) accepts all data as string or characters but not as numbers.
 If a numerical value is entered, the input values should be explicitly converted into numeric
data type.
 The int( ) function is used to convert string data as integer data explicitly.

Example 3:
x = int (input(“Enter Number 1: ”))
y = int (input(“Enter Number 2: ”))
print (“The sum = ”, x+y)
Output:
Enter Number 1: 34
Enter Number 2: 56
The sum = 90

Comments

 Comments are the non-executable statements in a program. They are just added
to describe the statements in the program code.
 Comments make the program easily readable and understand able by the
programmer as well as other users who are seeing the code. The interpreter
simply ignores the comments.
 In Python, a hash sign (#) is used to denote a comment. All characters following
the # and up to the end of the line are part of the comment
 Example :
Print(“Hello”) # to display hello
 For writing Multiline comments. Make sure to indent the leading „ „ „
appropriately to avoid an Indentation Error
 Example :
„„„
This is a multiline comment.
„„„

Indentation

 Whitespace at the beginning of the line is called indentation. These whitespaces


or the indentation are very important in Python.

 In a Python program, the leading whitespace including spaces and tabs at the
beginning of the logical line determines the indentation level of that logical line
 Example:

Type Conversion
 In Python, it is just not possible to complete certain operations that involve
different types of data.
 For example, it is not possible to perform "2"+4 since one operand is an integer
and the other is of string type.
>>>”20”+“30” >>>int(“2”)+int(“3”)

Output Output

2030 5

Another situation in which type conversion is must i s when accepting an on string value
(integer or float) as an input and their input function returns string, so typecast the input
to numbers to perform calculations on them.

Example:
x=int(input(“Enter the first number))

y=int(input(“Enter the second number))


print(x+y)

Output

Enter the first number 6

Enter the second number7

13

Arrays
 An array is a collection of items stored at contiguous memory locations. The idea is to store
multiple items of the same type together.
 Array in Python can be created by importing array module. array(data_type,value_list)
isused to create an array with datatype and value list specified in its arguments.
 Array Representation

 syntax for creating an array:

variable_name=array(typecode,[elements])
o variable_name would be the name of the array.
o The typecode specifies what kind of elements would be stored in the array. Whether it
would be an array of integers, an array of floats or an array of any other Python data type. all
elements should be of the same data type.
o Inside square brackets the elements that would be stored in the array is mentioned with each
element being separated by a comma. An empty array can be created as follows
writing variable_name = array(typecode) alone, without any elements.
o The following are the different typecodes that can be used with the different data types when
defining Python arrays:

TYPECODE C TYPE PYTHON TYPE SIZE

'b' signed char int 1


'B' unsigned char int 1
'u' wchar_t Unicode character 2
'h' signed short int 2
TYPECODE C TYPE PYTHON TYPE SIZE

'H' unsigned short int 2


'i' signed int int 2
'I' unsigned int int 2
'l' signed long int 4
'L' unsigned long int 4
'q' signed long long int 8
'Q' unsigned long long int 8
'f' float float 4
'd' double float 8
 Example :
output 10
import array as arr
20
numbers = arr.array('i',[10,20,30])
30
print(numbers)

o First the array module is included, in this case with import array as arr .

o Then, a numbers array is created.

o arr.array() is used, because of import array as arr .

o Inside the array() constructor, first I is included, for signed integer. Signed integer
means that the array can include positive and negative values. Unsigned integer, with H
for example, would mean that no negative values are allowed.

o At Last, the values to be stored in the array in square brackets is included.


 Basic Operations

Followingarethebasic operationssupportedbyanarray.
 Traverse − print all the array elements one by one.
 Insertion − Adds an element at the given index.
 Deletion − Deletes an element at the given index.
 Search − Searches an element using the given index or by the value.
 Update − Updates an element at the given index.

1) Traversing an Array
The elements of an array are accessed by indexing, slicing and looping.
Indexing Array

- Each item in an array has a specific address. Individual items are accessed by
referencing their index number.
- In general, Index starts at 0. The counting starts at 0 and not at 1.

- Syntax : array_name[index_value_of_item]

- Example :
import array as arr

numbers = arr.array('i',[10,20,30])

print(numbers[0])

print(numbers[1])

print(numbers[2])
- It is also possible to access each individual element using negative indexing.
- With negative indexing, the last element would have an index of -1, the second to last
element would have an index of -2, and so on.
- Example :
import array as arr
output 30
numbers = arr.array('i',[10,20,30])
20
print(numbers[-1]) 10
print(numbers[-2])
print(numbers[-3])

2) Insertion
 To add one single value at the end of an array, use the append() method is used
 Ex:
import array as arr
numbers = arr.array('i',[10,20,30])
output
numbers.append(40)
array('i', [10, 20, 30, 40])
print(numbers)

 The new item should be the same data type as the rest of the items in the array.

 To add more than one value to the end an array, extend() is used.

 Ex:
import array as arr
numbers = arr.array('i',[10,20,30])
numbers.extend([40,50,60]) Output
print(numbers) array('i', [10, 20, 30, 40, 50, 60])
 To add an item at a specific position, insert() is used.
 Ex:
import array as arr
numbers = arr.array('i',[10,20,30]) Output
numbers.insert(0,40)
print(numbers) array('i', [40, 10, 20, 30])
3) Deletion
 To remove an element from an array, use the remove() method and include the value as an argument
to the method.

 Ex:
import array as arr
Output
numbers = arr.array('i',[10,20,30])
array('i', [20, 30])
numbers.remove(10)
print(numbers)

 when there are more than one identical values, Only the first occurence is removed.

 To remove the specific position of the element to be removed, pop() is used.

 Ex:
import array as arr
Output
numbers = arr.array('i',[10,20,30,10,20])
array('i', [20, 30, 10, 20])
numbers.pop(0)
print(numbers)
4) Search
 Array elements can be changed based on its value or its index.
 Ex:
import array as arr
Output:
array1 =arr. array('i', [10,20,30,40,50]) 3
print (array1.index(40))
 If the value is not present in the array then the program returns an error.
5) Update
 Update operation refers to updating an existing element from the array at a given index.
 Ex:
import array as arr
Output:
array1 = arr.array('i', [10,20,30,40,50]) 10
20
array1[2] = 80
80
for x in array1: 40
50
print(x)

You might also like