PPS UNIT 1.2 Python_Intro
PPS UNIT 1.2 Python_Intro
Uses:
web development (server-side),
software development,
mathematics,
system scripting.
Machine Learning
Data Analysis
Game Development
Embedded Application Development
Desktop Applications
Integrated Lang
Portable
1) Easy to Learn and Use
Python is easy to learn and use. It is developer-friendly.
Easy code compared to Java and C++.
Mandatory indentation, increases readability.
Easy to remember syntax, rules, regulations.
3) Expressive Language
Python language is more expressive means that it is
more understandable and readable.
4) Interpreted Language
That means interpreter executes the code line by line at
a time. This makes debugging easy and thus suitable for
beginners.
In C++,Java you must first compile code then run it.
When we run python application, interpreter checks for
syntax errors, if no then in converts into intermediate
code and execute it.
8) Portable
Its code written for windows can run it on
Mac., for that you don’t need to make changes.
Take code and run on any machine.
8) Large Standard Library Support
Python has a large and broad library and provides
rich set of module and functions for rapid application
development.
Easily add third party libraries in applications.
9) GUI Programming and web application Support
Graphical user interfaces can be developed using
Python.
10) Integrated
It can be easily integrated with languages like C,
C++, JAVA etc.
11) Extensible
Can write some python code in other languages such as
C/C++. It makes python extensible.
Python 2.0 October 16, 2000 Python 3.2 February 20, 2011
Python 2.2 December 21, 2001 Python 3.4 March 16, 2014
Types of Strings:
There are two types of Strings supported in Python:
a)Single line String- Strings that are terminated within a
single line are known as Single line Strings.
Eg:
>>> text1=“hello”
print text1
b)Multi line String- A piece of text that is spread
along multiple lines is known as Multiple line String.
o/p:
Hello user hi
ii)Using triple quotation marks:-
Eg:
>>> str2=“““welcome
to
AVCOE”””
>>> print str2
O/P:
welcome
to
AVCOE
Numeric Literals are immutable means unchangable.
O/P: True
False
51
50
Python contains one special literal i.e., None.
O/P:
10
None
Collections such as List literals, Tuple literals,
Dictionary literals, and set literals are used in Python.
E.g:
l=['aman',678,20.4,'saurav']
t=(1,2,3)
d={‘a’:‘Apple’, ‘b’:‘Basket’}
s={‘a’, ‘e’, ‘i’, ‘o’, ‘u’}
print(l)
print(t)
print(d)
print(s)
O/P:
['aman', 678, 20.4, 'saurav']
(1,2,3)
{‘a’:‘Apple’, ‘b’:‘Basket’}
{‘a’, ‘e’, ‘i’, ‘o’, ‘u’}
Variable is a name which is used to store the data in
the memory.
It holds data which can be changed later throughout
programming.
2)Save as main.py
import constant
print(constant.PI)
print(constant.GR)
O/P: 3.14
9.8
Variables can hold values of different data types.
Python is a dynamically typed language hence we need
not define the type of the variable while declaring it.
The interpreter implicitly binds the value with its type.
Every value in Python has a datatype
Python provides us the type() function which returns
the type of the variable passed.
O/P:
Python List:
List is an ordered sequence of items.
It is one of the most used datatype in Python and is very
flexible.
Lists are similar to arrays in C.
However; the list can contain data of different types.
The items stored in the list are separated with a
comma (,) and enclosed within square brackets [].
We can use slice [:] operators to access the data of the
list. The concatenation operator (+) and repetition
operator (*) works with the list in the same way as they
were working with the strings.
Lists are mutable, value of elements of a list can be
altered.
e.g:
a = [1, 2.2, 'python']
E.g:
list=[1,'hi','python',2]
print(l[3:])
print(list[0:2])
print(list)
print(list+list)
print(list*3)
list[2]='AVCOE'
print("After adding element",list)
O/P:
[2]
[1, 'hi']
[1, 'hi', 'python', 2]
[1, 'hi', 'python', 2, 1, 'hi', 'python', 2]
[1, 'hi', 'python', 2, 1, 'hi', 'python', 2, 1, 'hi', 'python', 2]
After adding element [1, 'hi', 'AVCOE', 2]
Python Tuple:
Tuple is an ordered sequence of items same as list.
O/P:
Hello
world
HelloHelloHello
Helloworld
o
ll
A set is an unordered collection of items. Every
element is unique (no duplicates).
However, the set itself is mutable. We can add or
remove items from it.
Sets can be used to perform mathematical set
operations like union, intersection, symmetric
difference etc.
Items in set are not ordered.
Set defined by values separated by comma inside
braces{ }.
Slicing operator [ ] does not work as indexing.
E.g:
my_set = {1, 2, 3} # set of integers
print(my_set)
my_set = {1.0, "Hello", (1, 2, 3)} #set of mixed datatypes
print(“Set=”,my_set)
O/P:
{1, 2, 3}
{1.0, 'Hello', (1, 2, 3)}
Python dictionary is an unordered collection of
items.
Dictionary has a key: value pair, while other data
types have only value as an element,
Dictionaries are optimized to retrieve values when
the key is known.
In other words, we can say that a dictionary is the
collection of key-value pairs where the value can
be any python object whereas the keys are the
immutable python object, i.e., Numbers, string or
tuple.
Creating the dictionary:
The dictionary can be created by using multiple
key-value pairs and separated by the colon (:).The
collections of the key-value pairs are enclosed
within the curly braces {}.
The syntax to define the dictionary is given below:
dict = {"Name": "Ayush","Age": 22}
E.g:
dict={"Name": "John", "Age": 29,
"salary":25000,"Company":"GOOGLE"}
print("printing Employee data .... ")
print("Value of Key Name:", dict["Name"])
print("Value of Key Age :",dict["Age"])
print("All keys", dict.keys())
print("All values", dict.values())
O/P:
printing Employee data ....
Value of Key Name: John
Value of Key Age : 29
All keys dict_keys(['Name', 'Age', 'salary', 'Company'])
All values dict_values(['John', 29, 25000, 'GOOGLE'])
type() function:
-type() function returns the type of the variable passed.
e.g:
list = [4, 5]
dict={4: 'four', 5: 'five'}
my_set={1.0, "Hello", (1, 2, 3)}
str1 ='Hello' O/P:
tuple1=('hi','python1',2) <class 'list'>
num_int=10 <class 'dict'>
num_float=12.6 <class 'set'>
print(type(list)) <class 'str'>
<class 'tuple'>
print(type(dict)) <class 'int'>
print(type(my_set)) <class 'float'>
print(type(str1))
print(type(tuple1))
print(type(num_int))
print(type(num_float))
Using different type conversion functions like int(),
float(), str()
a=10 O/P:
10 into float 10.0
print(“10 into float”, float(a))
b=10.8
O/P:
print(“10.8 into int”, int(b)) 10.8 into int 10
c=“50”
d=“20.4” O/P:
string to int is 50
print(“string to int is”, int(c)) string to float is 20.4
print(“string to float is ”, float(d))
Type Conversion:
The process of converting the value of one data
type (integer, string, float, etc.) to another data
type is called type conversion.
Python has two types of type conversion:
1. Implicit Type Conversion
2. Explicit Type Conversion
1. Implicit Type:
In Implicit type conversion, Python automatically
converts one data type to another data type. This
process doesn't need any user involvement.
Python promotes conversion of lower datatype
(integer) to higher data type (float) to avoid data
loss.
e.g:
num_int = 123
num_float = 1.23
num_new = num_int + num_float
print("datatype of num_int:",type(num_int))
print("datatype of num_flo:",type(num_flo))
print("Value of num_new:",num_new)
print("datatype of num_new:",type(num_new))
O/P:
datatype of num_int: <class 'int'>
datatype of num_flo: <class 'float'>
Value of num_new: 124.23
datatype of num_new: <class 'float'>
2. Explicit Type Conversion:
In Explicit Type Conversion, user convert the data
type of an object to required data type. We use the
predefined functions like int(), float(), str(), etc to
perform explicit type conversion.
This type conversion is also called typecasting
because the user casts (change) the data type of
the objects.
Syntax :
(required_datatype)(expression)
E.g:
int1 =105
str1 ="100"
print("Data type of int1 is:",type(int1))
print("Data type of str1 before Type Casting:",type(str1))
str1 = int(str1)
O/P:
Data type of int1 is: <class 'int'>
Data type of str1 before Type Casting: <class 'str'>
Data type of str1 after Type Casting: <class 'int'>
Sum of int1 and str1: 205
Data type of the sum: <class 'int'>
Input Output Operation:
Python input:
Input() function used to take input from user.
It prompts for the user input and reads a line. After
reading data, it converts it into a string and returns
that. It throws an error EOFError if EOF is read.
Syntax: input ([prompt])
prompt: It is a string message which prompts for the user
input.
e.g1:
name = input("Enter your name: ")
print("You entered:",name)
O/P:
Enter a value: Ram
You entered: Ram
e.g:
val = int(input("Enter an integer"))
sqr = val*val
print("Square of the value:",sqr)
O/P:
Enter an integer 10
Square of the value: 100
Python Output:
Syntax:
print(object(s), sep=separator, end=end, file=file, fl
ush=flush)
e.g:
a=10
print(“number is”,a)
Comments can be used to explain Python
code.
Comments can be used to make the code
more readable.
Comments can be used to prevent execution
when testing code.
In Python, we use the hash (#) symbol to
start writing a comment.
Eg:
print("Hello, World!") #This is a comment
e.g:
#This is a comment
print("Hello, World!")
as elif if or yield
O/P:??
2)
if a>b:
print(“a is greater”)
else:
print(“b is greater”)
O/P??
Operators are special symbols in Python that carry
out arithmetic or logical computation.
The value that the operator operates on is called
the operand.
1. Arithmetic operators
2. Comparison operators
3. Assignment Operators
4. Logical Operators
5. Bitwise Operators
6. Membership Operators
7. Identity Operators
1) Arithmetic operators
Arithmetic operators are used to perform
arithmetic operations between two operands.
It includes +(addition), - (subtraction),
*(multiplication), /(divide), %(reminder),
//(floor division), and exponent (**)
E.g:
c=a+b
Or
c=20-10
Operator Meaning Example
x%y
Modulus - remainder of the division of left
% operand by the right
(remainder
of x/y)
x**y (x to
Exponent - left operand raised to the power of
** right
the power
x = 15
y=4
print(x+y)
print(x-y)
print(x*y)
print(x/y)
print(x//y)
print(x**y)
O/P:
x + y = 19
x - y = 11
x * y = 60
x / y = 3.75
x // y = 3
x ** y = 50625
2) Comparison operators
Comparison operators are used to compare values.
It either returns True or False according to the
conditi
on.
O/P:??
5) Logical Operators:
Logical operators are the and, or, not operators.
Returns True and False.
E.g:
age=25
if age<33 and age>20:
print ("Young Man")
else:
print(" Not Eligible ")
Membership operators
in and not in are the membership operators in
Python. They are used to test whether a value or
variable is found in a sequence (string, list,
tuple,set and dictionary).
In a dictionary we can only test for presence of
key, not the value.
Operator Meaning Example
True if
value/variable is
in 5 in x
found in the
sequence
True if
value/variable is
not in 5 not in x
not found in the
sequence
x = "Hello world"
y= (2,9,7,8)
z = {1:"apple", 2:"basket"}
print('H' in x)
print('hello' not in x)
print(7 in y)
print(4 not in y)
print(1 in z)
print('apple' in z)
7) Identity operators
is
and is not are the identity operators in Python.
They are used to check if two values (or variables)
are located on the same part of the memory. Two
variables that are equal does not imply that they
are identical.
Operator Meaning Example