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

AR20 Python Unit-I

Uploaded by

guderaj1818
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
14 views

AR20 Python Unit-I

Uploaded by

guderaj1818
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 71

RAGHU ENGINEERING COLLEGE

Python
Programming
Unit-I

Python Programming Raghu Engineering College 1


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

• It was created by Guido van Rossum during 1985- 1990.

• Python is designed to be highly readable.

• It uses English keywords frequently where as other languages use


punctuation, and it has fewer syntactical constructions than
other languages.

Python Programming Raghu Engineering College 2


Prerequisites
• You should have a basic understanding of Computer Programming
terminologies.

• A basic understanding of any of the programming languages is


a plus.

Raghu Engineering College


Python Programming 3
Need of Python Programming
• Python is Interpreted

• Python is Interactive

• Python is Object-Oriented

• Python is a Beginner's Language

• Easy-to-learn

• Easy-to-read

• Easy-to-maintain

Python Programming Raghu Engineering College 4


Python Features
• A broad standard library

• Interactive Mode

• Portable

• Extendable

• Databases

• GUI Programming

• Scalable

Python Programming Raghu Engineering College 5


Applications for Python

• Web Application Development:

– Python can be used to build server-side web applications.

– most Python developers write their web applications


using a combination of Python and JavaScript.

– Python is executed on the server side while


JavaScript is downloaded to the client and run by the web
browser.

Python Programming Raghu Engineering College Slide 6


Applications for Python

• Scientific and Numeric Computations:


– Python has specialized modules, like Numpy, Scipy, Matplotlib,
Pandas and so on, - an ideal programming language for
solving numerical problems.
– Furthermore, the community of Python is a lot larger and faster
growing than other relative technologies like R and
MATLAB.
– Python is completely free, whereas MATLAB can be very
expensive.
– Python is not only free of costs, but its code is open source.
Python is continually becoming more powerful by a
rapidly growing number of specialized modules.

Python Programming Raghu Engineering College Slide 7


Applications for Python

• Education:
– Python offers an interactive environment in which to explore
procedural, functional and object oriented
approaches to problem solving.

– Its high level data structures and clear syntax make it an ideal
first language, while the large number of existing
libraries make it suitable to tackle almost any programming
tasks.

Python Programming Raghu Engineering College Slide 8


Applications for Python
• Graphical User Interface:

– Tkinter is the standard GUI library for Python. Python when


combined with Tkinter provides a fast and easy way to
create GUI applications.

– Tkinter provides a powerful object-oriented interface to the Tk


GUI toolkit.

– Tkinter provides various controls, such as buttons, labels and


text boxes used in a GUI application. These
controls are commonly called widgets.

Python Programming Raghu Engineering College Slide 9


Applications for Python
• Software Development:

– Python is used by top Multi National Companies like google.

– Pinterest and Instagram have been built with Python.

– With built-in list and dictionary data structures, Python is used


for building fast runtime data structures.

– This programming language offers enhanced process control


capabilities and can be used for developing complex
multi- protocol network applications.

Python Programming Raghu Engineering College Slide 10


Applications for Python

• Business Applications:

– Python is also used to build ERP and e-commerce systems:

– Odoo is an all-in-one management software built using python,


that offers a range of business applications that form a
complete suite of enterprise management applications.

Python Programming Raghu Engineering College Slide 11


Using the REPL(Shell)
• A Read–Eval–Print Loop (REPL), also known as an interactive
top-level or language shell.

• It is a simple, interactive computer programming environment that


takes single user inputs (i.e. single expressions), evaluates
them, and returns the result to the user;

• A program written in a REPL environment is executed piecewise.

• Python can be downloaded from


shell
https://www.python.org/downloads

Python Programming Raghu Engineering College 12


Using the REPL(Shell)
A sample screenshot of python Shell:

Python Programming Raghu Engineering College 13


Running Python Scripts
• In python shell, we execute programs piece wise, but we can also
execute entire script at once.

• In python shell goto File - > New File, a new empty


editor pops up in which we can write python scripts.

• After writing entire script save it by using .py extension.

• Then this script can be executed by pressing F5 button or


by clicking on run button from the editor.

Python Programming Raghu Engineering College 14


Running Python Scripts
A sample screenshot of writing entire script in python

Python Programming Raghu Engineering College 15


Basics of Python Programming

print() function:

To Display some message as output, we use print() function:


print(“Hello World”)

Note: Do not use any semi colon “ ; ” at the end of a


statement.

Python Programming Raghu Engineering College 16


Python Variables
Identifier:
• A Python identifier is a name used to identify a variable, function,
class, module or other object.

• An identifier starts with a letter A to Z or a to z or an underscore


(_) followed by zero or more letters, underscores and digits
(0 to 9).

• Python does not allow punctuation characters such as @, $, and %


within identifiers.

• Python is a case sensitive programming language.

Python Programming Raghu Engineering College 17


Variables
• Variables are nothing but reserved memory locations to store
values.

• This means that when you create a variable you reserve some
space in memory.

• In python, variables need not be declared with a data type.

• Ex: x=5
• Here x is a variable which stores value 5.

Python Programming Raghu Engineering College 18


Naming conventions
• Class names start with an uppercase letter. All other identifiers
start with a lowercase letter.

• Starting an identifier with a single leading underscore indicates


that the identifier is private.

• Starting an identifier with two leading underscores


indicates a strongly private identifier.

• If theidentifier also ends with two trailing underscores,


the
identifier is a language-defined special name.

Python Programming Raghu Engineering College 19


Assignment
• Python variables do not need explicit declaration to
reserve memory space.

• The declaration happens automatically when you assign a value


to a variable.

• The equal sign (=) is used to assign values to variables.

• The operand to the left of the = operator is the name of the


variable and the operand to the right of the = operator is the value
stored in the variable.

Python Programming Raghu Engineering College 20


Assignment Contd.

• You can print the variables as below,


print(counter)
print(miles)
print(name)

Python Programming Raghu Engineering College 21


Multiple Assignment
• Python allows you to assign a single value to several
variables simultaneously.
For example : a = b = c = 1

• You can also assign multiple objects to multiple variables.


For example : a,b,c = 1,2,"john"

Python Programming Raghu Engineering College 22


Keywords

• There are several reserved words and you cannot use them
as constant or variable or any other identifier names.
• All the Python keywords contain lowercase letters only.
and def exec if not return

assert del finally import or try

break elif for in pass while

class else from is print with

continue except global lambda raise yield

Python Programming Raghu Engineering College 23


Input - Output

• To read input entered by user, we use input() function.

• Example: x = input()

• The value entered by user is assigned to variable x.

• The default data type returned by input() function is string,


so whatever user enters, it is taken as string only.

Python Programming Raghu Engineering College 24


Input - Output

• To display a prompt message to the user while reading


input we use input() function as follows:

• Example: x = input(“enter some value: ”)

Python Programming Raghu Engineering College 25


Input - Output

• To display value of a variable as output, we can use print()


function as below:

• Example: print(x)

• Displays value of x as output.

Python Programming Raghu Engineering College 26


Data
Types
Basic Data Types of Python:
• Numbers
» int
»
long
»
Float
»
complex
• Strings
• Boolean

Python Programming Raghu Engineering College Slide 27


Data Types - Numbers
• Number data types store numeric values.

• Python supports four different numerical types :


– int (signed integers)
– long (long integers, they can also be represented in octal
and hexadecimal)
– float (floating point real values)
– complex (complex numbers)

Python Programming Raghu Engineering College 28


Data Types - Numbers
In python 3, int and long have been merged and treated similarly

Example:
x = 123456789012345678901234567890
y=1
Print(x+y)

Output:
12345678901234
56789012345678
91

Python Programming Raghu Engineering College 29


Data Types – using format
specifiers for number
s
Using more format specifiers in same
int – %d, float - %f print() function:

Program: Program:
n=12 n=12
print("value of n is %d"%n) m=13.56
print("value of n is %f"%n) print("va
lues are
%d,
Sample input output: %f"%
value of n is 12 (n,m))
value of n is 12.000000
Sample
input
output:
values
Python Programming Raghu Engineering College 30
are
Data Types – Restricting
Number of Decimal
• places
We can restrict the number of decimal places in floating
point values by using %.nf.
• Substitute some value in place of n.

Program:
x=15.123456789
y=15.149
print("x is %.2f
and y is %.5f"%
(x,y))

Sample input
output:
Python Programming Raghu Engineering College 31
x is 15.12 and y
Data Types - Strings
• Strings in Python are identified as a contiguous set of characters
represented in the quotation marks.

• Python allows for either pairs of single or double quotes.

• In python, there is no separate data type for character. A


String
with length 1 is treated as a character.

Python Programming Raghu Engineering College 32


Data Types – format specifiers for
strings
Format specifier for string - %s

Program:
s1="hello"
s2="world"
print("first
string is
%s and
second
string is
%s"%
(s1,s2))

Slide 33
Sample
Python Programming Raghu Engineering College
Data Types - Boolean
• Boolean values are the two constant objects False and True.

• They are used to represent truth values (other values can also be
considered false or true).

• In numeric contexts (for example, when used as the argument to an


arithmetic operator), they behave like the integers 0 and
1, respectively.

Python Programming Raghu Engineering College 34


Data Types - Boolean

Format Specified for


boolean: %r
Program:
Program: x=(5==5)
x=(5==10) print("x is %r"%x)
print("x is %r"%x)
Sample Input Output:
Sample Input Output: x is True
x is False

Python Programming Raghu Engineering College 35


Data Type Conversion
• Sometimes, you may need to perform conversions between
the built-in types.

• To convert between types, you simply use the type name as


a function.

• There are several built-in functions to perform conversion


from one data type to another.

• These functions return a new object representing the converted


value.

Python Programming Raghu Engineering College 36


Data Type Conversion
• int(x [,base]) Converts x to an integer. Base specifies the base
of x before conversion.

• long(x [,base] ) Converts x to a long integer. Base specifies base of x


before conversion.

• float(x) Converts x to a floating-point number.

• complex(real [,imag]) Creates a complex number.

• str(x) Converts object x to a string representation.

• chr(x) Converts an integer to a character.

Python Programming Raghu Engineering College Slide 37


Data Type Conversion -
Examples
Program: Program:
x="25" x="10101"
n=int(x) n=int(x,2)
print(n) print(n)

Sample Sample
input input
output: output:
25 21

Python Programming Raghu Engineering College Slide 38


Data Type Conversion -
Examples
Program: Program:
c=complex(10,20) c=chr(97)
print(c) print(c)

Sample input Sample


output: input
(10+20j) output:
a

Python Programming Raghu Engineering College Slide 39


OPERATORS
•Arithmetic Operators

•Comparison (Relational) Operators

•Assignment Operators

•Logical Operators

•Bitwise Operators

•Membership Operators

•Identity Operators

Python Programming 40
Arithmetic Operators

Python Programming Raghu Engineering College 41


Comparison
Operators

Python Programming Raghu Engineering College 42


Assignment Operators
• = Assigns value of right side expression to left side
operand. Ex: z = x+y

• Assignment operator can be combined with arithmetic operators


as a+=b which is equivalent to a=a+b

Python Programming Raghu Engineering College 43


Logical Operators

Python Programming Raghu Engineering College 44


Logical Operators

Python Programming Raghu Engineering College 45


Bitwise
Operators

Python Programming Raghu Engineering College 46


Bitwise Operators
Bitwise operator works on bits and performs bit by bit operation.
Assume if a = 60; and b = 13; Now in binary format they will be
as follows −
• a = 0011 1100
• b = 0000 1101

• a&b = 0000 1100


• a|b = 0011 1101
• a^b = 0011 0001
• ~a = 1100 0011

Python Programming Raghu Engineering College 47


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.

Python Programming Raghu Engineering College 48


Membership Operators
• x = 'Hello world‘
• y = {1:'a',2:'b'}

• print('H' in x) # Output: True


• print('hello' not in x) # Output: True
• print(1 in y) # Output: True
• print('a' in y) # Output: False

Python Programming Raghu Engineering College 49


Identity Operators

Python Programming Raghu Engineering College 50


Identity Operators
x1 = 5
y1 = 5
x2 = 'Hello‘
y2 = 'Hello‘
print(x1 is # Output: False
not y1)
Here, we see that x1 and y1 are integers of same values, so they
are equal as well as identical. Same is the case
with x2 and y2 (strings).

print(x2 is y2) # Output: True

Python Programming Raghu Engineering College 51


Identity Operators

x3 = [1,2,3]
y3 = [1,2,3]
print(x3 is y3) # Output: False

But x3 and y3 are lists. They are equal but not identical. Since lists
are mutable (can be changed), interpreter locates them separately
in memory although they are equal.

Python Programming Raghu Engineering College 52


Slice Operator
The slice operator [n:m] returns the part of the string from the
n’th character to the m-1’th character, including the first but
excluding the last.
singers = "Peter, Paul, and Mary"
print(singers[7:11])
Output: Paul

fruit = "banana"
print(fruit[:3]) # outputs ban
print(fruit[3:]) # outputs ana

Python Programming Raghu Engineering College 53


Slice Operator

• We can easily extract the elements of a list with even


indices: L[::2]
This will extract the elements at indices 0, 2,
4, 6,... Up to the end of list

• To reverse a given list we can use L[::-1]

Python Programming Raghu Engineering College 54


Expressions and order of
evaluations
• The combination of values, variables, operators and function calls
is termed as an expression.

• To evaluate expressions, there is a rule of precedence in Python. It


guides the order in which operations are carried out.

• The operator precedence in Python is listed in the table shown in


next 2 slides.

• It is in descending order, upper group has higher precedence than


the lower ones.

Python Programming Raghu Engineering College 55


Operator Precedence table Part
1/2

Python Programming Raghu Engineering College 56


Operator Precedence table Part
2/2

Python Programming Raghu Engineering College 57


• WhenAssociativity
two operators have theof
samePython
precedence, associativity
helpsOperators
to determine which operator should be evaluated first.

• Associativity is the order in which an expression is evaluated


that has multiple operators of the same precedence.

• For example, multiplication and floor division have the same


precedence. Hence, if both of them are present in an expression,
left one evaluates first.

• Almost all the operators in python have left-to-right


associativity.

Python Programming Raghu Engineering College 58


Associativity of Operators -
Examples

Program: Program:
print(7//2*6) print(6*7//2)

Sample input output: Sample input output:


18 21

Python Programming Raghu Engineering College 59


Associativity of Python
Operators
• Exponent operator ** has right-to-left associativity in python.

• Example: 2**3**2 is evaluated as 2**(3**2) but not


(2**3)**2

Program:
print(2**3**2)

Sample input output:


512

Python Programming Raghu Engineering College 60


Strings
• Python strings are immutable. In simple words, a mutable object
can be changed after it is created, and an immutable object
cannot be changed.

• Consider the following code:


s="abcdef"
s[2]='d'
print(s)

• For this code, we will get an


error saying:
“ 'str' object does not support item assignment “, so s cannot
be modified.

Python Programming Raghu Engineering College 61


Strings
The isalpha() method returns True if all characters in the string are
alphabets. If not, it returns False.

name = “raghu“
print(name.isalpha()) #returns true

name = “raghu engineering“


print(name.isalpha()) #returns false

name = “ab3cd22er“
print(name.isalpha()) #returns false

Python Programming Raghu Engineering College 62


Strings
The isdigit() method returns True if all characters in a string are
digits. If not, it returns False.

s = "28212“
print(s.isdigit()) #returns true

s = "Mo3 nicaG el l22er“


print(s.isdigit()) #returns
false

Python Programming Raghu Engineering College 63


Strings
.upper() & .lower()
Performing the .upper() method on a string converts all of the
characters to uppercase, whereas the lower() method converts all of
the characters to lowercase.

s = “CoMpUteR”
s.upper() # converts characters in s to “COMPUTER”
s.lower() # converts characters in s to “computer”

Python Programming Raghu Engineering College 64


Strings
swapcase()
Swaps the case of each character in a string i.e., it converts lower
case characters to upper case and vice versa.

s = “CoMpUteR”
s.swapcase() # converts characters in s to
“cOmPuTEr”

Python Programming Raghu Engineering College 65


String
String
islower(): ss
Returns True if all the characters in a string are in lower case and false
otherwise:
s = “aBcD”
s.islower() # returns false

s = “abcd”
s.islower() # returns True

s = “abcd4”
s.islower() # returns True

Python Programming Raghu Engineering College 66


String
String
isupper():
ss
Returns True if all the characters in a string are in upper case and
false
otherwise:
s = “aBcD”
s.isupper() # returns false

s = “ABCD”
s.isupper() # returns True

s = “ABCD4”
s.isupper() # returns True

Python Programming Raghu Engineering College 67


String
String
Concatenating Strings: ss
+ operator can be used to concatenate two strings in python.

s1 = “hello”
s2 = “world”
s1 + s2 #contains “helloworld”

print(‘abc’ + ‘def’) # prints abcdef

print(‘abc’*3) # prints abcabcabc

print(‘abc’ + 3) # type error because ‘abc’


# is string and 3 is int

Python Programming Raghu Engineering College 68


String
String
ASCII value of characters ss
Python has a very simple way to convert text to ASCII and ASCII
to text.

• To find the ASCII value of a character use the ord() function.


Example:
print(ord('B'))
# Prints 66

• To get a character from it's ASCII value use the chr() function.
Example:
print(chr(65))
# Prints 'A'

Python Programming Raghu Engineering College 69


String Handling
Functions
Python String capitalize()
Converts first character to Capital Letter
string.capitalize()
returns occurrences of substring in string
Python String count()
string.count(substring, start=..., end=...)
Checks if String Ends with the Specified Suffix
Python String endswith()
str.endswith(suffix)
Returns the Lowest Index of Substring
Python String find()
str.find(sub)
Returns Index of Substring
Python String index()
str.index(sub[, start[, end]] )
Checks Alphanumeric Character
Python String isalnum()
string.isalnum()
Checks Decimal Characters
Python String isdecimal()
string.isdecimal()
Checks for Valid Identifier
Python String isidentifier()
string.isidentifier()
Checks for Titlecased String
Python String istitle()
string.istitle()
Python Programming Raghu Engineering College

70
String Handling
Functions
Python String join()
Returns a Concatenated String
string.join(str)
separator.join(iterable)

Python String lstrip() Removes Leading spaces: string.lstrip()

Python String rstrip() Removes Trailing spaces: string.rstrip()

Python String strip() Removes Both Leading and Trailing spaces: string.strip()

Python String replace() Replaces Substring Inside: str.replace(old, new [, count])

Python String rfind() Returns the Highest Index of Substring: str.rfind(sub[, start[, end]] )

Python String rindex() Returns Highest Index of Substring: str.rindex(sub[, start[, end]] )

Python String split() Splits String from Left: str.split([separator])

Checks if String Starts with the Specified String


Python String startswith()
str.startswith(prefix[, start[, end]])

Python String title() Returns a Title Cased String: str.title()

Python len() Returns Length of an Object: len(s)

Python Programming Raghu Engineering College 71

You might also like