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

Python Programming unit 2

This document provides an introduction to Python programming, covering key concepts such as variables, data types, input/output functions, and string manipulation. It explains how to create and manipulate strings, including operations like concatenation, slicing, and using various string functions. Additionally, it discusses the immutability of strings and the use of loops and membership operators in string handling.

Uploaded by

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

Python Programming unit 2

This document provides an introduction to Python programming, covering key concepts such as variables, data types, input/output functions, and string manipulation. It explains how to create and manipulate strings, including operations like concatenation, slicing, and using various string functions. Additionally, it discusses the immutability of strings and the use of loops and membership operators in string handling.

Uploaded by

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

PYTHON

PROGRAMMING
Unit 2 Python Programming Introduction
Contents
• Variables and assignment statements
• Data Types
• Input and print functions
• String formatting
Variables and Assignment statements
• Variables in Python are used to store and manipulate data. They act as containers
that hold values of different types, such as numbers, strings, or Boolean values.
Assignment statements are used to assign a value to a variable.
• In Python, you can create a variable by choosing a name and using the assignment
operator (=) to assign a value to it. For example:
age = 25
name = "John"
is_student = True

• You can also assign the result of an expression to a variable. For example:
x = 10
y = 5
sum = x + y
Variables and Assignment statements
• Variables can be reassigned with new values at any point in the program. For
example:
x = 10
x = x + 5

• It's important to note that Python is a dynamically typed language, meaning you
don't need to explicitly declare the type of a variable. The type is inferred based on
the value assigned to it.
Data Types
• The various data types in Python include:
• Integer (int): Represents whole numbers, such as 1, 2, -3, etc.
• Float: Represents decimal numbers, such as 3.14, -0.5, etc.
• String (str): Represents a sequence of characters enclosed in single quotes ('') or double
quotes ("").
• Boolean (bool): Represents either True or False.
• List: Represents an ordered collection of items, enclosed in square brackets ([]).
• Tuple: Represents an ordered, immutable collection of items, enclosed in parentheses ().
• Dictionary: Represents a collection of key-value pairs, enclosed in curly braces ({key:
value}).
• Set: Represents an unordered collection of unique items, enclosed in curly braces ({item1,
item2}).
• None: Represents the absence of a value or a null value.
• These are the main data types in Python, but there are also more specialized data
types and data structures available through libraries and modules.
Input and Print Function
• In Python, the `input()` function is used to accept user input from the keyboard,
while the `print()` function is used to display output on the console. Here's an
example of how to use these functions:
# Accepting user input
name = input("Enter your name: ")
age = input("Enter your age: ")
# Displaying output
print("Hello,", name)
print("You are", age, "years old.")
• When you run this code, it will prompt the user to enter their name and age. The
input values will be stored in the `name` and `age` variables, respectively. Then, the
`print()` function will display a greeting message along with the entered name and
age on the console.
String Formatting
• A String is a type of data value, stored in a variable that is made up of characters,
words, phrases, or symbols.
• Just like all variables have values that can change, Strings can change too, just like a
person's name can change in a variable.
• In Python, Strings are a sequence of Unicode characters. a string is a text, or
language, that we use to converse with a user.
Creating Strings
• There are different ways in python, to create strings, in single, double, as well as in
triple quotes.
Creating Strings
• While creating a string, if a string has any type of quotes, then in declaration you
should use a different type of quote to avoid an error.
• For better understanding, let’s look at an example.
Creating Strings
• Triple quotes are used, when you are declaring, or accessing a large paragraph.
There is an in-built function, for declaring or converting any other data type to
string.
• In this example, we have converted the integer 77, to a string, using the str()
function.
Accessing parts of a String
• Accessing parts of a string, is sometimes necessary to solve some particular use
case.
Accessing parts of a String
• Indexing on strings, also works with positive and negative indexing.
Slicing a String
• When we have long strings, like sentences, or paragraphs, and we want to access
some parts, like complete words, then we cannot use only indexing.
• Slicing a string, is achieved using the colon operator, within the square bracket.
• Here, we need to define the starting index, and ending index, separated with a colon.
By doing this, the output will be part of the string, from a starting index, to the
ending index minus one.
• Let’s look at an example. In this example, using indexes 1 and 4, we have retrieved
the character, till the third index.
Variations in Slicing
• In this example, the 1st slicing
operation, prints the string characters
from the 2nd string till the end.
• The 2nd operation, prints from the
star, till the 3rd index value. The 3rd
operation, prints the complete string,
and the last slicing operation, prints
particular string elements “H”,”I”, and
“w”.
Editing and Deleting Python Strings
• Strings are immutable data types in
Python, and if you try to edit any
string, then it will throw a type error.
• This means that, you cannot edit or
add a new character to the existing
string. But you can reassign it to a
different variable. This means, to
create a new string.
• In the 2nd operation, we have
reassigned the variable, with a slicing
operation, to reassign the string.
Editing and Deleting Python Strings
• In the 3rd operation,
when we try to delete a
string element, using the
del function, we get an
error.
• Also deleting a portion
of the string is not
possible.
Operations on Python Strings
• When it comes to strings, we can
perform only two arithmetic
operations:
• Addition
• Multiplication

• Addition
• Adding two strings, is also known as
concatenation. It means that, we can
join any number of strings, using an
addition operator between them.
• In this example, we have added three
strings, using the addition operator.
Operations on Python Strings
• Multiplication
• Multiplication on strings, is also known
as string repetition.
• This means that, to repeat a particular
string before the multiplication operator,
any number of times.
• In this example, we have multiplied the
string ‘hello’, 5 times. When we run this
code, the string is multiplied 5 times.
Operations on Strings
• Relational Operations on Strings
• Relational Operators mean, exhibiting
the relation between two terms, and
checking whether the given condition is
True or False.
• Therefore, the output of the relational
operator is, a Boolean value.
• In this example, we have used the
relational operators, is equal to, and is
not equal to.
• Once we run the code, python checks
and prints, whether the condition is true
or false.
Operations on Strings
• In this second example, we have used the relational operators, greater than, and
lesser than.
• Once we run the code, python checks the relation between the strings, and prints
true or false.
Operations on Strings
• Logical Operations on Strings
• Whenever we perform logical operators,
AND, OR, and NOT, on strings, then
Python says False to empty strings, and
True to non-empty strings.
• In this example, python prints True for the
1st logical operation, as both conditions
are true, since both strings exist.
• In the second operation, python prints
nothing, as only one strings exists.
• In the 3rd operation, logical “OR”, has
one string missing, hence python prints it
as False, and in the 4th, python see the not
logical operation, and prints it as false.
• In the 5th, since no string is present, the
not logic becomes true.
Loops on Strings
• We can loop over string, from any
index, using slicing. we can use a “for
loop”, on a string to access different
characters or to form a pattern.
• In this example, we have 1st used the
“for loop”, to loop through all the
characters in a string.
• 2nd, we have looped through
particular string values, in the given
string.
• In the 3rd, we have executed a
continuous loop, using “for loop”.
Membership Operators on Strings
• Membership operators in Python, are “in” and “not in”, which is used to check if any
element, is present in any sequence data structure of Python.
String Functions
• The length function
• This function, gives us the length of the
string.
• In this example, using the len() function,
we have printed the length, or number of
characters in the string, hello.
• The minimum function
• This function, gives you the smallest
character present in a string. In this
example, capital “H” comes before small
“h”, as per the ASCII table.
• Therefore, capital “H” is printed. Suppose
we replace the capital with a small “h”, in
the variable “A’, python prints the letter
“e”, as “e” comes 1st in alphabetical
order.
String Functions
• The maximum function
• This function works exactly opposite to
the minimum function, as python looks
for the maximum value in the string.
• In this example, python prints the letter
“o”, as it is the maximum in alphabetical
order.
• The sorted function
• This function sorts the string, in ascending
or descending order, according to ASCII
sequence.
• The output of this function, is always in
form of a list of characters.
• In this example, python sorts the string
characters, as per the ASCII table
sequence.
Specific String Functions

• The capitalize and title function


• Capitalize function, converts the first
letter of a string, in uppercase, while the
title function, converts each word’s first
character in uppercase.
• Once we execute the code, capitalization
is applied on the string characters.

• The upper , lower, and swap case Function


• The upper function, converts each
character of string, into upper case, and
lower function, in the lowercase. while the
swap, converts a lower character to upper,
and vice-versa. Once we execute the code,
the string elements are changed, as per the
function applied.
Specific String Functions
• The Count Function
• This function, gives you the count of
any substring present in a string. If the
substring is not present in the string,
then it outputs zero.
• The split function
• This function, splits the string into a list
of elements.
• The default splitting is done on the basis
of string, while you can also do splitting
on any other element.
• Once we execute the code, python has
split each word, into each string
element.

You might also like