Python Unit 1.pptx
Python Unit 1.pptx
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.
Popularity of 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
● Local Machine
● 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.
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.
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.
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.
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.
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.
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.
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).
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
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.
Bitwise Operators:
Bitwise operators perform operations on binary representations
of integers.
● &, |, ^: Bitwise AND, OR, XOR
● <<, >>: Left shift, right shift
● ~: Bitwise NOT
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.
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.
Example:
# Taking input from the user
num = int(input("Enter an integer: "))
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")
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.
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.
List
List
Definition and Characteristics:
List
Creation:
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)
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.
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']
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.
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().
# List comprehension
squared_numbers = [x ** 2 for x in my_list if isinstance(x, int)]
Tuple
Tuples in Python are similar to lists, but they have some key
differences. Here's a detailed explanation of tuples 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:
Creation:
You can create a tuple in Python using parentheses () or the built-in tuple()
function. Here's how you can create a tuple:
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 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
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).
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
Lists support more operations like append, Tuples support fewer operations due to
Operations
extend, insert, remove, etc. immutability