Unit-1 (Introduction) (1)
Unit-1 (Introduction) (1)
INTRODUCTION
History- Features- Working with Python- Installing Python- basic syntax- Data types -variables- Manipulating
Numbers Text Manipulations Python Build in Functions
1. INTRODUCTION TO PYTHON:
Python
Python is a high level programming language like C, C++ designed to be easy to read,
and less time to write. It is an open source and it is an interpreter which directly executes the
program without creating any executable file. Python is portable which means python can run on
different platform with less or no modifications.
Python is interpreted: Python is processed at runtime by the interpreter. You do not need to
compile your program before executing it.
Python is Interactive: You can actually sit at a Python prompt and interact with the interpreter
directly to write your programs.
Python is Object-Oriented: Python supports Object-Oriented style or technique of programming
that encapsulates code within objects.
Python is a Beginner's Language: Python is a great language for the beginner-
Level programmers and supports the development of a wide range of applications.
Python Features:
Easy-to-learn: Python is clearly defined and easily readable. The structure of the program is very
simple. It uses few keywords.
Easy-to-maintain: Python's source code is fairly easy-to-maintain.
Portable: Python can run on a wide variety of hardware platforms and has the same interface on all
platforms.
Interpreted: Python is processed at runtime by the interpreter. So, there is no need to compile a
program before executing it. You can simply run the program.
Extensible: Programmers can embed python within their C,C++,JavaScript
, ActiveX, etc.
Free and Open Source: Anyone can freely distribute it, read the source code, and edit it.
High Level Language: When writing programs, programmers concentrate on solutions of the
current problem, no need to worry about the low level details.
Scalable: Python provides a better structure and support for large programs than shell scripting.
Applications:
Bit Torrent file sharing
Google search engine, YouTube
Intel, Cisco, HP,IBM
i Robot
NASA
1
Face book, Drop box
Python Interpreter
Python Interpreter translates high level instruction into an immediate form of
machine level language. It executes instructions directly without compiling.
The Python interpreter is usually installed in C:/Program Files/Python3.6. In windows operating python can also
be found in the start menu. All Programs Python 3.6 Python 3.6 (Shell) and Python IDLE.
Interactive mode is a command line which gives immediate feedback for each statement.
Python interactive mode can be start by two methods - Python 3.6 (Shell) and Python IDLE.
Python 3.6 (Shell), A prompt will appear and it usually have 3 greater than signs (>>>).
Each Statements can be enter
will represent the multiple lines.
Python IDLE (Integrated Development for Learning Environment) which provides a user
friendly console to the python users. Different colors are used to represent different
keywords.
IDLE starts by python version, after a line (>>>) three greater than symbols will be
displayed. The statements will be executed in that line.
Example:
>>> 1+1
2
>>>5+10
15
1.2.2 In Script mode
In script mode, type python program in a file and store the file with .py extension and use
the interpreter to execute the content of the file which is called a script.
Working in script mode is convenient for testing small piece of code because you can type
and execute them immediately, But for more than few line we can use script since we can
modify and execute in future.
2
Compiler Interpreter
Compiler Takes Entire program as input Interpreter Takes Single instruction as input
3
This is an example of a print statement. It displays a result on the screen. In this case, the result is the words.
Script mode:
In script mode, we type python program in a file and then use interpreter to execute the content of the
file.
Scripts can be saved to disk for future use. Python scripts have the
extension .py, meaning that the filename ends with.py
Save the code with filename.py and run the interpreter in script mode to execute the script.
save and edit the code Can save and edit the code
If we want to experiment with the code, If we are very clear about the code, we can
we can use interactive mode. use script mode.
we cannot save the statements for further use and we we can save the statements for further use and we no
have to retype all the statements to re-run them. need to retype all the statements to re-run them.
Value:
Value can be any letter, number or string.
Eg, Values are 2, 42.0, and 'Hello, World!'. (These values belong to different datatypes.)
Data type:
Every value in Python has a data type.
It is a set of values, and the allowable operations on those values.
Python has four standard data types:
1. Numbers:
Number data type stores Numerical Values.
This data type is immutable [i.e. values/items cannot be changed].
Python supports integers, floating point numbers and complex numbers. They are defined as,
1.1 Integer
Let Integer be positive values, negative values and zero.
Example:
5
>>>2+2
4
>>>a=-20
print() - 20
>>> type(a) <type
1.2 Float
A floating point value indicates number with decimal point.
Example:
>>> a=20.14
>>>type(a) <type
2. Boolean
A Boolean variable can take only two values which are True or False. True and False
are simply set of integer values of 1 and 0.The type of this object is bool.
Example:
>>>bool(1)
True
>>>bool(0)
False
>>>a=True
>>>type(a) <type
>>>b=false #Prints error
>>>type(c) <type
The boolean type is a subclass of the int class so that arithmetic using a boolean works.
>>>True + 1
2
>>>False * 85
0
# A Boolean variable should use Capital T in true & F in False and be enclosed within
the quotes.
>>>d=10>45 #Which returns False
Boolean Operators
Boolean Operations are performed by
Example:
6
True and True True
True and False False
True or True True
3. Sequence:
A sequence is an ordered collection of items, indexed by positive integers.
It is a combination of mutable (value can be changed) and immutable (values cannot be changed)
datatypes.
There are three types of sequence data type available in Python, they are
1. Strings
2. Lists
3. Tuples
3.1 Strings:
A String in Python consists of a series or sequence of characters - letters, numbers, and special
characters.
Strings are marked by quotes:
Single quotes(' ') E.g., 'This a string in single quotes'
double quotes(" ") E.g., "'This a string in double quotes'"
triple quotes(""" """)E.g., """This is a paragraph. It is made up of multiple
lines and sentences."""
Individual character in a string is accessed using a subscript(index).
Characters can be accessed using indexing and slicing operations .Strings are
Immutable i.e the contents of the string cannot be changed after it is created.
Example:
>>>type(a)
<type
Subsets of strings can be taken using the slice operator ([ ] and [:]) with indexes starting at 0 in
the beginning of the string and working their way from -1 at the end. The plus (+) sign is the
string concatenation operator and the asterisk (*) is the repetition operator.
Example:
>>>str = 'Python Programming'
>>>print(str) # Prints complete string
>>>print(str[0]) # Prints first character of the string
>>>print(str[-1]) # Prints last character of the string
>>>print(str[2:5]) # Prints characters starting from 3rd to 5th
>>>print(str[2:]) # Prints string starting from 3rd character
>>>print(str * 2) # Prints string two times
>>>print(str + " Course") # Prints concatenated string
Output
Python
7
Programming
P
g
tho
thon Programming
Python ProgrammingPython Programming
Python Programming Course
Indexing:
8
st
Slice operator is used >>>print(s[:4]) - Displaying items from 1
to extract part of a Good
position till 3rd.
data
type
String Functions:
For the following string functions the value of str1 and str2 are as follows:
9
10. It removes all the spaces at the
rstrip() rstrip() rstrip(a) it returns -1
end
11. \n \ New Line Character \
12. \t \ It provides Space \
13. I\
\ \ Escape Character ( / ) is used to
print single quote or double
14. I\
\ \ quote in a String
3.2 Lists
A list is an ordered set of values, where each value is identified by an index. The values that
make up a list are called its elements. A list contains items separated by commas and enclosed
within square brackets ([]). Lists are mutable which means the items in the list can be add or
removed later.
The values stored in a list can be accessed using the slice operator ([ ] and [:]) with indexes
starting at 0 in the beginning of the list and working their way to end -1. The plus (+) sign is the
list concatenation operator, and the asterisk (*) is the repetition operator.
Example:
>>>list = [ 'Hai', 123 , 1.75, 'vinu', 100.25 ]
>>>smalllist = [251, 'vinu']
>>>print(list) # Prints complete list
>>>print(list[0]) # Prints first element of the list
>>>print(list[-1]) # Prints last element of the list
>>>print(list[1:3]) # Prints elements starting from 2nd till 3rd
>>>print list([2:]) # Prints elements starting from 3rd element
>>>print(smalllist * 2) # Prints list two times
>>>print(list + smalllist) # Prints concatenated lists
Output
['Hai', 123, 1.75, 'vinu', 100.25]
Hai
100.25
[123, 1.75]
[1.75, 'vinu', 100.25]
[251, 'vinu', 251, 'vinu']
['Hai', 123, 1.75, 'vinu', 100.25, 251, 'vinu']
Operations on list:
Indexing
Slicing
Concatenation
Repetitions
10
Updation, Insertion, Deletion
6.78, 9]
Repetition >>>list2*3 Creates new strings, concatenating
['god', 6.78, 9, 'god', 6.78, 9, 'god', multiple
6.78, 9] copies of the same string
Updating the list >>>list1[2]=45 Updating the list using index value
>>>print( list1)
7.79, 45,
Inserting an element >>>list1.insert(2,"program") Inserting an element in 2ndposition
>>> print(list1)
['python', 7.79, 'program', 45,
'hello']
Removing an element >>>list1.remove(45) Removing an element by
>>> print(list1) giving the element directly
['python', 7.79, 'program', 'hello']
3.3 Tuple
Tuple are sequence of values much like the list. The values stored in the tuple can be of
any type and they are indexed by integers. A tuple consists of a sequence of elements separated
square bracket
([ ]) and their elements and size can be changed while tuples are enclosed in parenthesis (( )) and
cannot be updated.
Syntax:
tuple_name=(items)
11
Example:
>>>
Note:
A tuple is same as list, except that the set of elements is enclosed in parentheses
instead of square brackets.
A tuple is an immutable list.i.e. once a tuple has been created, you can't add elements to a tuple or
remove elements from the tuple.
Benefit of Tuple:
Tuples are faster than lists.
If the user wants to protect the data from accidental changes, tuple can be used.
Tuples can be used as keys in dictionaries, while lists can't.
Basic Operations:
Creating a tuple >>>t= ("python",7.79, 101, Creating the tuple with elements
of different data types.
Indexing >>>print (t[0]) python Accessing the item in the
>>>t[2] position 0
101 Accessing the item in the
position 2
12
Altering the tuple data error occurs when user tries to do.
>>>t[0]="a"
Trace back (most recent call last):
File "<stdin>", line 1, in <module>
Type Error: object does not support item assignment
Mapping
-This data type is unordered and mutable.
-Dictionaries fall under Mappings.
4. Dictionaries:
Lists are ordered sets of objects, whereas dictionaries are unordered sets.
Dictionary is created by using curly brackets. i,e.{}
Dictionaries are accessed via keys and not via their position.
A dictionary is an associative array (also known as hashes). Any key of the dictionary is associated
(or mapped) to a value.
The values of a dictionary can be any Python data type. So dictionaries are unordered key-value-
pairs(The association of a key and a value is called a key- value pair)
Dictionaries don't support the sequence operation of the sequence data types like strings, tuples and lists.
Creating a >>> food = {"ham":"yes", "egg" : Creating the dictionary with elements
dictionary "yes", "rate":450 } of different data
>>>print(food) types.
{'rate': 450, 'egg': 'yes', 'ham':
'yes'}
Indexing >>>>print(food["rate"]) Accessing the item with keys.
450
Slicing( ending >>>print(t[1:3]) Displaying items from 1st till 2nd.
position -1) (7.79, 101)
Syntax:
dict_name= {key: value}
Example:
>>>dict1={}
>>>dict2={1:10,2:20,3:30}
If you try to access a key which doesn't exist, you will get an error message:
13
>>>words = {"house" : "Haus", "cat":"Katze"}
>>>words["car"]
Traceback (most recent call last): File
"<stdin>", line 1, in <module>KeyError: 'car'
5. SET
Sets are used to store multiple items in a single variable.A set is a collection which is both unordered
and unindexed do not allow duplicate values.
Sets are written with curly brackets.
EXAMPLE
thisset = {"apple","banana", "cherry"}
print(thisset)
OUTPUT
cherry appl anana }
6. FROZENSET
The frozen set() is an in built function in Python which takes an iterable object as input and makes the
immutable. Simply it freezes the iterable objects and makes them unchangeable.
In Python, frozen set is same as set except its elements are immutable.
SYNTAX
frozen set(iterable_object_name)
Parameter: This function accepts iterable object as input parameter. Return Type: This function return an
EXAMPLE:
#TUPLE OFNUMBERS
num=(1,2,3,4,5,6,7,8,9)
fnum=frozen set(num)
print( ozen set object is: ,fnum)
Output
Frozen set objectis :frozenset({1,2,3,4,5,6,7,8,9})
14
7. BinaryTypes
In Python 2, the str type was used for two different kinds of values text and bytes, whereas in
Python 3, these are separate and incompatible types.This means that before Python3 we could treat a
set of bytes as a string and work from there, this is not the case now, now we have a separate data type,
called bytes.
This data type can be briefly explained as a string of bytes, which essentially means, once the
bytes data type is initialized it is immutable.
EXAMPLE
byte str = bytes (b 'abc')
# initializing a string with b
# makes it a binary string print (byte str)
Print (byte str[0])
byte str[0] = 97
OUTPUT
b 'abc'
97
EXAMPLE
x = bytearray(5)
#display x:
print(x)
#display the data type of x:
print(type(x))
OUTPUT
b'Hello'
<class 'bytes'>
EXAMPLE
x = memory view(bytes(5))
#display x:
print(x)
#display the data type of x:
print(type(x))
OUTPUT
<memory at0x0368AFA0>
<class 'memoryview'>
---------------------------------------------------------------------------------------------------------------------------------------------
15
3. Variables, Keywords Expressions, Statements, Comments, Docstring ,Lines And Indentation,
Quotation In Python, Tuple Assignment:
VARIABLES:
A variable allows us to store a value by assigning it to a name, which can be used later.
Named memory locations to store values.
Programmers generally choose names for their variables that are meaningful.
It can be of any length. No space is allowed.
We don't need to declare a variable before using it. In Python, we simply assign a value to a variable
and it will exist.
>>> a=b=c=100
Assigning multiple values to multiple variables:
>>>a,b,c=2,4,"ram"
----------------------------------------------------------------------------------------------------------------------------- -----------------------------
KEYWORDS:
---------------------------------------------------------------------------------------------------------------------------------------------
IDENTIFIERS:
Identifier is the name given to entities like class, functions, variables etc. in Python.
Identifiers can be a combination of letters in lowercase (a to z) or uppercase (A to
Z) or digits (0 to 9) or an underscore (_).
all are valid example.
An identifier cannot start with a digit.
Keywords cannot be used as identifiers.
Cannot use special symbols like!, @, #, $, % etc. in our identifier.
Identifier can be of any length.
Example:
Names like myClass, var_1, and this_is_a_long_variable
Here, The first line is an assignment statement that gives a value to n. The second line is
a print statement that displays the value of n.
Expressions:
-An expression is a combination of values, variables, and operators.
- A value all by itself is considered an expression, and also a variable.
- So the following are all legal expressions:
>>> 42
42
>>> a=2
>>>a+3+2 7
>>> z=("hi"+"friend")
>>>print(z) hifriend
INPUT: Input is data entered by user (end user) in the program. In python, input
() function is available for input.
Syntax for input() is:
variable = input
40
Example:
>>> x=input("enter the name:")
enter the name: george
>>>y=int(input("enter the number"))
enter the number 3
#python accepts string as default data type. Conversion is required for type.
COMMENTS:
A hash sign (#) is the beginning of a comment.
Anything written after # in a line is ignored by interpreter.
Eg: percentage = (minute * 100)/60 # calculating percentage of an hour
Python does not have multiple-line commenting feature. You have to comment each line
individually as follows:
Example:
# This is a comment.
# This is a comment, too.
# I said that already.
DOCSTRING:
Docstring is short for documentation string.
It is a string that occurs as the first statement in a module, function, class, or method definition. We
must write what a function/class does in the docstring.
Triple quotes are used while writing docstrings.
Syntax:
functionname doc. Example:
def double(num):
"""Function to double thevalue"""
return2*num
>>>print (double. doc )
Function to double the value
41
Example:
a=3
b=1
if a>b:
print("a is greater")
else:
print("b is greater")
QUOTATION INPYTHON:
Python accepts single ('), double (") and triple (''' or """) quotes to denote string literals. Anything that is
represented using quotations are considered as string.
TUPLE ASSIGNMENT
Example:
-It is useful to swap the values of two variables. With conventional assignment statements, we have to use a
temporary variable. For example, to swap a and b:
42
-Tuple assignment solves this problem neatly:
(a, b) = (b, a)
>>>age
25
>>>salary
---------------------------------------------------------------------------------------------------------------------------------------------
EXPRESSION:
An expression is a combination of variables, operators, values and calls to functions. Expressions need
to be evaluated.
Need for Expression:
Suppose if you wish to calculate area. Area depends on various parameters in
different situations. E.g. Circle, Rectangle and so on.
is w * l in case of rectangle. Hence, in this case a variable / value / operator are not enough to handle
such situation. So expressions are used. Expression is the combination of variables, values and operations.
---------------------------------------------------------------------------------------------------------------------------------------------
43
1.6 Manipulating Numbers:
If a numeric literal contains a decimal point, then it denotes a real value or float
An optional sign is + or -.
A numeric literal is a literal containing only the numeric or digits (0 9).
Example:
12.21
10.00
00.02
Or, it denotes an integer value.
Example:
12
21
Example:
12,500 (Invalid)
12500 (Valid)
The values -2 and 30, for example, are said to be integer values. The integer (or int) data type
indicates values that are whole numbers. Numbers with a decimal point, such as 2.14, are called floating-
point numbers (or floats).
Example for Integers
>>> 1 + 1
>>> a = 4
>>> type(a)
>>> c = 2.1
>>> type(c)
45
1.7 Text Manipulations:
Strings are amongst the most popular types in Python. We can create them simply by enclosing
characters in quotes. Python treats single quotes the same as double quotes.
Creating strings is as simple as assigning a value to a variable.
Example:
var1 = 'Hello World!'
var2 = "Python Programming"
Accessing Values in Strings
Python does not support a character type; these are treated as strings of length one, thus also considered
a substring. To access substrings, use the square brackets for slicing along with the index or indices to
obtain your substring.
Example:
var1 = 'Hello World!' var2 = "Python Programming" print("var1[0]: ", var1[0])
print("var2[1:5]: ", var2[1:5])
Output
var1[0]: H
var2[1:5]:
ytho
Updating Strings
You can "update" an existing string by (re)assigning a variable to another string. The new value
can be related to its previous value or to a completely different string altogether.
Example:
var1 = 'Hello World!'
print("Updated String :- ", var1[:6] + 'Python')
When the above code is executed, it produces the following result:
Output:
Updated String :- Hello Python
ESCAPE CHARACTERS
Following table is a list of escape or non-printable characters that can be represented with backslash
notation.
An escape character gets interpreted; in a single quoted as well as double quoted strings.
46
One of Python's coolest features is the string format operator %. This operator is
unique to strings and makes up for the pack of having functions from C's printf()
family.
Example
Output
Here is the list of complete set of symbols which can be used along with
47
---------------------------------------------------------------------------------------------------------------------------------------------
A function is a group of statements that performs a specific task. Python provides a library of functions like
any other programming language. The built-in functions such as eval, input, print, and int are always available
in the functions.
Simple Python Built-in Functions
Function Description Example
abs(x) Returns the absolute value for x abs(-2) is 2
max(x1, x2, ...) Returns the largest among x1, x2, ... max(1, 5, 2) is 5
min(x1, x2, ...) Returns the smallest among x1, x2, ... min(1, 5, 2) is 1
pow(a, b) Returns ab. Same as a ** b. pow(2, 3) is 8
48
round(x) Returns an integer nearest to x. If x is round(5.4) is 5
equally close to two integers, the even one round(5.5) is 6
is returned. round(4.5) is 4
round(x, n) Returns the float value rounded to n digits round(5.466, 2) is 5.47
after the decimal point. round(5.463, 2) is 5.46
Mathematical Functions
Function Description Example
fabs(x) Returns the absolute value for x as a float. fabs(-2) is 2.0
ceil(x) Rounds x up to its nearest integer and returns that integer. ceil(2.1) is 3
ceil(-2.1) is -2
floor(x) Rounds x down to its nearest integer and returns that integer. floor(2.1) is 2
floor(-2.1) is -3
exp(x) Returns the exponential function of x (ex). exp(1) is 2.71828
log(x) Returns the natural logarithm of x. log(2.71828) is 1.0
log(x, base) Returns the logarithm of x for the specified base. log(100, 10) is 2.0
sqrt(x) Returns the square root of x. sqrt(4.0) is 2
sin(x) Returns the sine of x. x represents an angle in radians. sin(3.14159 / 2) is 1
sin(3.14159) is 0
asin(x) Returns the angle in radians for the inverse of sine. asin(1.0) is 1.57
asin(0.5) is 0.523599
cos(x) Returns the cosine of x. x represents an angle in radians. cos(3.14159 / 2) is 0
cos(3.14159) is -1
acos(x) Returns the angle in radians for the inverse of cosine. acos(1.0) is 0
acos(0.5) is 1.0472
tan(x) Returns the tangent of x. x represents an angle in radians. tan(3.14159 / 4) is 1
tan(0.0) is 0
degrees(x) Converts angle x from radians to degrees. degrees(1.57) is 90
radians(x) Converts angle x from degrees to radians. radians(90) is 1.57
String Functions:
Method Description
capitalize() Converts the first character to upper case
casefold() Converts string into lower case.
center() Returns a centered string.
count() Returns the number of times a specified value occurs in a string.
encode() Returns an encoded version of the string
endswith() Returns true if the string ends with the specified value
expandtabs() Sets the tab size of the string
find() Searches the string for a specified value and returns the position of where it was found
format() Formats specified values in a string
index() Searches the string for a specified value and returns the position of where it was found
isalpha() Returns True if all characters in the string are in the alphabet
isdecimal() Returns True if all characters in the string are decimals
isdigit() Returns True if all characters in the string are digits
sidentifier() Returns True if the string is an identifier
islower() Returns True if all characters in the string are lower case
isnumeric() Returns True if all characters in the string are numeric
isupper() Returns True if all characters in the string are upper case
join() Joins the elements of an iterable to the end of the string
lower() Converts a string into lower case
49
replace() Returns a string where a specified value is replaced with a specified value
upper() Converts a string into upper case
Function is a sub program which consists of set of instructions used to perform a specific task.
A large program is divided into basic building blocks called function.
FUNCTIONS:
Need For Function:
When the program is too complex and large they are divided into parts. Each part is separately
coded and combined into single program. Each subprogram is called as function.
Debugging, Testing and maintenance becomes easy when the program is divided into
subprograms.
Functions are used to avoid rewriting same code again and again in a program.
Function provides code re-usability
The length of the program is reduced.
Types of function:
Functions can be classified into two categories:
i) user defined function
ii) Built in function
i) Built in functions
Built in functions are the functions that are already created and stored inpython.
These built in functions are always available for usage and accessed by a programmer. It cannot be
modified.
50
Built in function Description
3. What is IDLE?
Integrated Development Learning Environment (IDLE) is a graphical user interface which
is completely written in Python. It is bundled with the default implementation of the python language and
also comes with optional part of the Python packaging.
4. Differentiate between interactive and script mode.
58
6. What is a tuple?
A tuple is same as list, except that the set of elements is enclosed in parentheses
instead of square brackets.
A tuple is an immutable list.i.e. once a tuple has been created, you can't add elements to a tuple or
remove elements from the tuple.
7. Outline the logic to swap the contents of two identifiers without using third variable.
Swap two numbers Output:
a=2;b=3
print(a,b) (2, 3)
a = a+b (3, 2)
b= a-b >>>
a= a-b
print(a,b)
Example Output
59
10. What is return statement?
The return statement is used to exit a function and go back to the place from
where it was called. If the return statement has no arguments, then it will not return any
values. But exits from function.
Syntax:
return[expression]
Required Arguments
Keyword Arguments
Default Arguments
Variable length Arguments
60