Unit 1 Notes
Unit 1 Notes
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.
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 Keywords
False Await else import pass
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.
name =
"Ayushman"age
= 23
marks = 81.50
print(name)
print(age)
print(marks)
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.
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.
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.
Example:
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.
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.
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 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.
Statement Description
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.
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
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)
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
Python provides the following control statements. We will discuss them later
in detail.
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.
Code
Syntax:
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")
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.
Code
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.
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 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")
Code
Continue Statement
It returns the control to the beginning of the loop.
Code
Break Statement
It stops the execution of the loop when the break statement is reached.
Code
Pass Statement
Pass statements are used to create empty loops. Pass statement is also
employed for classes, functions, and empty control statements.
Code
Python String
Syntax:
1. str = "Hi Python !"
Here, if we check the type of the variable str using a Python script
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.
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
Example 2
1. str = "HELLO"
2. print(str)
3. str = "hello"
4. print(str)
Output:
HELLO
hello
1. str = "JAVATPOINT"
2. del str[1]
Output:
TypeError: 'str' object doesn't support item deletion
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
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.
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.
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
Code
Method Description
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
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
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
print(type(list))
print(list)
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
output: 4
output: 2
list=[10,”AI”,”BTech”,True,7.3,”BTech”]
list.append(7) print(list)
Output: [10,”AI”,”BTech”,True,7.3,”BTech”,7]
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)
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)
list1=list[:]
list=[1,4,3,7]
list.sort() print(list)
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
print(t)
print(type(t))
print(t)
t2=t1 print(t2)
t2.pop()
Syntax dictionaryname={key:value}
Ordered
print(dict) print(type(dict))
d3={"Username":"A123","Password":"cd@234"} print(d3.get("Password"))
d3.clear() print(d3)
#another way
for key,value in d4.items(): print(key,value)
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}
Unordered
Mutable in nature
s.add("LearnPython") print(s)
print(s)
print(s1)
s1.remove("L") print(s1)
print(s1)
s3={4,"bytexl"} print(s2.union(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)