0% found this document useful (0 votes)
5 views

PPS UNIT 1.2 Python_Intro

The document provides an overview of Python programming, highlighting its features, uses, and data types. It explains Python's ease of learning, high-level nature, and support for various programming paradigms, including object-oriented and procedural programming. Additionally, it covers Python's history, version releases, and details about literals, variables, and collections such as lists, tuples, sets, and dictionaries.

Uploaded by

aadiprec
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 views

PPS UNIT 1.2 Python_Intro

The document provides an overview of Python programming, highlighting its features, uses, and data types. It explains Python's ease of learning, high-level nature, and support for various programming paradigms, including object-oriented and procedural programming. Additionally, it covers Python's history, version releases, and details about literals, variables, and collections such as lists, tuples, sets, and dictionaries.

Uploaded by

aadiprec
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/ 65

Problem Solving, Programming

and Python Programming

Part 2: Python Programming


 Python is a popular programming language.
 Python is a general-purpose interpreted,
interactive, object-oriented, and high-level
programming language.

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.

2)High level language


Developer no need to bother about stystem arch. and
memory management.

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.

5) Platform Independent Language


Python can run equally on different platforms such
as Windows, Linux, Unix and Macintosh etc.
So, we can say that Python is a portable language.
 Uses PVM to covert code to machine understandable
code.

6) Free and Open Source


Python language is freely available at official web
site.
 The source-code is also available, we can read, modify
its source code. Therefore it is open source.
----S. R. Wakchaure
7) Object-Oriented and Procedural Language
Support
Python supports object oriented language
and concepts of classes and objects come into
existence.
 It supports both the features., we can implement
OOPs features like encapsulation, polymorphism,
inheritance, abstraction.

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.

12) Dynamically typed


 No need to declare type of variable, type is decided at
runtime.
 While assigning value to the variable, type will
allocated automatically.
 Python laid its foundation in the late 1980s.
 The implementation of Python was started in the
December 1989 by Guido Van Rossum at CWI in
Netherland.

 In February 1991, van Rossum published the code


(labeled version 0.9.0) to alt.sources.

 In1994, Python 1.0 was released with new features like:


lambda, map, filter, and reduce.

 Python2.0 added new features like: list


comprehensions, garbage collection system.
Python 2.6 October 1, 2008
Python Version Released Date
Python 1.0 January 1994 Python 2.7 July 3, 2010

Python 1.5 December 31, 1997


Python 3.0 December 3, 2008

Python 1.6 September 5, 2000 Python 3.1 June 27, 2009

Python 2.0 October 16, 2000 Python 3.2 February 20, 2011

Python 3.3 September 29,


Python 2.1 April 17, 2001 2012

Python 2.2 December 21, 2001 Python 3.4 March 16, 2014

Python 2.3 July 29, 2003 Python 3.5 September 13,


2015
Python 2.4 November 30, 2004
Python 3.6 December 23,
2016
Python 2.5 September 19,
2006 Python 3.7 June 27, 2018
Literals can be defined as a data that is given in a variable
or constant.

Python support the following literals:


1. String literals:
String literals can be formed by enclosing a text in
the quotes. We can use both single as well as double
quotes for a String.
e.g
“Ram" , ‘56789‘

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.

There are two ways to create Multiline Strings:

i)Adding black slash at the end of each line.


Eg:
>>> text1=“hello\
user \
Hi”
>>> text1

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.

Numeric literals can belong to following four different


numerical types.

 int(signed integers): Numbers( can be both positive


and negative) with no fractional part.eg: 100

 long(long integers): Integers of unlimited size followed


by lowercase or uppercase L eg: 87032845L

 float(floating point): Real numbers with both integer


and fractional part eg: -26.2

 complex(complex): In the form of a+bj where a forms


the real part and b forms the imaginary part of
complex number. eg: 3.14j
a = 0b1010 #Binary Literals
b = 100 #Decimal Literal
c = 0o310 #Octal Literal
d = 0x12c #Hexadecimal
float_1 = 10.5 #Float Literal
float_2 = 1.5e2
x = 3.14j #Complex Literal
print(a, b, c, d)
print(float_1, float_2)
print(x, x.imag, x.real)

O/P: 10 100 200 300


10.5 150.0
3.14j 3.14 0.0
A Boolean literal can have any of the two values:
True or False.
a=(1==True)
b=(1==False)
c=True+50
d=False+50
print(a)
print(b)
print(c)
print(d)

O/P: True
False
51
50
Python contains one special literal i.e., None.

None is used to specify to that field that is not


created. It is also used for end of lists in
Python.
 Eg:
val1=10
val2=None
Print(val1)
print(val2)

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.

Rules and Naming convention for variables and


Constants:
 Variable names can be both letters in lowercase(a to z)
or uppercase(A to Z) and digits(0 to 9), but they have
to begin with a letter or an underscore(_).
 Don’t start with digit.
 It is recommended to use lowercase letters for variable
name. Rahul and rahul both are two different
variables.
 Use capital letters for constants where possible.
 Never use special symbols like !, @, #, %, ^, &, $ etc.
 E.g
num=40
print(“After declaration value is”,num)
O/P: After declaration value is 40

Changing value of variable:


num=40
print(“Value is”,num)
num=70
print(“After changing value is”,num)
O/P:
 A type of variable whose value can not be changed.
 In python constants usually declared and assigned on a
modules containing variables, functions etc. which is
imported to main file. Inside module, constants are
written in all capital letters and underscores.
Eg:1) save as constant.py
PI=3.14
GR=9.8

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.

Standard data types:


 A variable can hold different types of values. For
example, a person's name must be stored as a string
whereas its id must be stored as an integer.
1. Numbers
2. List
3. Tuple
4. Strings
5. Set
1) Python Numbers:
Number stores numeric value only.

1. int (signed integers like 10, 2, 29, etc.). Integers


can be of any length, it is only limited by the
memory available.
2. long (long integers used for a higher range of
values like 908090800L, -0x1929292L, etc.)L for
long integer
3. float (float is used to store floating point numbers
like 1.9, 9.902, 15.2, etc.). A floating point
number is accurate up to 15 decimal places.
4. complex (complex numbers like 2.14j, 2.0 + 2.3j,
etc.)
 E.g:
a=5
b = 2.0
c = 1+2j
print(a)
print(b)
print(c)

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.

 The only difference is that tuples are immutable.


Tuples once created cannot be modified.

 Tuples are used to write-protect data and are usually


faster than list as it cannot change dynamically.

 It is defined within parentheses () where items are


separated by commas.
tuple=('hi','python1',2)
print(tuple[1:])
print(tuple[0:1])
print(tuple)
print(tuple + tuple)
print(tuple*3)
print (type(tuple))
tuple[2] = 'avcoe'
o/P:
('python1', 2)
('hi',)
('hi', 'python1', 2)
('hi', 'python1', 2, 'hi', 'python1', 2)
('hi', 'python1', 2, 'hi', 'python1', 2, 'hi', 'python1', 2)
<class 'tuple'>

File "D:/AVCOE/PPS 2019-20/Programs/temp1.py", line 8, in


<module>
tuple[2] = 'avcoe '
TypeError: 'tuple' object does not support item assignment
 A string is a sequence of characters
 In python, strings can be created by enclosing the
character or the sequence of characters in the
quotes. Python allows us to use single quotes, double
quotes, or triple quotes to create the string.
 Consider the following example in python to create a
string.
str = "Hi Python !"
+ :It is known as concatenation operator used to join
the strings given either side of the operator .
* :It is known as repetition operator. It concatenates
the multiple copies of the same string.
[] :It is known as slice operator. It is used to access the
sub-strings of a particular string.
 E.g:
str1 ='Hello'
str2 ='world'
print(str1)
print(str2)
print(str1*3) # prints HelloHelloHello
print(str1+str2) # prints Helloworld
print(str1[4]) # prints o
print(str1[2:4]) # prints ll

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)

#print(“Set=”,my_set[1]) --generates error

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())

#print("dict update=", dict[2])# generates error

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)

print("Data type of str1 after Type Casting:",type(str1))

sum = int1 + str1

print("Sum of int1 and str1:", sum)


print("Data type of the sum:",type(sum))

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:

Python print() function prints the given object on the


screen or other standard output devices(screen).

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!")

Multi Line Comments


 Can be given in triple quotes or
# at each line
e.g:
#This is a comment
#written in
#more than just one line
print("Hello, World!")
OR
'''This is a comment
written in
more than just one line'''
print("Hello, World!")
 Keywords are the reserved words in Python.
 We cannot use a keyword as a variable name,
function name or any other identifier. They are
used to define the syntax and structure of the
Python language.
 In Python, keywords are case sensitive.
 There are 33 keywords in Python 3.7. This number
can vary slightly in the course of time.
False class finally is return

None continue for lambda try

True def from nonlocal while

and del global not with

as elif if or yield

assert else import pass

break except in raise


 Most of the programming languages like C,
C++, Java use braces { } to define a block of
code. Python uses indentation.
 A code block (body of a function, loop etc.)
starts with indentation and ends with the
first unindented line. The amount of
indentation is up to you, but it must be
consistent throughout that block.
 Generally four whitespaces are used for
indentation and is preferred over tabs.
 indentation in Python makes the code look
neat and clean. This results into Python
programs that look similar and consistent.
e.g:
if num >= 0:
print("Positive or Zero")
else:
print("Negative number")

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

+ Add two operands x+y

- Subtract right operand from the left x-y

* Multiply two operands x*y

Divide left operand by the right one (always


/ results into float)
x/y

x%y
Modulus - remainder of the division of left
% operand by the right
(remainder
of x/y)

Floor division - division that results into whole


// number adjusted to the left in the number line
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.

Operator Meaning Example

Greater than - True if left operand is greater than the


> x>y
right
< Less than - True if left operand is less than the right x<y
== Equal to - True if both operands are equal x == y
!= Not equal to - True if operands are not equal x != y
Greater than or equal to - True if left operand is
>= x >= y
greater than or equal to the right
Less than or equal to - True if left operand is less than
<= x <= y
or equal to the right
e.g:
x = 10
y = 12
print(x>y)
print(x<y)
print(x==y)
print(x!=y)
print(x>=y)
print(x<=y)
o/p:
x > y is False
x < y is True
x == y is False
x != y is True
x >= y is False
x <= y is True
3. Assignment Operators
Assignment operators are used in Python to
assign values to variables.
Operator Example Equivatent to
= x=5 x=5
+= x += 5 x=x+5
-= x -= 5 x=x-5
*= x *= 5 x=x*5
/= x /= 5 x=x/5
%= x %= 5 x=x%5
//= x //= 5 x = x // 5
**= x **= 5 x=x -
e.g:
a=15
b=3
a+=b #a=a+b
print(a)
a+=4 #a=a+6
print(a)
c=3
d=17
d//=c #d=d//c
print(d)
4) Bitwise operators
 Bitwise operators act on operands as if they were
string of binary digits. It operates bit by bit, hence
the name.
 For example, in binary, 2 is 10 and 7 is 111.

Operator Meaning Example

& Bitwise AND X & y = 0 (0000 0000)

| Bitwise OR x | y = 14 (0000 1110)

~ Bitwise NOT ~x = -11 (1111 0101)

^ Bitwise XOR x ^ y = 14 (0000 1110)

>> Bitwise right shift x>> 2 = 2 (0000 0010)

<< Bitwise left shift x<< 2 = 40 (0010 1000)


e.g:
x=10
y=4
print(x & y)
print(x | y)
print(~x)
print(x ^ y)
print(x >> 2)
print(x << 2)

O/P:??
5) Logical Operators:
Logical operators are the and, or, not operators.
Returns True and False.

Operator Meaning Example

True if both the


and operands are x and y
true
True if either of
or the operands is x or y
true
True if operand is
false
not not x
(complements
the operand)
e.g:
x = True
y = False
print(x and y)
print(x or y)
print(not x)

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

True if the operands are


is identical (refer to the x is True
same object)

True if the operands are


is not not identical (do not refer x is not True
to the same object)
e.g:
x1 = 5
y1 = 5
x2 = 'Hello'
y2 = 'Hello'
x3 = [1,2,3]
y3 = [1,2,3]
print(x1 is y1) ) # Output: True
print(x1 is not y1) # Output: False

print(x2 is y2) # Output: True

print(x3 is y3) # list are mutable so False

x3 and y3, they are equal but not identical. It is


because interpreter locates them separately in memory
although they are equal.

You might also like