python unit-1
python unit-1
python unit-1
UNIT-1
Introduction: Python is a widely used high-level programming language for general-purpose
programming, created by Guido van Rossum and first released in 1991. Python features a
dynamic type system and automatic memory management and supports multiple programming
paradigms, including object-oriented, imperative, functional programming, and procedural
styles. It has a large and comprehensive standard library.
There are two major Python versions- Python 2 and Python 3.
➢ On 16 October 2000, Python 2.0 was released with many new features.
➢ On 3rd December 2008, Python 3.0 was released with more testing and includes new
features
Python is Interpreted − Python is processed at runtime by the interpreter. You do not need to
compile your program before executing it. This is similar to PERL and PHP.
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 from simple text
processing to WWW browsers to games.
2 Easy to learn Python has a very simple syntax, meaning learners can very
quickly learn and start writing code.
3 Free and open Most Linux operating systems have Python by default. The
source standard modules and the Python interpreter are free.
Page |1 G L N V S Kumar, Dept of MCA, BVCITS, Amalapuram
Python Programming
4 High level When you write programs in Python, you never need to bother
language about the low-level details such as managing the memory used by
your program, etc.
5 portable Python programs can execute on any platform like Windows,
Linux, etc., without requiring any changes at all.
6 interpreted Python converts the source code into an intermediate form
called byte code
7 Object oriented Python supports procedure-oriented programming as well as
object-oriented programming.
8 Extensible If one needs a critical piece of code to run very fast or want to have
some piece of algorithm, you can code that part of your program
in C or C++ and then use/execute it from inside a Python program.
9 Embeddable One can embed Python within a C or C++ program.
10 Extensive The Python Standard Library is very exhaustive libraries for
libraries regular expressions, documentation generation, unit testing,
threading, databases, web browsers, CGI, FTP, email,
XML(Extensible Markup Language), XML-RPC, HTML, WAV
files, cryptography, GUI (graphical user interfaces), and other OS
related operations.
To start an IDLE interactive shell, search for the IDLE icon in the start menu and double
click on it.
You can execute Python statements same as in Python Shell as shown below.
To execute a Python script, create a new file by selecting File -> New File from the menu.
Enter multiple statements and save the file with extension .py using File -> Save. For
example, save the following code as hello.py.
Now, you can enter a single statement and get the result. For example, enter a simple
expression like 3 + 2, press enter and it will display the result in the next line, as shown
below.
Like other programming knowledge, python also has same rules of giving identifier to an
entity: such as,
✓ They start with letter A-Z or a-z or underscore [ _ ]. Internally, they can have digits
but not to start with.
✓ Their length is not Limited. But referred to be meaningful.
✓ They should not contain whitespaces.
✓ They are case sensitive. That is 'num' and 'NUM' are different.
✓ They should not be keywords.(it will show error, saying "Syntax error: Invalid
syntax") .
Some example of valid and invalid identifiers :
num #valid
wordCount #valid
account_number #valid
x_co-ordinate #valid
_4 #valid, but meaningless
ErrorNumber4 #valid
Plot#3 #invalid because of special symbol #
account number #invalid because of space
255 #invalid because starts with digit
empno. #invalid because of special symbol .
Python Indentation
Indentation refers to the spaces at the beginning of a code line. Where in other programming
languages the indentation in code is for readability only, the indentation in Python is very
important. Python uses indentation to indicate a block of code.
Most of the previous programming languages uses pair of curly braces { } to define a logical
block. But Python uses indentation.
A logical block of code (such as, body of a function, loop, class, etc.) starts with indentation
and ends with the first unindented line.
Variable
Every variable in Python is an object. A Python variable is a reserved memory location
to store values. Every value in Python has a data type. Different data type
in Python are Numbers, List, Tuple, Strings, Dictionary, etc.
Therefore, by assigning different data type values to variables, users can store integers,
floating point numbers, or characters in these variables.
Assigning Different Values to Variables
➢ Binding a variable in Python means setting a name to a variable to hold a reference to
some object.
➢ In Python, assignment creates references, not copies.
➢ Variable names in Python do not have any data type but objects have types.
Page |7 G L N V S Kumar, Dept of MCA, BVCITS, Amalapuram
Python Programming
➢ Python determines the type of the data automatically based on what data is assigned to it.
➢ Python uses reference semantics.
a = 50
b=a
The variable b refers to the same object that a points to because Python does not create
another object.
Let's assign the new value to b. Now both variables will refer to the different objects.
a = 50
b =100
Multiple Assignment
Python allows us to assign a value to multiple variables in a single statement, which is also
known as multiple assignments.
x=y=z=50
print(x)
print(y)
print(z)
You can also assign multiple objects to multiple variables. For example −
a,b,c=10,20.34,’kumar’
1.7. Explain various datatypes (Int, float, Boolean, string, and list)
Python Data Types
A Data Type describes the characteristic of a variable.
Python has six standard Data Types:
1. Numbers/Numeric
2. String
3. Boolean
4. List
5. Tuple
6. Set
7. Dictionary
1. Int - Integer value can be any length such as integers 10, 2, 29, -20, -150 etc. Python has
no restriction on the length of an integer. Its value belongs to int
2. Float - Float is used to store floating-point numbers like 1.9, 9.902, 15.2, etc. It is
accurate upto 15 decimal points.
3. complex - A complex number contains an ordered pair, i.e., x + iy where x and y denote
the real and imaginary parts, respectively. The complex numbers like 2.14j, 2.0 + 2.3j,
etc.
Example:
a=5
print("The type of a", type(a))
b = 40.5
print("The type of b", type(b))
c = 1+3j
print("The type of c", type(c))
output:
The type of a <class 'int'>
The type of b <class 'float'>
The type of c <class 'complex'>
String
The string can be defined as the sequence of characters represented in the quotation marks. In
Python, we can use single, double, or triple quotes to define a string.
str = "string using double quotes"
print(str)
s = '''''A multiline
string'''
print(s)
Output:
string using double quotes
A multiline
string
Accessing characters in Python String
In Python, individual characters of a String can be accessed by using the method of Indexing.
Page |9 G L N V S Kumar, Dept of MCA, BVCITS, Amalapuram
Python Programming
Indexing allows negative address references to access characters from the back of the String, e.g.
-1 refers to the last character, -2 refers to the second last character, and so on.
Index 0 1 2 3 4
Data K U M A R
Negative Index -5 -4 -3 -2 -1
str='satya kumar'
print('original string:: ' + str)
print('1st Character of String:: '+ str[0])
print('last character of string:: '+str[-1])
Boolean
Boolean type provides two built-in values, True and False. These values are used to determine
the given statement true or false. It denotes by the class bool. True can be represented by any
non-zero value or 'T' whereas false can be represented by the 0 or 'F'.
Example:
a = True
b = False
print (a)
print (b)
Output:
True
False
Python Lists
Lists are the most versatile of Python's compound data types. A list contains items separated by
commas and enclosed within square brackets ([]). To some extent, lists are similar to arrays in C.
One difference between them is that all the items belonging to a list can be of different data type.
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 Program:
list = [ 'bvcits', 786 , 2.23, 'kumar', 70.2 ]
list1 = [123, 'satya']
print(list) # Prints complete list
print(list[0]) # Prints first 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(list1 * 2) # Prints list two times
print(list + list1) # Prints concatenated lists
Output:
['bvcits', 786, 2.23, 'kumar', 70.2]
bvcits
[786, 2.23]
[2.23, 'kumar', 70.2]
[123, 'satya', 123, 'satya']
['bvcits', 786, 2.23, 'kumar', 70.2, 123, 'satya']
P a g e | 10 G L N V S Kumar, Dept of MCA, BVCITS, Amalapuram
Python Programming
1.8. Explain declaration, initialization of variables.
In Python, we need not declare a variable with some specific data type.
Python has no command for declaring a variable. A variable is created when some value is
assigned to it. The value assigned to a variable determines the data type of that variable.
Thus, declaring a variable in Python is very simple.
✓ Just name the variable
✓ Assign the required value to it
✓ The data type of the variable will be automatically determined from the
value assigned, we need not define it explicitly.
Example:
x=2
print(x)
print(type(x))
x=2.0
print(x)
print(type(x))
x='2'
print(x)
print(type(x))
1.9. Explain Input and Output statements.
Python Output using print() function
The simplest way to produce output is using the print() function where you can pass zero or
more expressions separated by commas. This function converts the expressions you pass
into a string before writing to the screen.
Syntax: print(value(s), sep= ‘ ‘, end = ‘\n’, file=sys.stdout, flush=False)
Parameters:
value(s) : Any value, and as many as you like. Will be converted to string before printed
sep=’separator’ : (Optional) Specify how to separate the objects, if there is more than
one.Default :’ ‘
end=’end’: (Optional) Specify what to print at the end. Default : ‘\n’
file : (Optional) An object with a write method. Default : sys.stdout
flush : (Optional) A Boolean, specifying if the output is flushed (True) or buffered (False).
Default: False
Returns: It returns output to the screen.
Example:
print(“Satya kumar")
x=5
# Two objects are passed
print("x =", x)
The Placeholders
The placeholders can be identified using named indexes {price}, numbered indexes {0}, or even
empty placeholders {}.
txt1 = "My name is {fname}, I'm {age}".format(age = 36, fname = "Satya",sal=40000)
print(txt1)
Formatting Types
Inside the placeholders you can add a formatting type to format the result:
:< Left aligns the result (within the available space)
:> Right aligns the result (within the available space)
:^ Center aligns the result (within the available space)
:= Places the sign to the left most position
:, Use a comma as a thousand separator
#Use "<" to left-align the value:
Assignment Operators
Assignment operators are used in Python to assign values to variables
Logical Operators
Logical operators are used to combine conditional statements:
and Returns True if both statements are true x < 5 and x < 10
not Reverse the result, returns False if the result is true not(x < 5 and x < 10)
Bitwise Operators
Bitwise operator works on bits and performs bit by bit operation. Assume if a = 60; and
b = 13;
Membership Operators
Python’s membership operators test for membership in a sequence, such as strings, lists, or
tuples.
a = 10
b = 20
list = [1, 2, 3, 4, 5 ]
if ( a in list ):
print ("Line 1 - a is available in the given list")
else:
print ("Line 1 - a is not available in the given list")
if ( b not in list ):
print ("Line 2 - b is not available in the given list")
else:
print ("Line 2 - b is available in the given list")
a=2
if ( a in list ):
print ("Line 3 - a is available in the given list")
else:
print ("Line 3 - a is not available in the given list")
Output:
Line 1 - a is not available in the given list
Line 2 - b is not available in the given list
Line 3 - a is available in the given list
Identity Operators
Identity operators compare the memory locations of two objects.
print(x is z)
print(x is y)
print(x == y)
Output:
True
False
False
Example :
a=10
b=10
if (a is b):
print(True)
else:
print(False)
c=a
print(id(a),id(b),id(c))
a=30
print(id(a))
if (a is c):
print(True)
else:
print(False)
Output:
True
10914784 10914784 10914784 10915424
False
➢ Parameterized functions
➢ Default arguments
➢ Keyword arguments
➢ Variable length arguments
➢ Pass by Reference or pass by value?
➢ Function with return value
1.18. Explain Built-in Functions.
print( ) function
The print() function prints the specified message to the screen or another standard output device.
type( ) function
The type() function returns the type of the specified object.
input( ) function
The input() function allows taking the input from the user.
abs( ) function
The abs() function returns the absolute value of the specified number.
pow( ) function
The pow() function returns the calculated value of x to the power of y i.e, xy.
If a third parameter is present in this function, then it returns x to the power of y, modulus z.
dir( ) function
The dir() function returns all the properties and methods of the specified object, without the
values.
This function even returns built-in properties which are the default for all objects.
sorted( ) function
The sorted() function returns a sorted list of the specified iterable object.
You can specify the order to be either ascending or descending. In this function, Strings are
sorted alphabetically, and numbers are sorted numerically.
reverse Optional. A Boolean. False will sort ascending, True will sort descending. Default is
False
1.19. Give the Steps in Develop a simple python program and execution.
Give the Steps in Develop a simple python program and execution
After writing the code, we need to run the code to execute and obtain the output. On running the
program, we can check whether the code is written is correct and produces the desired output.
Running a python program is quite an easy task.
Run on IDLE
To run a python program on IDLE, follow the given steps −
• Write the python code and save it.
• To run the program, go to Run > Run Module or simply click F5.