0% found this document useful (0 votes)
5 views32 pages

Unit-1 (Introduction) (1)

The document provides an introduction to Python, detailing its features, installation, and basic syntax, as well as data types and variables. It explains the Python interpreter, including interactive and script modes, and outlines the different data types such as numbers, booleans, strings, and lists. Additionally, it covers string functions and operations, emphasizing Python's ease of use and versatility for beginners and experienced programmers alike.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
5 views32 pages

Unit-1 (Introduction) (1)

The document provides an introduction to Python, detailing its features, installation, and basic syntax, as well as data types and variables. It explains the Python interpreter, including interactive and script modes, and outlines the different data types such as numbers, booleans, strings, and lists. Additionally, it covers string functions and operations, emphasizing Python's ease of use and versatility for beginners and experienced programmers alike.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 32

UNIT I

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 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
flying Python was released in the year 2000.

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

1.2 PYTHON INTERPRETER AND INTERACTIVE MODE

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.

1.2.1 Python Interactive mode

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

No Intermediate is Object Code


Intermediate Object Code is Generated
Generated
Conditional Control Statements are Conditional Control Statements are
Executes faster Executes slower
Memory Requirement is More(Since Object
Memory Requirement is Less
Code is Generated)
Program need not be compiled every time Every time higher level program is
converted into lower level program
Errors are displayed after entire program is checked Errors are displayed for every instruction
interpreted (if any)
Example : C Compiler Example : PYTHON

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
Interactive mode:
Interactive Mode, as the name suggests, allows us to interact with OS.
When we type Python statement, interpreter displays the result(s) immediately.
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!

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.

Interactive mode Script mode


A way of using the Python interpreter by A way of using the Python interpreter to read and
typing commands and expressions at the prompt. execute statements in a 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.

We can see the results immediately. We see the code immediately.

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.
Features of IDLE:
Multi-window text editor with syntax highlighting.
Auto completion with smart indentation.
Python shell to display output with syntax highlighting.
---------------------------------------------------------------------------------------------------------------------------------------------

2. VALUES AND DATATYPES

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:

Positive indexing helps in accessing the string from the beginning


Negative subscript helps in accessing the string from the end.
Subscript 0 or ven(where n is length of the string) displays the first element.
Example: A[0] or A[-5] will display
Subscript 1 or ve (n-1) displays the second element.
Example: A[1] or A[-4] will display
Operations on string:
i. Indexing
ii. Slicing
iii. Concatenation
iv. Repetitions
v. Membership
Creating a string >>> s="good morning" Creating the list with elements of different data
types.
Indexing >>>print(s[2]) Accessing the item in the the
o Position 0
>>>print(s[6]) Accessing the item in
O Position 2
nd
Slicing (ending >>>print(s[2:]) - Displaying items from 2 till last.
position -1) od morning

8
st
Slice operator is used >>>print(s[:4]) - Displaying items from 1
to extract part of a Good
position till 3rd.
data
type

Concatenation >>>print(s+"friends") -Adding and printing the


good morning friends characters of two strings.

Repetition >>>print(s*2) Creates new strings,


good morning concatenating multiple copies of
good morning the same string
in, not in (membership >>> s="good morning" Using membership operators to check a particular
operator) >>>"m" in s True character is in string or not. Returns true if present.
>>> "a" not in s
True

String Functions:

For the following string functions the value of str1 and str2 are as follows:

S.No Method Syntax Description Example


1. print(str1+str2)
+ String1 + String2 It Concatenates two Strings
HelloWorld
2. str1*3
* String*3 It multiples the string
HelloHelloHello
3. len() len(String) Returns the length of the String len(str1) 5
4. The String will be centred
along with the width specified str1.centre(20,+)
centre() centre(width,fullchar)
and the charecters will fill the ++++Hello++++
space
5. Converts all upper case into
lower() String.lower() str1.lower() hello
lower case
6. Converts all lower case into
upper() String.upper() str1.upper() HELLO
upper case
7. splits according to the
split() character which is present
H+E+L+L+O
inside the function
8. It converts a string in to its
ord() ord(String) 96
corresponding value
9. It converts a number in to its
chr() chr(Number) chr(100)--
corresponding String

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

Creating a list >>>list1=["python", 7.79, 101, Creating the list with


elements of different data
>>>list2=["god",6.78,9] types.
Indexing >>>print(list1[0]) python Accessing the item in the
>>>list1[2] position0
101 Accessing the item in the
position2

Slicing( ending >>>print(list1[1:3]) - Displaying items from 1st


position -1) [7.79, 101] till2nd.
Slice operator is used to >>>print(list1[1:]) [7.79, 101, - Displaying items from 1st
extract part of a string, 'hello'] position till last.
or some part of a
list
Python

Concatenation >>>print( list1+list2) -Adding and printing the


['python', 7.79, 101, 'hello', 'god', items of two lists.

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:
>>>

>>>print(tuple2) #print tuple2 elements


>>>print(tuple2[0]) #print the first element of tuple2

>>>print(tuple2 + tuple3) #print the concatenation of tuple2 and tuple3


>>>print(tuple3[2]) #print the second element of tuple3
Output:

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

Slicing (ending >>>print (t[1:3]) Displaying items from1st


position -1) (7.79, 101) nd
till 2 .

Concatenation >>>t+("ram", 67) Adding tuple elements at


('python', 7.79, 101, 'hello', 'ram', the end of another tuple elements
67)

Repetition >>>print (t*2) Creates new strings,


('python', 7.79, 101, 'hello', concatenating multiple copies of the
'python', 7.79, 101, 'hello')
same string

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'

Data type Compile time Run time


int a=10
float a=10.5
string a
list a=[20,30,40,50] a
tuple a=(20,30,40,50) a

Data Type : Set TYPE

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

equivalent frozen set object.

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.

Assigning value to variable:


Value should be given on the right side of assignment operator(=) and variable on left side.
>>>counter =45
print (counter)

Assigning a single value to several variables simultaneously:

>>> a=b=c=100
Assigning multiple values to multiple variables:

>>>a,b,c=2,4,"ram"
----------------------------------------------------------------------------------------------------------------------------- -----------------------------
KEYWORDS:

Keywords are the reserved words in Python.


We cannot use a keyword as 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:
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

Valid declarations Invalid declarations


Num Number 1
Num num1
Num1 addition of program
_NUM 1Num
NUM_temp2 Num.no
IF if
Else else
---------------------------------------------------------------------------------------------------------------------------------------------

STATEMENTS AND EXPRESSIONS:


Statements:
-Instructions that a Python interpreter can executes are called statements.
-A statement is a unit of code like creating a variable or displaying avalue.
>>> 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

INPUT AND OUTPUT

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.

OUTPUT: Output can be displayed to the user using Print statement .


Syntax:
print (expression/constant/variable)
Example:
>>> print ("Hello")
Hello
---------------------------------------------------------------------------------------------------------------------------------------------

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

LINES AND INDENTATION:


Most of the programming languages like C, C++, Java use braces { } to define a block of code. But,
python uses indentation.
Blocks of code are denoted by line indentation.
It is a space given to the block of codes for class and function definitions or flow control.

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.

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

TUPLE ASSIGNMENT

An assignment to all of the elements in a tuple using a single assignment statement.


Python has a very powerful tuple assignment feature that allows a tuple of variables on the left of an
assignment to be assigned values from a tuple on the right of the assignment.
The left side is a tuple of variables; the right side is a tuple of values.
Each value is assigned to its respective variable.
All the expressions on the right side are evaluated before any of the assignments. This feature makes
tuple assignment quite versatile.
Naturally, the number of variables on the left and the number of values on the right have to be the
same.
>>>(a, b, c, d) = (1, 2, 3)
ValueError: need more than 3 values to unpack

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:

Swap two numbers Output:


a=2;b=3
print(a,b) (2, 3)
temp = a (3, 2)
a=b >>>
b = temp
print(a,b)

42
-Tuple assignment solves this problem neatly:

(a, b) = (b, a)

-One way to think of tuple assignment is as tuple packing/unpacking.


In tuple packing, the values on the left are together in a tuple:

>>>b = ("George",25,"20000") # tuplepacking

-In tuple unpacking,


right:

>>>b = ("George", 25, "20000") # tuple packing


>>>(name, age, salary)=b # tupleunpacking
>>>name

>>>age
25
>>>salary

-The right side can be any kind of sequence (string, list,tuple)


Example:
-To split an email address in to user name and a domain
>>>mailid='[email protected]'
>>>name,domain=mailid.split('@')
>>>print name god
>>> print (domain) abc.org

---------------------------------------------------------------------------------------------------------------------------------------------

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)

Numbers in Python refer to the numeric data types in Python programming.


Python supports three kinds of numeric data types:
int, float, and complex.
Complex numbers have real parts and imaginary parts.
num=2+5j
type(num)
num.real #Gives the real part of the complex number
44
num.imag #Gives the imaginary part of the complex number
1.6. 1 INTEGERS AND FLOAT:
A data type is a category for values, and every value belongs to exactly one data type. All data values
in Python are encapsulated in relevant object classes. The most common data types in Python are listed in
below.

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)

<type int >

Example for Floats

>>> c = 2.1

>>> type(c)

<type float >


c) COMPLEX:
Complex numbers are written with a "j" as the imaginary part:
Example
>>>x = 3+5j
>>>y = 5j
>>>z = -5j
>>>print(type(x))
>>>print(type(y))
>>>print(type(z))
Output
<class
<class
<class
---------------------------------------------------------------------------------------------------------------------------------------------

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

Print("My name is %s and weight is %d kg!" % ('Zara', 21) )

Output

My name is Zara and weight is 21 kg!

Here is the list of complete set of symbols which can be used along with

47
---------------------------------------------------------------------------------------------------------------------------------------------

PYTHON BUILT-IN FUNCTIONS:


FUNCTIONS
A function is a named sequence of statements that performs a specific task. Functions help
programmers to break complex program into smaller manageable units. It avoids repetition and
makes code reusable.
Types of Functions
BUILT-IN FUNCTIONS
USER DEFINED FUNCTIONS

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

>>>max(3,4) 4 # returns largest element

>>>min(3,4) 3 # returns smallest element

>>>len("hello") 5 #returns length of an object

>>>range(2,8,1) [2, #returns range of given values


3, 4, 5, 6, 7]
>>>round(7.8) 8.0 #returns rounded integer of the given number

>>>chr(5) #returns a character (a string) from an integer


\x05'
>>>float(5) #returns float number from string or integer
5.0
>>>int(5.0) 5 # returns integer from string or float

>>>pow(3,5) 243 #returns power of given number

>>>type( 5.6) #returns data type of object to which it belongs


<type 'float'>
>>>t=tuple([4,6.0,7]) # to create tuple of items from list
(4, 6.0, 7)
>>>print("good morning") # displays the given object
Good morning
>>>input("enter name:") # reads and returns the given string
enter name : George

ii) User Defined Functions:


User defined functions are the functions that programmers create for their requirement anduse.
These functions can then be combined to form module which can be used in other programs by
importing them.
Advantages of user defined functions:
Programmers working on large project can divide the workload by making different functions.
If repeated code occurs in a program, function can be used to include those codes and execute
---------------------------------------------------------------------------------------------------------------------------------------------
ILLUSTRATIVE PROGRAMS

Program for SWAPPING(Exchanging )of Output


values
a = int(input("Enter a value ")) Enter a value 5
b = int(input("Enter b value")) Enter b value 8
c=a a=8
a=b b=5
b =c
print("a=",a,"b=",b,)

Program to find distance between twopoints Output

import math enter x17


x1=int(input("enter x1")) enter y16
y1=int(input("enter y1"))
enter x25
x2=int(input("enter x2"))
y2=int(input("enter y2")) enter y27
distance =math.sqrt((x2-x1)**2)+((y2- y1)**2) 2.5
print(distance)

Program to circulate n numbers Output:


a=list(input("enter the list")) enter the list '1234'

print(a) ['1', '2', '3', '4']


for i in range(1,len(a),1): ['2', '3', '4', '1']
print(a[i:]+a[:i]) ['3', '4', '1', '2']
['4', '1', '2', '3']
TWO MARKS:
1. What is Python?
Python is a general-purpose interpreted, interactive, object-oriented, and high-
level programming language.

2. Enlist some features of python.


Easy-to-learn.
Easy-to-maintain.
Portable
Interpreted
Extensible
Free and Open Source
High Level Language

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.

Interactive mode Script mode


A way of using the Python interpreter by A way of using the Python interpreter to read and
typing commands and expressions at the execute statements in a script.
prompt.
Cant save and edit the code Can save and edit the code
we cannot save the statements for further we can save the statements for further use and we
use and we have to retype no need to retype
all the statements to re-run them. all the statements to re-run them.
We can see the results immediately. We cant see the code immediately.

5. What are keywords? Give examples.


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.

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)

8. State about logical operators available in python with example.


Logical operators are and, or, operators.

Example Output

a = True a and b is False


b = False a or b is True
print('a and b is',a and b) not a is False
print('a or b is',a or b)
print('not a is',not a)

9. What are the needs used 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.

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]

11. What are the types of arguments?

Required Arguments
Keyword Arguments
Default Arguments
Variable length Arguments

12. Define a module.


A module is a file containing Python definitions, functions, statements and
instructions. Standard library of Python is extended as modules. To use these
modules in a program, programmer needs to import the module.

13. What is meant by interpreter?


An interpreter is a computer program that executes instructions written in a programming language. It
can either execute the source code directly or translate the source code in a first step into a more efficient
representation and executes this code.

14. What is a local variable?


A variable defined inside a function. A local variable can only be used inside its function.

15. What is meant by traceback?


A list of the functions that tells us what program file the error occurred in, and what line, and what
functions were executing at the time. It also shows the line of code that caused the error.

60

You might also like