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

Unit 1 Notes

Python is a versatile, high-level programming language that supports multiple programming paradigms, including object-oriented and functional programming. It is easy to learn, open-source, and has a vast collection of libraries and frameworks, making it suitable for various applications such as web development, data science, and artificial intelligence. Key features include dynamic typing, extensive community support, and a wide range of career opportunities for developers.

Uploaded by

Priyanshu Verma
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)
7 views

Unit 1 Notes

Python is a versatile, high-level programming language that supports multiple programming paradigms, including object-oriented and functional programming. It is easy to learn, open-source, and has a vast collection of libraries and frameworks, making it suitable for various applications such as web development, data science, and artificial intelligence. Key features include dynamic typing, extensive community support, and a wide range of career opportunities for developers.

Uploaded by

Priyanshu Verma
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
You are on page 1/ 46

Unit-1

What is Python
Python is a general-purpose, dynamic, high-level, and interpreted programming
language. It supports Object Oriented programming approach to develop applications.
It is simple and easy to learn and provides lots of high-level data structures.

Python is an easy-to-learn yet powerful and versatile scripting language, which makes it
attractive for Application Development.

With its interpreted nature, Python's syntax and dynamic typing make it an ideal
language for scripting and rapid application development.

Python supports multiple programming patterns, including object-oriented, imperative,


and functional or procedural programming styles.

Python is not intended to work in a particular area, such as web programming. It is a


multipurpose programming language because it can be used with web, enterprise, 3D
CAD, etc.

We don't need to use data types to declare variable because it is dynamically typed, so
we can write a=10 to assign an integer value in an integer variable.

Python Features
o Easy to use and Learn: Python has a simple and easy-to-understand syntax,
unlike traditional languages like C, C++, Java, etc., making it easy for beginners
to learn.
o Expressive Language: It allows programmers to express complex concepts in
just a few lines of code or reduces Developer's Time.
o Interpreted Language: Python does not require compilation, allowing rapid
development and testing. It uses Interpreter instead of Compiler.
o Object-Oriented Language: It supports object-oriented programming, making
writing reusable and modular code easy.
o Open Source Language: Python is open source and free to use, distribute and
modify.
o Extensible: Python can be extended with modules written in C, C++, or other
languages.
o Learn Standard Library: Python's standard library contains many modules and
functions that can be used for various tasks, such as string manipulation, web
programming, and more.
o GUI Programming Support: Python provides several GUI frameworks, such as
Tkinter and PyQt, allowing developers to create desktop applications easily.
o Integrated: Python can easily integrate with other languages and technologies,
such as C/C++, Java, and . NET.
o Embeddable: Python code can be embedded into other applications as a
scripting language.
o Dynamic Memory Allocation: Python automatically manages memory
allocation, making it easier for developers to write complex programs without
worrying about memory management.
o Wide Range of Libraries and Frameworks: Python has a vast collection of
libraries and frameworks, such as NumPy, Pandas, Django, and Flask, that can be
used to solve a wide range of problems.
o Versatility: Python is a universal language in various domains such as web
development, machine learning, data analysis, scientific computing, and more.
o Large Community: Python has a vast and active community of developers
contributing to its development and offering support. This makes it easy for
beginners to get help and learn from experienced developers.
o Career Opportunities: Python is a highly popular language in the job market.
Learning Python can open up several career opportunities in data science,
artificial intelligence, web development, and more.
o High Demand: With the growing demand for automation and digital
transformation, the need for Python developers is rising. Many industries seek
skilled Python developers to help build their digital infrastructure.
o Increased Productivity: Python has a simple syntax and powerful libraries that
can help developers write code faster and more efficiently. This can increase
productivity and save time for developers and organizations.
Where is Python used?

Python is a general-purpose, popular programming language, and it is used in almost every


technical field. The various areas of Python use are given below.

o Data Science: Data Science is a vast field, and Python is an important


language for this field because of its simplicity, ease of use, and availability of
powerful data analysis and visualization libraries like NumPy, Pandas, and
Matplotlib.
o Desktop Applications: PyQt and Tkinter are useful libraries that can be
used in GUI - Graphical User Interface-based Desktop Applications. There are
better languages for this field, but it can be used with other languages for
making Applications.
o Console-based Applications: Python is also commonly used to create
command-line or console-based applications because of its ease of use and
support for advanced features such as input/output redirection and piping.
o Mobile Applications: While Python is not commonly used for creating
mobile applications, it can still be combined with frameworks like Kivy or
BeeWare to create cross-platform mobile applications.
o Software Development: Python is considered one of the best software-
making languages. Python is easily compatible with both from Small Scale to
Large Scale software.
o Artificial Intelligence: AI is an emerging Technology, and Python is a
perfect language for artificial intelligence and machine learning because of the
availability of powerful libraries such as TensorFlow, Keras, and PyTorch.
o Web Applications: Python is commonly used in web development on the
backend with frameworks like Django and Flask and on the front end with tools
like JavaScript and HTML.
o Enterprise Applications: Python can be used to develop large-scale
enterprise applications with features such as distributed computing, networking,
and parallel processing.

& many more


Python Popular Frameworks and Libraries
o Web development (Server-side) - Django Flask, Pyramid, CherryPy
o GUIs based applications - Tk, PyGTK, PyQt, PyJs, etc.
o Machine Learning - TensorFlow, PyTorch, Scikit-learn, Matplotlib, Scipy, etc.
o Mathematics - Numpy, Pandas, etc.
o BeautifulSoup: a library for web scraping and parsing HTML and XML
o Requests: a library for making HTTP requests
o SQLAlchemy: a library for working with SQL databases
o Kivy: a framework for building multi-touch applications
o Pygame: a library for game development
o Pytest: a testing framework for Python
o Django REST framework: a toolkit for building RESTful APIs
o FastAPI: a modern, fast web framework for building APIs
o Streamlit: a library for building interactive web apps for machine learning and
data science
o NLTK: a library for natural language processing

Python Keywords
False Await else import pass

None Break except in raise

True Class finally is return

and Continue for lambda try

as Def from nonlocal while

assert Del global not with

async Elif if or yield


Python Variables
A variable is the name given to a memory location. A value-holding Python variable is
also known as an identifier.

Since Python is an infer language that is smart enough to determine the type of a
variable, we do not need to specify its type in Python.

Variable names must begin with a letter or an underscore, but they can be a group of
both letters and digits.

The name of the variable should be written in lowercase. Both Rahul and rahul are
distinct variables.

Identifier Naming
Identifiers are things like variables. An Identifier is utilized to recognize the literals
utilized in the program. The standards to name an identifier are given underneath.

Rules for constructing an Identifier


Identifiers are things like variables. An Identifier is utilized to recognize the literals
utilized in the program. The standards to name an identifier are given underneath.

o The variable's first character must be an underscore or alphabet (_).


o Every one of the characters with the exception of the main person might be a
letter set of lower-case(a-z), capitalized (A-Z), highlight, or digit (0-9).
o White space and special characters (!, @, #, %, etc.) are not allowed in the
identifier name. ^, &, *).
o Identifier name should not be like any watchword characterized in the language.
o Names of identifiers are case-sensitive; for instance, my name, and MyName isn't
something very similar.
o Examples of valid identifiers: a123, _n, n_9, etc.
o Examples of invalid identifiers: 1a, n%4, n 9, etc.
Variable Names
Variable names can be any length can have capitalized, lowercase (start to finish, a to z), the
digit (0-9), and highlight character(_). Take a look at the names of valid variables in the
following example.

name =

"Ayushman"age

= 23

marks = 81.50

print(name)

print(age)

print(marks)

Python Data Types


Every value has a datatype, and variables can hold values. Python is a powerfully
composed language; consequently, we don't have to characterize the sort of variable
while announcing it. The interpreter binds the value implicitly to its type.

a=10

We did not specify the type of the variable a, which has the value five from an integer.
The Python interpreter will automatically interpret the variable as an integer.

We can verify the type of the program-used variable thanks to Python. The type()
function in Python returns the type of the passed variable.

Consider the following illustration when defining and verifying the values of various data types.
a=10
b="Hi Python"
c = 10.5
print(type(a))
print(type(b))
print(type(c))
Standard data types
A variable can contain a variety of values. On the other hand, a person's id must be
stored as an integer, while their name must be stored as a string.
The storage method for each of the standard data types that Python provides is
specified by Python. The following is a list of the Python-defined data types.

1. Numbers
2. Sequence Type
3. Boolean
4. Set
5. Dictionary

The data types will be briefly discussed in this tutorial section. We will talk about every
single one of them exhaustively later in this instructional exercise.

Numbers
Numeric values are stored in numbers. The whole number, float, and complex qualities
have a place with a Python Numbers datatype. Python offers the type() function to
determine a variable's data type.

Python supports three kinds of numerical data.


o Int: Whole number worth can be any length, like numbers 10, 2, 29, - 20, - 150,
and so on. An integer can be any length you want in Python. Its worth has a
place with int.

o Float: Float stores drifting point numbers like 1.9, 9.902, 15.2, etc. It can be
accurate to within 15 decimal places.
o Complex: An intricate number contains an arranged pair, i.e., x + iy, where x and
y signify the genuine and non-existent parts separately. The complex numbers
like 2.14j, 2.0 + 2.3j, etc.

Sequence Type
String

The sequence of characters in the quotation marks can be used to describe the string. A
string can be defined in Python using single, double, or triple quotes.

String dealing with Python is a direct undertaking since Python gives worked-in
capabilities and administrators to perform tasks in the string.

When dealing with strings, the operation "hello"+" python" returns "hello python," and
the operator + is used to combine two strings.

Because the operation "Python" *2 returns "Python," the operator * is referred to as a


repetition operator.

The Python string is demonstrated in the following example

1. str = "string using double quotes"


2. print(str)
3. s = '''''A multiline
4. string'''
5. print(s)

List
Lists in Python are like arrays in C, but lists can contain data of different types. The things put
away in the rundown are isolated with a comma (,) and encased inside square sections [].

Example:
1. list1 = [1, "hi", "Python", 2]
2. #Checking type of given list
3. print(type(list1))
4.
5. #Printing the list1
6. print (list1)
7.
8. # List slicing
9. print (list1[3:])
10.
11. # List slicing
12. print (list1[0:2])
13.
14. # List Concatenation using + operator
15. print (list1 + list1)
16.# List repetation using * operator
17. print (list1 * 3)

Tuple
In many ways, a tuple is like a list. Tuples, like lists, also contain a collection of items
from various data types. A parenthetical space () separates the tuple's components from
one another.

Because we cannot alter the size or value of the items in a tuple, it is a read-only data
structure.

Let's look at a straightforward tuple in action.

Example:

1. tup = ("hi", "Python", 2)


2. # Checking type of tup
3. print (type(tup))
4. #Printing the tuple
5. print (tup)
7. # Tuple slicing
8. print (tup[1:])
9. print (tup[0:1])
11. # Tuple concatenation using + operator
12. print (tup + tup)
13.

14. # Tuple repatation using * operator


15. print (tup * 3)
16.
17. # Adding value to tup. It will throw an error.
18. t[2] = "hi"

Dictionary
A dictionary is a key-value pair set arranged in any order. It stores a specific value for
each key, like an associative array or a hash table. Value is any Python object, while the
key can hold any primitive data type.

The comma (,) and the curly braces are used to separate the items in the dictionary.

Look at the following example.

1. d = {1:'Ayushman', 2:'byteXL', 3:'Rohit', 4:'Rahul'}


2.
3. # Printing dictionary
4. print (d)
5.
6. # Accesing value using keys
7. print("1st name is "+d[1])
8. print("2nd name is "+ d[4])
9. print (d.keys())
10. print (d.values())

Boolean
True and False are the two default values for the Boolean type. These qualities are
utilized to decide the given assertion valid or misleading. The class book indicates this.
False can be represented by the 0 or the letter "F," while true can be represented by any
value that is not zero.

Look at the following example.

1. # Python program to check the boolean type


2. print(type(True))
3. print(type(False))
4. print(false)
Set
The data type's unordered collection is Python Set. It is iterable, mutable(can change
after creation), and has remarkable components. The elements of a set have no set
order; It might return the element's altered sequence. Either a sequence of elements is
passed through the curly braces and separated by a comma to create the set or the
built-in function set() is used to create the set. It can contain different kinds of values.

Look at the following example.

1. # Creating Empty set


2. set1 = set()
3.
4. set2 = {'James', 2, 3,'Python'}
5.
6. #Printing Set value
7. print(set2)
8.
9. # Adding element to the set
10.
11. set2.add(10)
12. print(set2)
13.
14. #Removing element from the set
15. set2.remove(2)
16. print(set2)

Python Operators
o Arithmetic operators (+, -, /, *, %, // (floor division), ** (Exponent)
o Comparison operators (==, !=, <=,>=,>,<)
o Assignment Operators (=, +=,-=,/=,*=,%=)
o Logical Operators (and, or, not)
o Bitwise Operators (&, I, ^,~,<<,>>)
o Membership Operators

Operator Description

in If the first operand cannot be found in the second operand, it is evaluated to be true (list,
tuple, or dictionary).

not in
If the first operand is not present in the second operand, the evaluation is true (list, tuple,
or dictionary).

o Identity Operators

Operator Description

is If the references on both sides point to the same object, it is determined


to be true.

is not
If the references on both sides do not point at the same object, it is
determined to be true.

Conditional statements
Decision making is the most important aspect of almost all the programming
languages. As the name implies, decision making allows us to run a particular
block of code for a particular decision. Here, the decisions are made on the
validity of the particular conditions. Condition checking is the backbone of
decision making.

In python, decision making is performed by the following statements.

Statement Description

If Statement The if statement is used to test a specific condition. If the condition


is true, a block of code (if-block) will be executed.

If - else The if-else statement is similar to if statement except the fact that,
Statement it also provides the block of the code for the false case of the
condition to be checked. If the condition provided in the if
statement is false, then the else statement will be executed.

Nested if Nested if statements enable us to use if ? else statement inside an


Statement outer if statement.
Indentation in Python
For the ease of programming and to achieve simplicity, python doesn't allow
the use of parentheses for the block level code. In Python, indentation is used
to declare a block. If two statements are at the same indentation level, then
they are the part of the same block.

Generally, four spaces are given to indent the statements which are a typical
amount of indentation in python.

Indentation is the most used part of the python language since it declares the
block of code. All the statements of one block are intended at the same level
indentation. We will see how the actual indentation takes place in decision
making and other stuff in python.

The if statement
The if statement is used to test a particular condition and if the condition is
true, it executes a block of code known as if-block. The condition of if
statement can be any valid logical expression which can be either evaluated to
true or false.
The syntax of the if-statement is given below.

1. if expression:
2. statement

Example 1
1. # Simple Python program to understand the if statement
2. num = int(input("enter the number:"))
3. # Here, we are taking an integer num and taking input dynamically
4. if num%2 == 0:
5. # Here, we are checking the condition. If the condition is true, we will enter th
e block
6. print("The Given number is an even number")

Output:
enter the number: 10
The Given number is an even number

Example 2 : Program to print the largest of the three


numbers.
1. # Simple Python Program to print the largest of the three numbers.
2. a = int (input("Enter a: "));
3. b = int (input("Enter b: "));
4. c = int (input("Enter c: "));
5. if a>b and a>c:
6. # Here, we are checking the condition. If the condition is true, we will enter th
e block
7. print ("From the above three numbers given a is largest");
8. if b>a and b>c:
9. # Here, we are checking the condition. If the condition is true, we will enter th
e block
10. print ("From the above three numbers given b is largest");
11.if c>a and c>b:
12. # Here, we are checking the condition. If the condition is true, we will enter th
e block
13. print ("From the above three numbers given c is largest");

The if-else statement


The if-else statement provides an else block combined with the if statement
which is executed in the false case of the condition.

If the condition is true, then the if-block is executed. Otherwise, the else-block
is executed.
The syntax of the if-else statement is given below.

1. if condition:
2. #block of statements
3. else:
4. #another block of statements (else-block)

Example 1 : Program to check whether a person is eligible


to vote or not.
1. # Simple Python Program to check whether a person is eligible to vote or not.
2. age = int (input("Enter your age: "))
3. # Here, we are taking an integer num and taking input dynamically
4. if age>=18:
5. # Here, we are checking the condition. If the condition is true, we will enter th
e block
6. print("You are eligible to vote !!");
7. else:
8. print("Sorry! you have to wait !!");

The elif statement


The elif statement enables us to check multiple conditions and execute the
specific block of statements depending upon the true condition among them.
We can have any number of elif statements in our program depending upon
our need. However, using elif is optional.

The elif statement works like an if-else-if ladder statement in C. It must be


succeeded by an if statement.

The syntax of the elif statement is given below.

1. if expression 1:
2. # block of statements
3.
4. elif expression 2:
5. # block of statements
6.
7. elif expression 3:
8. # block of statements
9.
10. else:
11. # block of statements
Example 1
1. # Simple Python program to understand elif statement
2. number = int(input("Enter the number?"))
3. # Here, we are taking an integer number and taking input dynamically
4. if number==10:
5. # Here, we are checking the condition. If the condition is true, we will enter th
e block
6. print("The given number is equals to 10")
7. elif number==50:
8. # Here, we are checking the condition. If the condition is true, we will enter th
e block
9. print("The given number is equal to 50");
10.elif number==100:
11. # Here, we are checking the condition. If the condition is true, we will enter th
e block
12. print("The given number is equal to 100");
13.else:
14. print("The given number is not equal to 10, 50 or 100");

Python Loops
The following loops are available in Python to fulfil the looping needs. Python offers 3 choices
for running the loops. The basic functionality of all the techniques is the same, although the
syntax and the amount of time required for checking the condition differ.

We can run a single statement or set of statements repeatedly using a loop command.

The following sorts of loops are available in the Python programming language

Sr.No. Name of Loop Type & Description


the loop

1 While loop Repeats a statement or group of statements while a given


condition is TRUE. It tests the condition before executing the
loop body.
2 For loop This type of loop executes a code block multiple times and
abbreviates the code that manages the loop variable.

3 Nested We can iterate a loop inside another loop.


loops

Loop Control Statements


Statements used to control loops and change the course of iteration are called control statements.
All the objects produced within the local scope of the loop are deleted when execution is
completed.

Python provides the following control statements. We will discuss them later
in detail.

Let us quickly go over the definitions of these loop control statements.

Sr.No. Name of the Description


control
statement

1 Break This command terminates the loop's execution and


statement transfers the program's control to the statement next
to the loop.

2 Continue This command skips the current iteration of the loop.


statement The statements following the continue statement are
not executed once the Python interpreter reaches the
continue statement.

3 Pass statement The pass statement is used when a statement is


syntactically necessary, but no code is to be executed.

The for Loop


Python's for loop is designed to repeatedly execute a code block while
iterating through a list, tuple, dictionary, or other iterable objects of Python.
The process of traversing a sequence is known as iteration.

Syntax of the for Loop

1. for value in sequence:


2. { code block }

In this case, the variable value is used to hold the value of every item present
in the sequence before the iteration begins until this particular iteration is
completed.

Loop iterates until the final item of the sequence are reached.

1. # Python program to show how the for loop works


2.
3. # Creating a sequence which is a tuple of numbers
4. numbers = [4, 2, 6, 7, 3, 5, 8, 10, 6, 1, 9, 2]
5.
6. # variable to store the square of the number
7. square = 0
8.
9. # Creating an empty list
10.squares = []
11.
12.# Creating a for loop
13.for value in numbers:
14. square = value ** 2
15. squares.append(square)
16.print("The list of squares is", squares)

Using else Statement with for Loop


As already said, a for loop executes the code block until the sequence element
is reached. The statement is written right after the for loop is executed after
the execution of the for loop is complete.
Only if the execution is complete does the else statement comes into play. It
won't be executed if we exit the loop or if an error is thrown.

Here is a code to better understand if-else statements.

Code

1. # Python program to show how if-else statements work


2.
3. string = "Python Loop"
4.
5. # Initiating a loop
6. for s in a string:
7. # giving a condition in if block
8. if s == "o":
9. print("If block")
10. # if condition is not satisfied then else block will be executed
11. else:
12. print(s)

Now similarly, using else with for loop.

Syntax:

1. for value in sequence:


2. # executes the statements until sequences are exhausted
3. else:
4. # executes these statements when for loop is completed

5. # Python program to show how to use else statement with for loop
6.
7. # Creating a sequence
8. tuple_ = (3, 4, 6, 8, 9, 2, 3, 8, 9, 7)
9.
10.# Initiating the loop
11.for value in tuple_:
12. if value % 2 != 0:
13. print(value)
14. # giving an else statement
15.else:
16. print("These are the odd numbers present in the tuple")

The range() Function


With the help of the range() function, we may produce a series of numbers.
range(10) will produce values between 0 and 9. (10 numbers).

We can give specific start, stop, and step size values in the manner range(start,
stop, step size). If the step size is not specified, it defaults to 1.

Since it doesn't create every value it "contains" after we construct it, the range
object can be characterized as being "slow." It does provide in, len, and
getitem actions, but it is not an iterator.

The example that follows will make this clear.

Code

1. # Python program to show the working of range() function


2.
3. print(range(15))
4.
5. print(list(range(15)))
6.
7. print(list(range(4, 9)))
8.
9. print(list(range(5, 25, 4)))

To iterate through a sequence of items, we can apply the range() method in


for loops. We can use indexing to iterate through the given sequence by
combining it with an iterable's len() function.

1. # Python program to iterate over a sequence with the help of indexing


2.
3. tuple_ = ("Python", "Loops", "Sequence", "Condition", "Range")
4.
5. # iterating over tuple_ using range() function
6. for iterator in range(len(tuple_)):
7. print(tuple_[iterator].upper())

While Loop
While loops are used in Python to iterate until a specified condition is met.
However, the statement in the program that follows the while loop is
executed once the condition changes to false.

Syntax of the while loop is:

1. while <condition>:
2. { code block }

All the coding statements that follow a structural command define a code
block. These statements are intended with the same number of spaces.
Python groups statements together with indentation.
Code

1. # Python program to show how to use a while loop


2. counter = 0
3. # Initiating the loop
4. while counter < 10: # giving the condition
5. counter = counter + 3
6. print("Python Loops")

Using else Statement with while Loops


As discussed earlier in the for loop section, we can use the else statement with
the while loop also. It has the same syntax.

1. #Python program to show how to use else statement with the while loop
2. counter = 0
3.
4. # Iterating through the while loop
5. while (counter < 10):
6. counter = counter + 3
7. print("Python Loops") # Executed untile condition is met
8. # Once the condition of while loop gives False this statement will be executed

9. else:
10. print("Code block inside the else statement")

Single statement while Block


The loop can be declared in a single statement, as seen below. This is similar
to the if-else block, where we can write the code block in a single line.

Code

1. # Python program to show how to write a single statement while loop


2. counter = 0
3. while (count < 3): print("Python Loops")

Loop Control Statements


Now we will discuss the loop control statements in detail. We will see an
example of each control statement.

Continue Statement
It returns the control to the beginning of the loop.

Code

1. # Python program to show how the continue statement works


2.
3. # Initiating the loop
4. for string in "Python Loops":
5. if string == "o" or string == "p" or string == "t":
6. continue
7. print('Current Letter:', string)

Break Statement
It stops the execution of the loop when the break statement is reached.

Code

1. # Python program to show how the break statement works


2.
3. # Initiating the loop
4. for string in "Python Loops":
5. if string == 'L':
6. break
7. print('Current Letter: ', string)

Pass Statement
Pass statements are used to create empty loops. Pass statement is also
employed for classes, functions, and empty control statements.

Code

1. # Python program to show how the pass statement works


2. for a string in "Python Loops":
3. pass
4. print( 'Last Letter:', string)

Python String

Python string is the collection of the characters surrounded by single quotes,


double quotes, or triple quotes. The computer does not understand the
characters; internally, it stores manipulated character as the combination of
the 0's and 1's.
Each character is encoded in the ASCII or Unicode character. So we can say
that Python strings are also called the collection of Unicode characters.

In Python, strings can be created by enclosing the character or the sequence


of characters in the quotes. Python allows us to use single quotes, double
quotes, or triple quotes to create the string.

Consider the following example in Python to create a string.

Syntax:
1. str = "Hi Python !"

Here, if we check the type of the variable str using a Python script

1. print(type(str)), then it will print a string (str).

Creating String in Python


We can create a string by enclosing the characters in single-quotes or double-
quotes. Python also provides triple-quotes to represent the string, but it is
generally used for multiline string or docstrings.

1. #Using single quotes


2. str1 = 'Hello Python'
3. print(str1)
4. #Using double quotes
5. str2 = "Hello Python"
6. print(str2)
7.
8. #Using triple quotes
9. str3 = '''''Triple quotes are generally used for
10. represent the multiline or
11. docstring'''
12.print(str3)
Strings indexing and splitting
Like other languages, the indexing of the Python strings starts from 0. For
example, The string "HELLO" is indexed as given in the below figure.

Consider the following example:

1. str = "HELLO"
2. print(str[0])
3. print(str[1])
4. print(str[2])
5. print(str[3])
6. print(str[4])
7. # It returns the IndexError because 6th index doesn't exist
8. print(str[6])
Example

1. # Given String
2. str = "HelloPython"
3. # Start Oth index to end
4. print(str[0:])
5. # Starts 1th index to 4th index
6. print(str[1:5])
7. # Starts 2nd index to 3rd index
8. print(str[2:4])
9. # Starts 0th to 2nd index
10.print(str[:3])
11.#Starts 4th to 6th index
12.print(str[4:7])

Reassigning Strings
Updating the content of the strings is as easy as assigning it to a new string.
The string object doesn't support item assignment i.e., A string can only be
replaced with new string since its content cannot be partially replaced. Strings
are immutable in Python.

Consider the following example.

Example 1
1. str = "HELLO"
2. str[0] = "h"
3. print(str)

Output:
Traceback (most recent call last):
File "12.py", line 2, in <module>
str[0] = "h";
TypeError: 'str' object does not support item assignment

However, in example 1, the string str can be assigned completely to a new


content as specified in the following example.

Example 2
1. str = "HELLO"
2. print(str)
3. str = "hello"
4. print(str)

Output:
HELLO
hello

Deleting the String


As we know that strings are immutable. We cannot delete or remove the
characters from the string. But we can delete the entire string using
the del keyword.

1. str = "JAVATPOINT"
2. del str[1]
Output:
TypeError: 'str' object doesn't support item deletion

Now we are deleting entire string.

1. str1 = "Ayushman"
2. del str1
3. print(str1)

Output:
NameError: name 'str1' is not defined

String Operators

1. str = "Hello"
2. str1 = " world"
3. print(str*3) # prints HelloHelloHello
4. print(str+str1)# prints Hello world
5. print(str[4]) # prints o
6. print(str[2:4]); # prints ll
7. print('w' in str) # prints false as w is not present in str
8. print('wo' not in str1) # prints false as wo is present in str1.
9. print(r'C://python37') # prints C://python37 as it is written
10.print("The string str : %s"%(str)) # prints The string str : Hello
11. Python String functions
12. Python provides various in-built functions that are used for string
handling. Many String fun

Method Description

capitalize() It capitalizes the first character of the String.


This function is deprecated in python3

casefold() It returns a version of s suitable for case-less


comparisons.

center(width ,fillchar) It returns a space padded string with the


original string centred with equal number of left
and right spaces.

count(string,begin,end) It counts the number of occurrences of a


substring in a String between begin and end
index.

decode(encoding = 'UTF8', Decodes the string using codec registered for


errors = 'strict') encoding.

encode() Encode S using the codec registered for


encoding. Default encoding is 'utf-8'.

endswith(suffix It returns a Boolean value if the string


,begin=0,end=len(string)) terminates with given suffix between begin and
end.

expandtabs(tabsize = 8) It defines tabs in string to multiple spaces. The


default space value is 8.

find(substring ,beginIndex, It returns the index value of the string where


endIndex) substring is found between begin index and end
index.

format(value) It returns a formatted version of S, using the


passed value.

index(subsring, beginIndex, It throws an exception if string is not found. It


endIndex) works same as find() method.

isalnum() It returns true if the characters in the string are


alphanumeric i.e., alphabets or numbers and
there is at least 1 character. Otherwise, it returns
false.

isalpha() It returns true if all the characters are alphabets


and there is at least one character, otherwise
False.

isdecimal() It returns true if all the characters of the string


are decimals.

isdigit() It returns true if all the characters are digits and


there is at least one character, otherwise False.

isidentifier() It returns true if the string is the valid identifier.

islower() It returns true if the characters of a string are in


lower case, otherwise false.

isnumeric() It returns true if the string contains only numeric


characters.

isprintable() It returns true if all the characters of s are


printable or s is empty, false otherwise.

isupper() It returns false if characters of a string are in


Upper case, otherwise False.

isspace() It returns true if the characters of a string are


white-space, otherwise false.

istitle() It returns true if the string is titled properly and


false otherwise. A title string is the one in which
the first character is upper-case whereas the
other characters are lower-case.

isupper() It returns true if all the characters of the string(if


exists) is true otherwise it returns false.

join(seq) It merges the strings representation of the given


sequence.

len(string) It returns the length of a string.

ljust(width[,fillchar]) It returns the space padded strings with the


original string left justified to the given width.
lower() It converts all the characters of a string to Lower
case.

lstrip() It removes all leading whitespaces of a string


and can also be used to remove particular
character from leading.

partition() It searches for the separator sep in S, and


returns the part before it, the separator itself,
and the part after it. If the separator is not
found, return S and two empty strings.

maketrans() It returns a translation table to be used in


translate function.

replace(old,new[,count]) It replaces the old sequence of characters with


the new sequence. The max characters are
replaced if max is given.

rfind(str,beg=0,end=len(str)) It is similar to find but it traverses the string in


backward direction.

rindex(str,beg=0,end=len(str)) It is same as index but it traverses the string in


backward direction.

rjust(width,[,fillchar]) Returns a space padded string having original


string right justified to the number of characters
specified.

rstrip() It removes all trailing whitespace of a string and


can also be used to remove particular character
from trailing.

rsplit(sep=None, maxsplit = -1) It is same as split() but it processes the string


from the backward direction. It returns the list of
words in the string. If Separator is not specified
then the string splits according to the white-
space.
Python List
In Python, the sequence of various data types is stored in a list. A list is a
collection of different kinds of values or items. Since Python lists are mutable,
we can change their elements after forming. The comma (,) and the square
brackets [enclose the List's items] serve as separators.

Although six Python data types can hold sequences, the List is the most
common and reliable form. A list, a type of sequence data, is used to store the
collection of data. Tuples and Strings are two similar data formats for
sequences.

Lists written in Python are identical to dynamically scaled arrays defined in


other languages, such as Array List in Java and Vector in C++. A list is a
collection of items separated by commas and denoted by the symbol [].

List Declaration
Code

1. # a simple list
2. list1 = [1, 2, "Python", "Program", 15.9]
3. list2 = ["Amy", "Ryan", "Henry", "Emma"]
4.
5. # printing the list
6. print(list1)
7. print(list2)
8.
9. # printing the type of list
10.print(type(list1))
11.print(type(list2))

Characteristics of Lists
o The lists are in order.
o The list element can be accessed via the index.
o The mutable type of List is
o The rundowns are changeable sorts.
o The number of various elements can be stored in a list.

Ordered List Checking


Code

1. # example
2. a = [ 1, 2, "Ram", 3.50, "Rahul", 5, 6 ]
3. b = [ 1, 2, 5, "Ram", 3.50, "Rahul", 6 ]
4. a == b

Let's take a closer look at the list example.

Code

1. # list example in detail


2. emp = [ "John", 102, "USA"]
3. Dep1 = [ "CS",10]
4. Dep2 = [ "IT",11]
5. HOD_CS = [ 10,"Mr. Holding"]
6. HOD_IT = [11, "Mr. Bewon"]
7. print("printing employee data ...")
8. print(" Name : %s, ID: %d, Country: %s" %(emp[0], emp[1], emp[2]))
9. print("printing departments ...")
10. print("Department 1:\nName: %s, ID: %d\n Department 2:\n Name: %s, ID: %s
"%( Dep1[0], Dep2[1], Dep2[0], Dep2[1]))
11. print("HOD Details .... ")
12. print("CS HOD Name: %s, Id: %d" %(HOD_CS[1], HOD_CS[0]))
13. print("IT HOD Name: %s, Id: %d" %(HOD_IT[1], HOD_IT[0]))
14. print(type(emp), type(Dep1), type(Dep2), type(HOD_CS), type(HOD_IT))
Python List/Array Methods
Python has a set of built-in methods that you can use on lists/arrays.

Method Description

append() Adds an element at the end of the list

clear() Removes all the elements from the list

copy() Returns a copy of the list

count() Returns the number of elements with the specified value

extend() Add the elements of a list (or any iterable), to the end of the current list

index() Returns the index of the first element with the specified value

insert() Adds an element at the specified position

pop() Removes the element at the specified position


remove() Removes the first item with the specified value

reverse() Reverses the order of the list

sort() Sorts the list

Python Tuples
A comma-separated group of items is called a Python triple. The ordering,
settled items, and reiterations of a tuple are to some degree like those of a
rundown, but in contrast to a rundown, a tuple is unchanging.

The main difference between the two is that we cannot alter the components
of a tuple once they have been assigned. On the other hand, we can edit the
contents of a list.

Example

1. ("Suzuki", "Audi", "BMW"," Skoda ") is a tuple.

List [ ]
List is a data structure which is also called as a collection of items in which we
can store any type of data like string, float, int. Every element of a list is
separated by comma (,)

Syntax:

Listname=[item1,item2 ,itemn]

Note: We can write the element of list inside square bracket [] & each item is
separated by comma (,)
Characteristics of List
Duplicate items are allowed

Mutable (Changeable) in Nature

Lists are ordered

Creating an Empty List:


list=[]

print(type(list))

List with Some values list=[10,”AI”,”BTech”,True,7.3]

print(list)

We can create list by another way using list function

List=list() print(type(list)

List Functions:
Index: If you want to print any item at specific index List=[1,5,”Ayushman”]

print(list[1] )

Output: 5

slicing list=[10,”AI”,”BTech”,True,7.3]

print(list[1:3])

output: [‘AI’,’BTech’]
count list=[10,”AI”,”BTech”,True,7.3]

print(list.count(“BTech”)

Output: 1

Index Method: for position of an item list=[10,”AI”,”BTech”,True,7.3]


print(list.index(7.3))

output: 4

*in case of repetition of item list=[10,”AI”,”BTech”,True,7.3,”BTech”]


print(list.index(“BTech”,1))

output: 2

append: This is used to add element at last in the list

list=[10,”AI”,”BTech”,True,7.3,”BTech”]

list.append(7) print(list)

Output: [10,”AI”,”BTech”,True,7.3,”BTech”,7]

insert: used to add element at specified index


list=[10,”AI”,”BTech”,True,7.3,”BTech”]

list.insert(3,”Ayushman”)

print(list)

Output: [10,”AI”,”BTech”,”Ayushman”,True,7.3,”BTech”,7]
pop: this is used to delete element at an specified index

list=[10,”AI”,”BTech”,True,7.3,”BTech”]

list.pop(2)

Output: [10,”AI”, True,7.3,”BTech”]

To delete last element don’t give index list.pop()

extend: This is used to add another list item in the existing list

list=[10,”AI”,”BTech”,True,7.3,”BTech”]

list1=[“Hi”,1,2] list.extend(list1)

copy: This is used to copy the item of one list into another

list=[10,”AI”,”BTech”,True,7.3,”BTech”]

list1=list.copy() print(list)

Another way of copying the list

list1=list[:]

sort: used to sort the list in ascending order

list=[1,4,3,7]

list.sort() print(list)

#to print data in descending order list.sort(reverse=True)

print(list)
reverse:

list=[10,”AI”,”BTech”,True,7.3,”BTech”]

list.reverse() print(list)

len:

list=[10,”AI”,”BTech”,True,7.3,”BTech”]

print(len(list))

Nested List
List=[2,5,10,[“CSE”,[“AI”]]

print(List)

Tuple ()
Tuple is a data structure which is also called as a collection of items in which
we can store any type of data like string, float, int. Every element of a tuple is
separated by comma (,)

Syntax:

tuplename=(item1,item2 ,itemn)

Note: We can write the element of tuple inside paranthesis () & each item is
separated by comma (,)
Characteristics of Tuple
Duplicate items are allowed

Immuutable (Changeable) in Nature

Tuples are ordered

#creating empty tuple


t=()

print(t)

print(type(t))

#adding values in tuple t=(1,2,"AI",True)

print(t)

#finding length of a tuple print(len(t))

#making changes in tuple '''t1=(1,2,"AI",True) t[1]=5

print(t1) #error as tuple are immutable''' #copying to another tuple


t1=(1,2,"AI",True)

t2=t1 print(t2)

#indexing in tuple print(t1[3]) #append in tuple t2.append()

print(t2) #there is no function in tuple like append #pop method

t2.pop()

print(t2) #error as there is no function like pop in tuple


Dictionary {key:value}
Dictionary is a data structure in which we represent group of objects as key
value

Syntax dictionaryname={key:value}

Indexing and slicing does’nt work

Ordered

Key must be unique, but duplicate values are allowed

#creating empty dictionary dict={}

print(dict) print(type(dict))

#some value in dictionary d={"course":"AI","Session":2024} print(d)

#for duplicate values d1={"Course":"AI","Age":23,"Number":23} print(d1)

#pop method d2={"Name":"Ayushman","Age":29,"Name":"Ashish","RN":29}


d2.pop("Name") #both name will be deleted

print(d2) #get method

d3={"Username":"A123","Password":"cd@234"} print(d3.get("Password"))

#if key is not present then output will be None print(d3.get("Apple"))

#for giving message in place of None print(d3.get("Apple","Not Available"))


#clear method

d3.clear() print(d3)

#Keys : this will give all keys d4={"course":"AI","Session":2024} print(d4.keys())

#items : it shows key and value pair print(d4.items())

#another way
for key,value in d4.items(): print(key,value)

#to update value in dict d4["Session"]=2026 print(d4)

Set {}
Set is a data structure which is also called as collection of items in which we
can represent group of unique values as a single entity

Syntax:

Setname={item1,item2, itemn}

We write the item of set inside curly {} braces

Unordered

Indexing and slicing doesn’t work

Mutable in nature

Duplicate values will be ignored #creating Empty set

s=set() print(s) print(type(s)) #add method

s.add("LearnPython") print(s)

#if you want to add multiple Items s.update("L","M")

print(s)

#remove: this will delete item as per our choice s1={"L","M",1,6.7}

print(s1)
s1.remove("L") print(s1)

#clear: this will clear all Items s1.clear()

print(s1)

#union: it will give unique value in both sets s2={4,6,"Ayushman"}

s3={4,"bytexl"} print(s2.union(s3))

#intersection: it will give common value in both sets print(s2.intersection(s3))

#difference : it will first match value of s2 and s3 #then remove common value
from both set and then #it will give remaining value of set 2

print(s2-s3)

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy