[Go to site: main page, start]

0% found this document useful (0 votes)
8 views69 pages

Python Unit 1

The document provides an introduction to Python programming, covering basics such as data types, variables, control structures, and expressions. It explains the use of Python IDEs, particularly IDLE, and details various programming concepts including statements, expressions, and type casting. Additionally, it outlines different types of operators and control statements in Python, including sequential, selection, and decision control statements.

Uploaded by

eluriakshara
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)
8 views69 pages

Python Unit 1

The document provides an introduction to Python programming, covering basics such as data types, variables, control structures, and expressions. It explains the use of Python IDEs, particularly IDLE, and details various programming concepts including statements, expressions, and type casting. Additionally, it outlines different types of operators and control statements in Python, including sequential, selection, and decision control statements.

Uploaded by

eluriakshara
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

NAYANI SATEESH REDDY

[Link]. (AMIE - CSE), [Link]. (CSE/WT) [Link].(CS) (Ph.D. – JNTUK)


UGC – NET (Computer Science & Applications)
SLET – TS&AP (Computer Science & Applications)

AICTE-NPTEL – Data Science Domain Certified Faculty.


Infosys-Campus Connect (“Bronze Level Partner Faculty”)

Disclaimer : All the contents presented in this PPT are based on resources available
on the internet. Original copyrights are reserved for the respective content
contributors on the internet. This Presentation is used for knowledge-sharing
purposes only and also for the benefit of the students
Unit I – Introduction to Python

Python Basics – Python Interpreter and IDLE environment,


Basic Data Types, Variables, statements, expressions, Operators,
Strings,

Control Structures – Branching and looping structures,


Simple programs.
Python Basics
Python is one of the most versatile programming languages used by
developers, data analysts, and other professionals. At the heart of this
incredible language is the Python interpreter.

Interpreters translate source code one statement at a time. On the


other hand, the compiler first scans the entire program and then
translates the whole program into machine code.
Introduction to Programming
with Python
Python IDEs
Python – IDLE

IDLE (Integrated Development and Learning Environment) is an integrated development


environment (IDE) for Python. It can be used to execute a single statement just like
Python Shell and also to create, modify, and execute Python scripts.

IDLE provides a fully-featured text editor to create Python script that includes features
like syntax highlighting, auto completion, and smart indent. It also has a debugger with
stepping and breakpoints features.

IDLE works more like a terminal or command prompt


Single line comment in python

#This is a single line comment in python


print(“hello world") #This is also a python comment

Multi-line comment in python

Method 1:
#This is a multiline comment in python
#which expands to more than one line
print(“hello world")

Method 2:
''‘This is a multiline comment in python
which expands to many lines''‘
print(“hello world")
Input in python

input(prompt)

print('Enter your name:')


x = input()
print('Hello, ' + x)

OR
x = input('Enter your name:')
print('Hello, ' + x)
Output /Print in python

print(object(s), sep=separator, end=end, file=file, flush=flush)


Formatting output using String modulo operator(%) :

The general syntax for a format placeholder is:

%[flags][width][.precision]type

# Python program showing how to use string modulo operator(%) to print


# fancier output

# print integer and float value


print(“Hello : %2d, Portal : %5.2f" % (1, 05.333))

# print integer value


print("Total students : %3d, Boys : %2d" % (240, 120))

# print octal value


print("%7.3o" % (25))

# print exponential value


print("%10.3E" % (356.08977))
A variable is a reserved memory location to store values.

Every variable in Python is an object. variables are a


symbolic name that is a reference or pointer to an object.

Every value in Python has a data type. Different data types in


Python are Numbers, List, Tuple, Strings, Dictionary, etc.
Variable Naming Rules in Python

•Variable name should start with letter(a-zA-Z) or underscore (_)

•In variable name, no special characters allowed other than underscore (_)

•Variables are case sensitive

•Variable name can have numbers but not at the beginning

•Variable name should not be a Python keyword/ reserved words


Data types in Python
Data types in Python
Variable declaration
Variable Assignment :: some special cases

a,b=2,3
Here a is assigned with 2 and b is assigned with 3

a,b=b,a
Here a,b values will be swapped. Now a has 3 and b has 2.
Type Casting is the method to convert the variable data type into a certain
data type in order to the operation required to be performed by users.

There can be two types of Type Casting in Python –


•Implicit Type Casting
•Explicit Type Casting

# Python program to demonstrate implicit type Casting

# Python automatically converts


a = 7 # a to int

# Python automatically converts


b = 3.0 # b to float

# Python automatically converts


c = a + b # c to float as it is a float addition

print(a,type(a))
print(b,type(b))
print(c,type(c))
# Python program to demonstrate Explicit type Casting

# int variable
a=5
print(type(a))

# typecast to float
n = float(a)

print(n)
print(type(n))
Any Instruction that a python interpreter can execute (carry out) is called a
Statement.

A Statement is the smallest executable unit of code that has an effect, like
creating a variable or displaying a value.

x=3 #Assignment Statement


print(x) #Print Statement

An Expression is a sequence or combination of values, variables, operators


and function calls that always produces or returns a result value.

x=5 y=3z=x+y

In the above example x, y and z are variables, 5 and 3 are values, = and + are
operators.
So, the first combination x = 5 is an expression, the second combination y =
3 is an another expression and at last, z = x + y is also an expression.
Types of statements in Python

A statement is an instruction that a Python interpreter can execute. The different


types of Python statements are listed below:

Multi-Line Statements

Python Conditional and Loop Statements


Python If-else
Python for loop
Python while loop
Python try-except
Python with statement
Python Expression statements
Python pass statement
Python del statement
Python return statement
Python import statement
Python continue and
Python break statement
[Link]
Multi-Line Statements
Python statement ends with the token NEWLINE character. But we can extend
the statement over multiple lines using line continuation character (\).
This is known as an explicit continuation.

addition = 10 + 20 + \
30 + 40 + \
50 + 60 + 70
print(addition)
# Output: 280

Implicit continuation:
We can use parentheses () to write a multi-line statement.
We can add a line continuation statement inside it.
Whatever we add inside a parentheses () will treat as a single statement
even it is placed on multiple lines.
addition = (10 + 20 +
30 + 40 +
50 + 60 + 70)
print(addition)
# Output: 280
Multi-Line Statements
We can use square brackets [] to create a list. we can place each list item on a
single line for better readability.

Same as square brackets, we can use the curly { } to create a dictionary with every
key-value pair on a new line for better readability.
# list of strings
names = ['Emma',
‘Kelly',
'Jessa']
print(names)

# dictionary name as a key and mark as a value # string:int

students = {'Emma': 70,


'Kelly': 65,
'Jessa': 75}
print(students)

['Emma', 'Kelly', 'Jessa']


{'Emma': 70, 'Kelly': 65, 'Jessa': 75}
Python try-except

try:
# Some Code
except:
# Executed if error in the try block

x,y=3, 0
try:
# Floor Division : Gives only Fractional Part as Answer
result = x // y
print("Yeah ! Your answer is :", result)
except ZeroDivisionError:
print("Sorry ! You are dividing by zero ")
Python with statement

# using with statement


with open('file_path', 'w') as file:
[Link]('hello world !')

Python del statement

my_variable1 = 20
print(my_variable1) # check if my_variable1 exists

# delete the variables


del my_variable1

print(my_variable1) # check if my_variable1 exists

20
NameError: name 'my_variable1' is not defined
Python import statement

import math
pie = [Link]
print("The value of pi is : ",pie)

The value of pi is : ', 3.141592653589793


Expressions in Python
A combination of operands and operators is called an expression. The
expression in Python produces some value or result after being interpreted
by the Python interpreter. An expression in Python is a combination of
operators and operands.

Types of Expression in Python


We have various types of expression in Python, let us discuss them along with
their respective examples.

1. Constant Expressions
2. Arithmetic Expressions
3. Integral Expressions
4. Floating Expressions
5. Relational Expressions
6. Logical Expressions
7. Bitwise Expressions
8. Combinational Expressions
1. Constant Expressions
A constant expression in Python that contains only constant values is known as a constant
expression. In a constant expression in Python, the operator(s) is a constant. A constant is a
value that cannot be changed after its initialization.

x = 10 + 15 # Here both 10 and 15 are constants but x is a variable.


print("The value of x is: ", x)

The value of x is: 25


2. Arithmetic Expressions
An expression in Python that contains a combination of operators, operands, and
sometimes parenthesis is known as an arithmetic expression. The result of an
arithmetic expression is also a numeric value just like the constant expression

x = 10
y=5
addition = x + y
subtraction = x - y
product = x * y
division = x / y
power = x**y
print("The sum of x and y is: ", addition)
print("The difference between x and y is: ", subtraction)
print("The product of x and y is: ", product)
print("The division of x and y is: ", division)
print("x to the power y is: ", power)

The sum of x and y is: 15


The difference between x and y is: 5
The product of x and y is: 50
The division of x and y is: 2.0
x to the power y is: 100000
3. Integral Expressions

An integral expression in Python is used for computations and type conversion


(integer to float, a string to integer, etc.). An integral expression always produces
an integer value as a resultant.

x = 10 # an integer number
y = 5.0 # a floating point number
# we need to convert the floating-point number into an integer or vice versa for
summation.

result = x + int(y)
print("The sum of x and y is: ", result)

The sum of x and y is: 15


4. Floating Expressions

A floating expression in Python is used for computations and type conversion


(integer to float, a string to integer, etc.). A floating expression always produces a
floating-point number as a resultant.

x = 10 # an integer number
y = 5.0 # a floating point number
# we need to convert the integer number into a floating-point number or vice versa
for summation.

result = float(x) + y
print("The sum of x and y is: ", result)

The sum of x and y is: 15.0


5. Relational Expressions

A relational expression in Python can be considered as a combination of two or


more arithmetic expressions joined using relational operators. The overall
expression results in either True or False (boolean result). We have four types of
relational operators in Python (i.e.>,<,>=,<=)(i.e.>,<,>=,<=).
A relational operator produces a boolean result so they are also known as Boolean
Expressions.

a = 25
b = 14
c = 48
d = 45
# The expression checks if the sum of (a and b) is the same as the difference of (c
and d).

result = (a + b) == (c - d)
print("Type:", type(result))
print("The result of the expression is: ", result)

Type: <class 'bool'> The result of the expression is: False


6. Logical Expressions

As the name suggests, a logical expression performs the logical computation, and
the overall expression results in either True or False (boolean result).

x = (10 == 9)
y = (7 > 5)

and_result = x and y
or_result = x or y
not_x = not x

print("The result of x and y is: ", and_result)


print("The result of x or y is: ", or_result)
print("The not of x is: ", not_x)

The result of x and y is: False


The result of x or y is: True
The not of x is: True
7. Bitwise Expressions
The expression in which the operation or computation is performed at the bit level
is known as a bitwise expression in Python. The bitwise expression contains the
bitwise operators.

x = 25

left_shift = x << 1
right_shift = x >> 1

print("One right shift of x results: ", right_shift)


print("One left shift of x results: ", left_shift)

One right shift of x results: 12


One left shift of x results: 50
8. Combinational Expressions
As the name suggests, a combination expression can contain a single or multiple
expressions which result in an integer or boolean value depending upon the
expressions involved.

x = 25
y = 35
result = x + (y << 1)
print("Result obtained : ", result)

Result obtained: 95
Expression Statement
An expression evaluates to a A statement executes
value something
The evaluation of a
statement does not changes The execution of a statement
state changes state
Execution of a statement may
or may not produces or
Evaluation of an expression displays a result value, it only
always Produces or returns a does whatever the statement
result value. says.
Every expression can’t be a Every statement can be an
statement. expression.
Assignment Operators
Arithmetic Operators
Logical Operators
Relational Operators
Identity Operators
Membership Operators
Python Operators : Precedence and Associativity
1. Sequential statements are a set of statements whose execution process
happens in a sequence. The problem with sequential statements is that if the logic
has broken in any one of the lines, then the complete source code execution will
break.

## This is a Sequential statement

a=20
b=10
c=a-b
print("Subtraction is : ",c)
2. Selection/Decision control statements

The selection statement allows a program to test several conditions and execute
instructions based on which condition is true.

Some Decision Control Statements are:


•Simple if
•if-else
•nested if
•if-elif-else

Simple if: If statements are control flow statements that help us to run a particular
code, but only when a certain condition is met or satisfied. A simple if only has
one condition to check.

if <expr>:
<statement(s)>

n = 10
if n % 2 == 0:
print("n is an even number")
if-else: The if-else statement evaluates the condition and will execute
the body of if. if the test condition is True, but if the condition is False,
then the body of else is executed.

if <expr>: n=5
if n % 2 == 0:
<statement(s)> print("n is even")
else: else:
<statement(s)> print("n is odd")
nested if: Nested if statements are an if statement inside another if
statement.

a=5
b = 10
c = 15
if a > b:
if a > c:
print("a value is big")
else:
print("c value is big") if <expr>:
elif b > c: if <expr>:
print("b value is big")
<statement(s)>
else:
print("c is big")
else:
<statement(s)>
else:
<statement(s)>
if-elif-else: The if-elif-else statement is used to conditionally execute a
statement or a block of statements.

if <expr>:
<statement(s)>
elif <expr>: x = 15
<statement(s)> y = 12
elif <expr>: if x == y:
print("Both are Equal")
<statement(s)> elif x > y:
... print("x is greater than y")
else: else:
print("x is smaller than y")
<statement(s)>
Conditional Expressions (Python’s Ternary Operator)

Python supports one additional decision-making entity


called a conditional expression. (It is also referred to as a
conditional operator or ternary operator.

<expr1> if <conditional_expr> else <expr2>

age = 12
s = 'minor' if age < 21 else 'adult'
3. Loops/ Repetition
A repetition (loop) statement is used to repeat a group(block) of
programming instructions.

In Python, we generally have two loops/repetitive statements:


•for loop
•while loop
Loops/ Repetition
for loop
A for loop is used to iterate over a sequence that is either a list, tuple,
dictionary, or a set. We can execute a set of statements once for each item in a
list, tuple, or dictionary.

for iterator_var in sequence:


<statement(s)>

lst = [1, 2, 3, 4, 5]
for i in range(len(lst)):
print(lst[i], end = " ")

for j in range(0,10):
print(j, end = " ")
Loops/ Repetition
While loop
while loop: In Python, while loops are used to execute a block of statements repeatedly
until a given condition is satisfied. Then, the expression is checked again and, if it is still
true, the body is executed again. This continues until the expression becomes false.

while <expr>:
<statement(s)>

m=5
i=0
while i < m:
print(i, end = " ")
i=i+1
print("End")
Nested loops

Nested looping is the process of looping one loop within the boundaries of
others. So when the control flows from the outer loop to the inner loop, it
returns back to the outer loop only when the inner loops are completed.

Indentation is used to determine the body of the nested loops. Indentation


starts the loop, and the line from which it starts to be unindented represents
the end of the mentioned loop.
Transfer Statements
Transfer statements alter the way a logic gets executed. These statements are often
used in loops for and while.
Break

We can use break statement inside loops to break loop execution based on some
condition.
for i in range(10):
if i==7:
print("Processing is enough..please break the loop")
break
print(i)

0
1
2
3
4
5
6
Processing is enough..please break the loop
continue

We can use continue statement to skip current iteration and continue next iteration

for i in range(10): output


if i%2==0: 1
continue 3
print(i) 5
7
9
pass statement
•In our programming syntactically if block is required which won’t do anything then
• we can define that empty block with pass keyword.
•This statement does nothing. It is used to define an empty block of code or a class.
•When written in a loop statement, it’s usually the last statement.
numbers = [10,11,12,13,14]
output
for num in numbers :
10
if num%2 == 0:
12
print(num)
14
else:
pass
Strings:

A string is a sequence of characters. strings in Python are arrays of bytes


representing unicode characters.

For example, "hello" is a string containing a sequence of characters 'h', 'e', 'l', 'l',
and 'o‘.

We use single quotes or double quotes to represent a string in Python.

# create a string using double quotes or single quotes


string1 = "Python programming"
string2 = 'Python programming‘

Note: You can assign a multiline string to a variable by using three quotes:

a = ‘’’CVR College of Engineering,


Ibrahimpatnam’’’

print(a)
Python String Operations

Compare Two Strings

We use the == operator to compare two strings. If two strings are


equal, the operator returns True. Otherwise, it returns False.

str1 = "Hello, world!"


str2 = "I love Python."
str3 = "Hello, world!"

# compare str1 and str2


print(str1 == str2) # False

# compare str1 and str3


print(str1 == str3) # True
Python String Operations

Join Two or More Strings( Concatenation )


greet = "Hello, "
name = “CVR"
# using + operator
result = greet + name
print(result)

Iterate Through a Python String


greet = 'Hello‘
# iterating through greet string
for letter in greet:
print(letter)

String Membership Test


We can test if a substring exists within a string or not, using the keyword in.

print('a' in 'program') # True


print('at' not in 'battle') #False
Python String Operations

String Indexing
Strings are a sequence of characters, which means Python can use indexes to call
parts of the sequence. There are two ways of indexing.

•Positive Indexing
•Negative Indexing

String = “CVRCE"

# Show first element in string


print("The 1st element is : ", String[0])
print("The 1st element is : ", String[-10])
Python String Operations
String Slicing
Python slicing is about obtaining a sub-string from the given string by slicing it
respectively from start to end.
Python slicing can be done in two ways.
•slice() Constructor
•Extending Indexing

colgname= “CVRCOLLEGE“

#Using slice() Constructor


s1 = slice(3) #include first 3
s2 = slice(-3) #exclude last 3

print(colgname[s1]) #CVR
print(colgname[s2]) #CVRCOLL

#Extending Indexing
print(colgname[:6]) #CVRCOL (include the range (0,6))
print(colgname[1:7]) #VRCOLL (include the range (1,7))
Python String Operations
#Extending Indexing
We can use [ : : ] for specifying the frequency to print elements. It
specifies the step after which every element will be printed starting
from the given index. If nothing is given then it starts from the 0th
index.

String = "CVRCOLLEGE“

# print everything with step 1


print(String[::1]) #CVRCOLLEGE

# print everything with step 2 starting from 1st index


print(String[1::2]) #VCLEE

# print a string backwards # REVERSE OF A STRING


print(String[::-1]) #EGELLOCRVC
Python String Operations

String Formatting (f-Strings)


Python f-Strings make it really easy to print values and variables. For example,

name = 'Cathy'
country = 'UK'

print(f'{name} is from {country}‘)


Formatting output using the format method :

# Python program showing use of format() method

# using format() method


print('I love {} for {}!’.format(‘CVR’, ‘Education’))

# using format() method and referring to variable names


print('I love {colg} for {purpose}!’.format(colg=‘CVR’, purpose=
‘Education’))

# using format() method and referring a position of the object


print('{0} and {1}'.format(‘CVR', ‘Education'))

print('{1} and {0}'.format(‘CVR', ‘Education'))


Methods of Python String
There are various string methods present in Python. Here are some of those methods:

Method
capitalize() index() isspace() rfind() swapcase()
casefold() isalnum() istitle() rindex() title()
center() isalpha() isupper() rjust() translate()
count() isascii() join() rpartition() upper()
encode() isdecimal() ljust() rsplit() zfill()
endswith() isdigit() lower() rstrip()
expandtabs() isidentifier() lstrip() split()
find() islower() maketrans() splitlines()
format() isnumeric() partition() startswith()
format_map() isprintable() replace() strip()
e-resources:

•[Link]
•[Link]
•[Link]
•[Link]
•[Link]
•[Link]
•[Link]
•[Link]
•[Link]

You might also like