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

Python Unit 1.pptx

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

Python Unit 1.pptx

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

Course Code:R1UC405C Course Name: Programming in Python

What is Python?
Python is a popular programming language. It was created by
Guido van Rossum, and released in 1991.
It is used for:
● web development (server-side),
● software development,
● mathematics,
● system scripting.

Faculty Name: Vimal Singh Department: SCSE


Course Code:R1UC405C Course Name: Programming in Python

Popularity of Python?

Faculty Name: Vimal Singh Department: SCSE


Course Code:R1UC405C Course Name: Programming in Python

What can Python do?


● Python can be used on a server to create web applications.
● Python can be used alongside software to create workflows.
● Python can connect to database systems. It can also read and modify
files.
● Python can be used to handle big data and perform complex
mathematics.
● Python can be used for rapid prototyping, or for production-ready
software development.

Faculty Name: Vimal Singh Department: SCSE


Course Code:R1UC405C Course Name: Programming in Python

Why Python?
● Python works on different platforms (Windows, Mac, Linux,
Raspberry Pi, etc).
● Python has a simple syntax similar to the English language.
● Python has syntax that allows developers to write programs with fewer
lines than some other programming languages.
● Python runs on an interpreter system, meaning that code can be
executed as soon as it is written. This means that prototyping can be
very quick.
● Python can be treated in a procedural way, an object-oriented way or a
functional way.
Faculty Name: Vimal Singh Department: SCSE
Course Code:R1UC405C Course Name: Programming in Python

Python Syntax compared to other programming languages


● Python was designed for readability, and has some similarities to the
English language with influence from mathematics.
● Python uses new lines to complete a command, as opposed to other
programming languages which often use semicolons or parentheses.
● Python relies on indentation, using whitespace, to define scope; such as the
scope of loops, functions and classes. Other programming languages often
use curly-brackets for this purpose.

Faculty Name: Vimal Singh Department: SCSE


Course Code:R1UC405C Course Name: Programming in Python

Platforms for Python Programming:

● Local Machine

● Integrated Development Environments (IDEs)

● Online Python Interpreters

● Jupyter Notebooks

● Cloud Services
Faculty Name: Vimal Singh Department: SCSE
Course Code:R1UC405C Course Name: Programming in Python

Identifiers:
● In Python, an identifier is a name given to entities such as
variables, functions, classes, etc.
● Rules for writing identifiers:
● It must begin with a letter (a-z, A-Z) or an underscore
(_).
● It can be followed by letters, underscores, or digits
(0-9).
● Identifiers are case-sensitive.
● It cannot be a keyword (reserved word).
Faculty Name: Vimal Singh Department: SCSE
Course Code:R1UC405C Course Name: Programming in Python

Keywords:
● Keywords are reserved words that have special meanings
in Python and cannot be used as identifiers.
● Examples of Python keywords include if, else, for, while,
def, class, import, True, False, etc.

Faculty Name: Vimal Singh Department: SCSE


Course Code:R1UC405C Course Name: Programming in Python

Indentation:
● Python uses indentation to define the scope and structure of code
blocks.
● Indentation refers to the spaces or tabs at the beginning of a line of
code.
● Consistent indentation is crucial for Python programs to be readable
and syntactically correct.
● Standard indentation is typically four spaces, although any
consistent indentation style is acceptable as long as it's maintained
throughout the codebase.

Faculty Name: Vimal Singh Department: SCSE


Course Code:R1UC405C Course Name: Programming in Python

Data Types:
Python supports various data types, including:
● Numeric types: int, float, complex
● Sequence types: list, tuple, range
● Mapping type: dict
● Set types: set, frozenset
● Boolean type: bool
● Text type: str
Python is dynamically typed, meaning you don't need to explicitly declare
the data type of a variable. The interpreter infers it based on the value
assigned.

Faculty Name: Vimal Singh Department: SCSE


Course Code:R1UC405C Course Name: Programming in Python

Variables:
● Variables are used to store data values in memory.
● In Python, you can create a variable by assigning a value to it
using the assignment operator (=).
● Variable names must adhere to the rules for identifiers.
● Variables can be reassigned to different values during the
program execution.

Faculty Name: Vimal Singh Department: SCSE


Course Code:R1UC405C Course Name: Programming in Python

Expressions:
● Expressions are combinations of values and operators that
evaluate to a single value.
● Examples of expressions include arithmetic expressions (2 +
3, x * y), boolean expressions (x > 5, a and b), and string
expressions ("Hello" + "World").
● Expressions can contain variables, literals, function calls, and
operators.

Faculty Name: Vimal Singh Department: SCSE


Course Code:R1UC405C Course Name: Programming in Python

Statements:
● Statements are instructions that perform actions or control
the flow of execution in a Python program.
● Examples of statements include assignment statements,
control flow statements (if-else, while, for), function
definitions, import statements, etc.
● Each statement typically ends with a newline character,
although semicolons (;) can be used to separate multiple
statements on a single line.

Faculty Name: Vimal Singh Department: SCSE


Course Code:R1UC405C Course Name: Programming in Python

Operators in Python:
Operators in Python are symbols or special keywords that perform
operations on operands (values or variables). Python supports various types
of operators, including:
Assignment Operators:
Assignment operators are used to assign values to variables.
● = : Assigns the value on the right to the variable on the left.
● +=, -=, *=, /=, //=, %=: Perform the respective operation and then assign
the result to the left operand.

Faculty Name: Vimal Singh Department: SCSE


Course Code:R1UC405C Course Name: Programming in Python

Arithmetic Operators:
Arithmetic operators are used to perform mathematical operations.
● +, -, *, /: Addition, subtraction, multiplication, division.
● //: Floor division (returns the quotient rounded down to the nearest
integer).
● %: Modulus (returns the remainder of the division).
● **: Exponentiation (raises the left operand to the power of the right
operand).

Faculty Name: Vimal Singh Department: SCSE


Course Code:R1UC405C Course Name: Programming in Python

Comparison Operators:
Comparison operators are used to compare the values of
operands.
● ==: Equal to
● !=: Not equal to
● >, <: Greater than, less than
● >=, <=: Greater than or equal to, less than or equal to

Faculty Name: Vimal Singh Department: SCSE


Course Code:R1UC405C Course Name: Programming in Python

Logical Operators:
Logical operators are used to combine conditional statements.
● and: Returns True if both statements are true.
● or: Returns True if at least one of the statements is true.
● not: Returns True if the statement is false.

Faculty Name: Vimal Singh Department: SCSE


Course Code:R1UC405C Course Name: Programming in Python

Bitwise Operators:
Bitwise operators perform operations on binary representations
of integers.
● &, |, ^: Bitwise AND, OR, XOR
● <<, >>: Left shift, right shift
● ~: Bitwise NOT

Faculty Name: Vimal Singh Department: SCSE


Course Code:R1UC405C Course Name: Programming in Python

Membership Operators:
Membership operators are used to test whether a value or
variable is found in a sequence.
● in: Returns True if the value is found in the sequence.
● not in: Returns True if the value is not found in the sequence.

Faculty Name: Vimal Singh Department: SCSE


Course Code:R1UC405C Course Name: Programming in Python

Identity Operators:
Identity operators are used to compare the memory locations of
two objects.
● is: Returns True if both variables point to the same object.
● is not: Returns True if both variables do not point to the same
object.

Faculty Name: Vimal Singh Department: SCSE


Course Code:R1UC405C Course Name: Programming in Python

Taking Input from User:


Python provides the input() function to allow users to enter data during program execution.
● The input() function prompts the user to enter data and returns the entered value as a
string.
● You can optionally provide a string argument to input() to display a message or prompt
to the user.
● The entered value can be stored in a variable for further processing.
● You can convert the input to other data types using type conversion functions like int(),
float(), etc., if needed.

# Taking input from the user


user_input = input("Enter your name: ")

# Displaying the input


print("Hello,", user_input)
Faculty Name: Vimal Singh Department: SCSE
Course Code:R1UC405C Course Name: Programming in Python

Example:
# Taking input from the user
num = int(input("Enter an integer: "))

# Check if the number is even or odd


if num % 2 == 0:
print(num, "is even.")
else:
print(num, "is odd.")

Faculty Name: Vimal Singh Department: SCSE


Course Code:R1UC405C Course Name: Programming in Python

Conditional Statements - If-Else Statement and its Working:


Conditional statements in Python allow you to execute different blocks of code based on
specified conditions. The primary conditional statement in Python is the if-else statement.
If-Else Statement:
The if-else statement allows you to execute one block of code if a condition is true, and
another block of code if the condition is false.
Working of the if-else Statement:
The Python interpreter evaluates the condition specified in the if statement.
If the condition evaluates to True, the interpreter executes the block of code associated
with the if statement.
If the condition evaluates to False, the interpreter executes the block of code associated
with the else statement.
After executing the if or else block, the interpreter continues executing the rest of the
program.

Faculty Name: Vimal Singh Department: SCSE


Course Code:R1UC405C Course Name: Programming in Python

Nested If Statement:
A nested if statement is an if statement that is nested within another if
statement. This allows for multiple levels of conditions to be checked
within a program.
# Example of nested if statement
x = 10
y=5

if x > 5:
if y > 2:
print("Both conditions are True")
else:
print("First condition is True but second condition is False")
else:
print("First condition is False")

Faculty Name: Vimal Singh Department: SCSE


Course Code:R1UC405C Course Name: Programming in Python

Purpose and Working of For Loop:


The for loop in Python is used to iterate over a sequence (such as a list, tuple, dictionary, or
string) and execute a block of code for each item in the sequence.

Working of For Loop:


The for loop iterates over each item in the sequence.
For each iteration, the current item in the sequence is assigned to the variable specified after
the for keyword (item in the above syntax).
The block of code within the for loop is executed once for each item in the sequence.
Example of For Loop:

# Example of for loop


fruits = ["apple", "banana", "cherry"]
for fruit in fruits:
print(fruit)
Faculty Name: Vimal Singh Department: SCSE
Course Code:R1UC405C Course Name: Programming in Python

Nested For Loop:


A nested for loop is a loop inside another loop. It allows for multiple
iterations over sequences within sequences.

for item1 in sequence1:


for item2 in sequence2:
# Execute this block of code for each combination of items from
sequence1 and sequence2
statement(s)

Faculty Name: Vimal Singh Department: SCSE


Course Code:R1UC405C Course Name: Programming in Python

Break Statement:
The break statement is used to exit the current loop prematurely, regardless of whether the
loop's condition has been satisfied or not.
Purpose of Break Statement:
● It is used to terminate the loop early if a certain condition is met.
● It allows for immediate termination of the loop's execution.

# Example of break statement


numbers = [1, 2, 3, 4, 5]

for number in numbers:


if number == 3:
break
print(number)

Faculty Name: Vimal Singh Department: SCSE


Course Code:R1UC405C Course Name: Programming in Python

Continue Statement:
The continue statement is used to skip the current iteration of a loop and proceed to the next
iteration.
Purpose of Continue Statement:
● It is used to bypass certain iterations based on a specific condition.
● It allows for the skipping of specific operations within a loop without terminating the
loop entirely.
# Example of continue statement
numbers = [1, 2, 3, 4, 5]
for number in numbers:
if number == 3:
continue
print(number)
In this example, the value of number is not printed when it equals 3, and the loop continues
with the next iteration.
Faculty Name: Vimal Singh Department: SCSE
Course Code:R1UC405C Course Name: Programming in Python
Purpose and Working of While Loop:
The while loop in Python is used to repeatedly execute a block of code as long as a specified condition is true. It is ideal
when you don't know the number of iterations beforehand and need to continue looping until a certain condition is met.

Working of While Loop:


The condition specified after the while keyword is evaluated.
If the condition is true, the block of code within the while loop is executed.
After executing the block of code, the condition is evaluated again.
If the condition is still true, the block of code is executed again. This process continues until the condition becomes
false.
When the condition becomes false, the program exits the while loop and continues executing the subsequent code.

# Example of while loop


count = 0

while count < 5:


print("Count is:", count)
count += 1
Faculty Name: Vimal Singh Department: SCSE
Course Code:R1UC405C Course Name: Programming in Python

Python Data Types


Data types are the classification or categorization of data items. It represents the
kind of value that tells what operations can be performed on a particular data.
Since everything is an object in Python programming, data types are classes and
variables are instances (objects) of these classes. The following are the standard
or built-in data types in Python:
● Numeric
● Sequence Type
● Boolean
● Set
● Dictionary
● Binary Types

Faculty Name: Vimal Singh Department: SCSE


Course Code:R1UC405C Course Name: Programming in Python

Faculty Name: Vimal Singh Department: SCSE


Course Code:R1UC405C Course Name: Programming in Python

List

Faculty Name: Vimal Singh Department: SCSE


Course Code:R1UC405C Course Name: Programming in Python

List
Definition and Characteristics:

● Ordered Collection: Lists maintain the order of elements as they are


inserted.
● Mutable: Lists are mutable, meaning you can change, add, or remove
elements after the list is created.
● Heterogeneous: Lists can contain elements of different data types, including
integers, floats, strings, other lists, dictionaries, etc.
● Dynamic: Lists can grow or shrink in size dynamically as elements are added
or removed.
Faculty Name: Vimal Singh Department: SCSE
Course Code:R1UC405C Course Name: Programming in Python

List
Creation:

You can create a list in Python using square brackets [] or the


built-in list() function. Here's how you can create a list:

my_list = [1, 2, 3, 'a', 'b', 'c']

Faculty Name: Vimal Singh Department: SCSE


Course Code:R1UC405C Course Name: Programming in Python

List
Accessing Elements:

You can access individual elements of a list using square brackets [] and the
index of the element. Python uses zero-based indexing, meaning the first
element has an index of 0, the second element has an index of 1, and so on.
my_list = [1, 2, 3, 'a', 'b', 'c']

print(my_list[0]) # Output: 1
print(my_list[3]) # Output: 'a'
Faculty Name: Vimal Singh Department: SCSE
Course Code:R1UC405C Course Name: Programming in Python

List
Accessing Elements:

You can also use negative indices to access elements from the
end of the list:
my_list = [1, 2, 3, 'a', 'b', 'c']
print(my_list[-1]) # Output: 'c' (last element)

Faculty Name: Vimal Singh Department: SCSE


Course Code:R1UC405C Course Name: Programming in Python

List
Slicing:
You can also extract a sublist (slice) from a list using the slice operator
:. This allows you to specify a range of indices to retrieve a portion of
the list.

Faculty Name: Vimal Singh Department: SCSE


Course Code:R1UC405C Course Name: Programming in Python

List
Slicing:
You can also extract a sublist (slice) from a list using the slice operator
:. This allows you to specify a range of indices to retrieve a portion of
the list.
my_list = [1, 2, 3, 'a', 'b', 'c']

print(my_list[2:5]) # Output: [3, 'a', 'b'] (from index 2 to 4)


print(my_list[:3]) # Output: [1, 2, 3] (from beginning to index 2)
print(my_list[3:]) # Output: ['a', 'b', 'c'] (from index 3 to end)
Faculty Name: Vimal Singh Department: SCSE
Course Code:R1UC405C Course Name: Programming in Python

List Operations:
● Concatenation: You can concatenate two lists using the “+”
operator.
● Repetition: You can repeat a list using the “*” operator.
● Membership: You can check if an element is present in a list
using the “in” operator.

Faculty Name: Vimal Singh Department: SCSE


Course Code:R1UC405C Course Name: Programming in Python

List Methods:
Python lists come with several built-in methods for common operations
such as adding, removing, and manipulating elements. Some of the
commonly used methods include
append(), extend(), insert(),
remove(), pop(), index(),
count(), sort(), and reverse().

Faculty Name: Vimal Singh Department: SCSE


Course Code:R1UC405C Course Name: Programming in Python

Iterating Over a List:


You can iterate over the elements of a list using a for loop or list
comprehension.
my_list = [1, 2, 3, 'a', 'b', 'c']
for item in my_list:
print(item)

# List comprehension
squared_numbers = [x ** 2 for x in my_list if isinstance(x, int)]

Faculty Name: Vimal Singh Department: SCSE


Course Code:R1UC405C Course Name: Programming in Python

Tuple

Faculty Name: Vimal Singh Department: SCSE


Course Code:R1UC405C Course Name: Programming in Python

Tuples in Python are similar to lists, but they have some key
differences. Here's a detailed explanation of tuples in Python:

Faculty Name: Vimal Singh Department: SCSE


Course Code:R1UC405C Course Name: Programming in Python

Tuples in Python are similar to lists, but they have some key
differences. Here's a detailed explanation of tuples in Python:
Definition and Characteristics:
● Ordered Collection: Like lists, tuples are ordered collections of
elements. This means the order of elements in a tuple is preserved.
● Immutable: Unlike lists, tuples are immutable, meaning once they are
created, their elements cannot be changed, added, or removed.
● Heterogeneous: Tuples can contain elements of different data types, just
like lists.
● Hashable: Tuples are hashable, which means they can be used as keys in
dictionaries and elements of sets.
Faculty Name: Vimal Singh Department: SCSE
Course Code:R1UC405C Course Name: Programming in Python

Creation:
You can create a tuple in Python using parentheses () or the built-in tuple()
function. Here's how you can create a tuple:

my_tuple = (1, 2, 3, 'a', 'b', 'c')

Faculty Name: Vimal Singh Department: SCSE


Course Code:R1UC405C Course Name: Programming in Python

Creation:
You can create a tuple in Python using parentheses () or the built-in tuple()
function. Here's how you can create a tuple:

my_tuple = (1, 2, 3, 'a', 'b', 'c')

Accessing Elements:
You can access individual elements of a tuple using square brackets [] and
the index of the element, just like lists.
print(my_tuple[0]) # Output: 1
print(my_tuple[3]) # Output: 'a'
Faculty Name: Vimal Singh Department: SCSE
Course Code:R1UC405C Course Name: Programming in Python

Tuple Packing and Unpacking:

Tuple packing is the process of packing multiple values into a tuple. Tuple
unpacking is the process of extracting values from a tuple into individual
variables.
# Tuple packing
my_tuple = 1, 2, 3

# Tuple unpacking
a, b, c = my_tuple
print(a, b, c) # Output: 1 2 3

Faculty Name: Vimal Singh Department: SCSE


Course Code:R1UC405C Course Name: Programming in Python

Operations:

Since tuples are immutable, they support fewer operations compared to lists.
You can concatenate tuples, repeat them, and check for membership using
the same operators used for lists (+, *, in).

Faculty Name: Vimal Singh Department: SCSE


Course Code:R1UC405C Course Name: Programming in Python

Difference Feature List Tuple


between Mutability Mutable Immutable

List and Syntax Defined using square brackets [] Defined using parentheses ()
Tuple: Modification Elements can be added, removed, or modified
Elements cannot be added, removed,
or modified

Performance Slightly slower due to mutability Slightly faster due to immutability

When the data should remain constant


Use Cases When the data needs to be modified frequently
after creation

Lists support more operations like append, Tuples support fewer operations due to
Operations
extend, insert, remove, etc. immutability

Hashability Lists are not hashable Tuples are hashable

Tuples consume less memory due to


Memory Lists consume more memory due to mutability
immutability
Faculty Name: Vimal Singh Department: SCSE
Thanks You

You might also like