Python Unit-1
Python Unit-1
Python Unit-1
UNIT-1 NOTES
History
Python is a general-purpose interpreted, interactive, object-oriented, and high-level
programming language.
It was created by Guido van Rossum during 1985- 1990.
Python got its name from “Monty Python’s flying circus”. Python was released in the year 1991.
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++,Java script ,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.
Advantages and Disadvantages
Advantages
Disadvantages
Applications
Python interpreter:
Interpreter: To execute a program in a high-level language by translating it one line at a time.
Compiler: To translate a program written in a high-level language into a low-level language all
at once, in preparation for later execution.
Python Setup
What is IDE?
Features of IDLE:
The Python interpreter can be used from an interactive shell. The interactive shell is
also interactive in the way that it stands between the commands or actions and their
execution.
Python offers a comfortable command line interface with the Python shell, which is also
known as the "Python interactive shell".
Python shell to display output with syntax highlighting.
MODES OF PYTHON INTERPRETER:
Python Interpreter is a program that reads and executes Python code. It uses 2 modes of
Execution.
1. Interactive mode
2. Script mode
1. Interactive mode:
Advantages:
Python, in interactive mode, is good enough to learn, experiment or explore.
Working in interactive mode is convenient for beginners and for testing small pieces of
code.
Drawback:
We cannot save the statements and have to retype all the statements once again to re-run
them.
In interactive mode, you type Python programs and the interpreter displays the result:
>>> 1+1
2
The chevron, >>>, is the prompt the interpreter uses to indicate that it is ready for you to
enter code. If you type 1 + 1, the interpreter replies 2.
>>> print ('Hello, World!')
Hello, World!
This is an example of a print statement. It displays a result on the screen. In this case, the result is
the words.
2. 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.
VALUES AND DATA TYPES
Value can be any letter ,number or string. Every value in Python has a data type.
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.
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,
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.
We can use the type( ) function to know which class a variable or a value belongs to.
Example
>>>num1 = 5
>>>print(num1,’ is of type ‘, type(num1))
Output: 5 is of type <class ‘int’>
>>>num2 = 2.5
>>>print(num2,’ is of type ‘, type(num2))
Output: 2.5 is of type <class ‘float’>
>>>num3 = 1+2j
>>>print(num3’ is of type ‘, type(num3))
Output: 1+2j is of type <class ‘complex’>
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) data types.
There are five types of sequence data type available in Python, they are
1. String
2 List
3. Tuple
4. Set
5. Range
1. String
A String in Python consists of a series or sequence of characters - letters, numbers, and special
characters.
Strings are marked by quotes:
single quotes (' ') Eg, 'This a string in single quotes'
double quotes (" ") Eg, "'This a string in double quotes'"
triple quotes(""" """) Eg, 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.
Operations on string:
1. Indexing
2. Slicing
3. Concatenation
4. Repetitions
5. Membership
2. List
List is an ordered sequence of items. Values in the list are called elements / items.
It can be written as a list of comma-separated items (values) between square brackets[ ].
Items in the lists can be of different data types.
Operations on list:
1. Indexing
2. Slicing
3. Concatenation
4. Repetitions
5. Updation, Insertion, Deletion
3. 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.
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:
Altering the tuple data type leads to error. Following error occurs when user tries to do.
>>> t[0]="a"
Trace back (most recent call last):
File "<stdin>", line 1, in <module>
Type Error: 'tuple' object does not support item assignment
Indexing:
Set items can appear in a different order every time we use them, and cannot be referred
to by index or key.
Set items are unchangeable, meaning that we cannot change the items after the set has
been created.
Example 1:
>>>s = {"apple", "banana", "cherry"}
>>>print(s)
Output: {‘banana’, ‘apple’, ‘cherry’}
# Note: the set list is unordered, meaning: the items will appear in a random order.
Example 2:
>>>s = {"apple", "banana", "cherry", "apple"}
>>>print(s)
Output: {‘banana’, ‘cherry’, ‘apple’}
Example 3:
>>>s = {"apple", "banana", "cherry"}
>>>print(len(s))
Output: 3
Example 4:
>>>set1 = {"abc", 34, True, 40, "male"}
>>>print(set1)
Output: {‘abc’, 34, True, 40, ‘male’}
Operations on Set:
1. Adding
2. Updating
3. Removing
4. Joining
1.Adding:
To add one item to a set use the add() method.
Example:
>>>s = {"apple", "banana", "cherry"}
>>>s.add("orange")
>>>(s)
Output: {‘apple’, ‘banana’, ‘cherry’, ‘orange’}
2.Updating:
To add items from another set into the current set, use the update() method.
Example:
>>>s = {"apple", "banana", "cherry"}
>>>p = {"pineapple", "mango", "papaya"}
>>>s.update(p)
>>>print(s)
Output: {‘apple’, ‘banana’, ‘cherry’, ‘pineapple’, ‘mango’, ‘papaya’}
3.Removing:
Example 2:
s = {"apple", "banana", "cherry"}
s.discard("banana")
print(s)
5.Joining:
o union() - returns a new set containing all items from both sets..
o update() - inserts all the items from one set into another.
o intersection() - return a new set, that only contains the items that are present in
both sets.
o symmetric_difference() - return a new set, that contains only the elements that
are NOT present in both sets.
Example 1:
>>>set1 = {"a", "b" , "c"}
>>>set2 = {1, 2, 3}
>>>set3 = set1.union(set2)
>>>print(set3)
Output: {‘a’, 1, 2, ‘b’ , 3, ‘c’}
Example 2:
>>>set1 = {"a", "b" , "c"}
>>>set2 = {1, 2, 3}
>>>set1.update(set2)
>>>print(set1)
Output: {‘a’, 1, 2, ‘b’ , 3, ‘c’}
Example 3:
>>>x = {"apple", "banana", "cherry"}
>>>y = {"google", "microsoft", "apple"}
>>>z = x.intersection(y)
>>>print(z)
Output: {‘apple’}
Example 4:
>>>x = {"apple", "banana", "cherry"}
>>>y = {"google", "microsoft", "apple"}
>>>z = x.symmetric_difference(y)
>>>print(z)
5.Range:
The range() function returns a sequence of numbers, starting from 0 by default, and
increments by 1 (by default), and stops before a specified number.
Syntax:
range(start, stop, step)
start Optional. An integer number specifying at which position to start. Default is 0
stop Required. An integer number specifying at which position to stop (not included).
Example 1:
x= range(4)
for n in x:
print (n)
Output:
0
1
2
3
Example 2:
x = range(3, 10, 2)
for n in x:
print(n)
Output:
3
5
7
9
Dictionary:
Dictionaries are written with curly brackets, and have keys and values.
Example 1:
Example 2:
KEYWORDS:
Keywords are the reserved words in Python.
We cannot use a keyword as variable name, function name or any other identifier.
They are used to define the syntax and structure of the Python language.
Keywords are case sensitive.
Identifiers - Python
Identifier is the name given to entities like class, functions, variables etc. in Python.
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
Comments - Python
A hash sign (#) is the beginning of a comment.
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.
Quotation in Python
Anything that is represented using quotations are considered as string.
QUOTATION IN PYTHON:
Python accepts single ('), double (") and triple (''' or """) quotes to denote string literals.
Anything that is represented using quotations are considered as string.
single quotes (' ') Eg, 'This a string in single quotes'
double quotes (" ") Eg, "'This a string in double quotes'"
triple quotes(""" """) Eg, This is a paragraph. It is made up of multiple lines and
sentences."""
Lines and Indentation - Python
Most of the programming languages like C, C++, Java use braces { } to define a block of code.
Example:
a=3
b=1
if a>b:
print("a is greater")
else:
print("b is greater")
Input and Output - Python
INPUT: Input is data entered by user (end user) in the program.
Statements:
Instructions that a Python interpreter can executes are called statements.
A statement is a unit of code like creating a variable or displaying a value.
>>> n = 17
>>> print(n)
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
TUPLE ASSIGNMENT
Output:
(2, 3)
(3, 2)
>>>
(a, b) = (b, a)
In tuple packing, the values on the left are ‘packed’ together in a tuple:
>>> b = ("George", 25, "20000") # tuple packing
In tuple unpacking, the values in a tuple on the right are ‘unpacked’ into
the variables/names on the right:
'George'
>>> age
25
>>> salary
'20000'
Example:
>>> mailid='god@abc.org'
>>> name,domain=mailid.split('@')
>>> print name
god
print (domain)
abc.org