Python UNIT - I
Python UNIT - I
PYTHON PROGRAMMING
WHAT IS PYTHON?
PYTHON JOBS
Today, Python is very high in demand and all the major companies are looking for great Python
Programmers to develop websites, software components, and applications or to work with Data Science,
AI, and ML technologies. When we are developing this tutorial in 2023, there is a high shortage of
Python Programmers whereas market demands more number of Python Programmers due to its
application in Machine Learning, Artificial Intelligence etc. Today a Python Programmer with 3-5 years
of experience is asking for around $150,000 annual package and this is the most demanding programming
language in America. Though it can vary depending on the location of the Job. It's impossible to list all of
the companies using Python, to name a few big companies are: Google Intel NASA PayPal
Facebook IBM Amazon Netflix Pinterest Uber
Python is consistently rated as one of the world's most popular programming languages. Python is fairly
easy to learn, so if you are starting to learn any programming language then Python could be your great
choice. Today various Schools, Colleges and Universities are teaching Python as their primary
programming language. There are many other good reasons which makes Python as the top choice of any
programmer: Python is Open Source which means its available free of cost.
Python is a MUST for students and working professionals to become a great Software Engineer specially
when they are working in Web Development Domain. I will list down some of the key advantages of
learning Python: Python is Interpreted − Python is processed at runtime by the interpreter. You do not
need to compile your program before executing it. This is similar to PERL and PHP.
Python is Interactive − You can actually sit at a Python prompt and interact with the interpreter directly
to write your programs.
Python is Object-Oriented − Python supports Object-Oriented style or technique of programming that
encapsulates code within objects.
Python is a Beginner's Language − Python is a great language for the beginner level programmers and
supports the development of a wide range of applications from simple text processing to WWW browsers
to games.
CHARACTERISTICS OF PYTHON
Following are important characteristics of Python Programming − It supports functional and structured
programming methods as well as OOP
. It can be used as a scripting language or can be compiled to byte-code for building large applications.
It provides very high-level dynamic data types and supports dynamic type checking. It supports
automatic garbage collection.
It can be easily integrated with C, C++, COM, ActiveX, CORBA, and Java.
o The implementation of Python was started in December 1989 by Guido Van Rossum at CWI in
Netherland.
o In February 1991, Guido Van Rossum published the code (labeled version 0.9.0) to alt.sources.
o In 1994, Python 1.0 was released with new features like lambda, map, filter, and reduce.
o Python 2.0 added new features such as list comprehensions, garbage collection systems.
o On December 3, 2008, Python 3.0 (also called "Py3K") was released. It was designed to rectify
the fundamental flaw of the language.
o ABC programming language is said to be the predecessor of Python language, which was capable
of Exception Handling and interfacing with the Amoeba Operating System.
o ABC language.
o Modula-3
Van Rossum wanted to select a name which unique, sort, and little-bit mysterious. So he decided to select
naming Python after the "Monty Python's Flying Circus" for their newly created programming
language.
The comedy series was creative and well random. It talks about everything. Thus it is slow and
unpredictable, which made it very interesting.
Python is also versatile and widely used in every technical field, such as Machine Learning, Artificial
Intelligence, Web Development, Mobile Application, Desktop Application, Scientific Calculation, etc.
Python programming language is being updated regularly with new features and supports. There are lots
of update in Python versions, started from 1994 to current release.
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.
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 Python doesn't tie us to pronounce a variable prior to involving it in the application. It permits us
to make a variable at the necessary time.
o In Python, we don't have to explicitly declare variables. The variable is declared automatically
whenever a value is added to it.
Variable Names
The process for declaring the valid variable has already been discussed. 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.
1. name = "Devansh"
2. age = 20
3. marks = 80.50
4.
5. print(name)
6. print(age)
7. print(marks)
Output:
Devansh
20
80.5
1. name = "A"
2. Name = "B"
3. naMe = "C"
4. NAME = "D"
5. n_a_m_e = "E"
6. _name = "F"
7. name_ = "G"
8. _name_ = "H"
9. na56me = "I"
10.
11. print(name,Name,naMe,NAME,n_a_m_e, NAME, n_a_m_e, _name, name_,_name, na56me)
Output:
ABCDEDEFGFI
o Camel Case - In the camel case, each word or abbreviation in the middle of begins with a capital
letter. There is no intervention of whitespace. For example - nameOfStudent, valueOfVaraible,
etc.
o Pascal Case - It is the same as the Camel Case, but here the first word is also capital. For
example - NameOfStudent, etc.
o Snake Case - In the snake case, Words are separated by the underscore. For example -
name_of_student, etc.
Multiple Assignment
Multiple assignments, also known as assigning values to multiple variables in a single statement, is a
feature of Python.
We can apply different tasks in two ways, either by relegating a solitary worth to various factors or doling
out numerous qualities to different factors. Take a look at the following example.
Eg:
1. x=y=z=50
2. print(x)
3. print(y)
4. print(z)
Output:
50
50
50
Eg:
1. a,b,c=5,10,15
2. print a
3. print b
4. print c
Output:
5
10
15
The values will be assigned in the order in which variables appear.
There are two types of variables in Python - Local variable and Global variable. Let's understand the
following variables.
Local Variable
The variables that are declared within the function and have scope within the function are known as local
variables. Let's examine the following illustration.
Example -
1. # Declaring a function
2. def add():
3. # Defining local variables. They has scope only within a function
4. a = 20
5. b = 30
6. c=a+b
7. print("The sum is:", c)
8.
9. # Calling a function
10. add()
Output:
Explanation:
We declared the function add() and assigned a few variables to it in the code above. These factors will be
alluded to as the neighborhood factors which have scope just inside the capability. We get the error that
follows if we attempt to use them outside of the function.
1. add()
2. # Accessing local variable outside the function
3. print(a)
Output:
We tried to use local variable outside their scope; it threw the NameError.
Global Variables
Global variables can be utilized all through the program, and its extension is in the whole program.
Global variables can be used inside or outside the function.
By default, a variable declared outside of the function serves as the global variable. Python gives the
worldwide catchphrase to utilize worldwide variable inside the capability. The function treats it as a local
variable if we don't use the global keyword. Let's examine the following illustration.
Example -
Output:
101
Welcome To Javatpoint
Welcome To Javatpoint
Explanation:
In the above code, we declare a global variable x and give out a value to it. We then created a function
and used the global keyword to access the declared variable within the function. We can now alter its
value. After that, we gave the variable x a new string value and then called the function and printed x,
which displayed the new value.
Delete a variable
We can delete the variable using the del keyword. The syntax is given below.
Syntax -
1. del <variable_name>
In the following example, we create a variable x and assign value to it. We deleted variable x, and print it,
we get the error "variable x is not defined". The variable x will no longer use in future.
Example -
1. # Assigning a value to x
2. x = 6
3. print(x)
4. # deleting a variable.
5. del x
6. print(x)
Output:
6
Traceback (most recent call last):
File "C:/Users/DEVANSH SHARMA/PycharmProjects/Hello/multiprocessing.py", line 389, in
print(x)
NameError: name 'x' is not defined
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.
1. a = 5
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.
1. a=10
2. b="Hi Python"
3. c = 10.5
4. print(type(a))
5. print(type(b))
6. print(type(c))
Output:
<type 'int'>
<type 'str'>
<type 'float'>
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. The
instance () capability is utilized to check whether an item has a place with a specific class.
When a number is assigned to a variable, Python generates Number objects. For instance,
1. a = 5
2. print("The type of a", type(a))
3.
4. b = 40.5
5. print("The type of b", type(b))
6.
7. c = 1+3j
8. print("The type of c", type(c))
9. print(" c is a complex number", isinstance(1+3j,complex))
Output:
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.
Example - 1
Output:
Example - 2
Output:
he
o
hello javatpointhello javatpoint
hello javatpoint how are you
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 [].
To gain access to the list's data, we can use slice [:] operators. Like how they worked with strings, the list
is handled by the concatenation operator (+) and the repetition operator (*).
Example:
Output:
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:
Output:
<class 'tuple'>
('hi', 'Python', 2)
('Python', 2)
('hi',)
('hi', 'Python', 2, 'hi', 'Python', 2)
('hi', 'Python', 2, 'hi', 'Python', 2, 'hi', 'Python', 2)
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.
Output:
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.
Output:
<class 'bool'>
<class 'bool'>
NameError: name 'false' is not defined
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.
Output:
Every scripting language has designated words or keywords, with particular definitions and usage
guidelines. Python is no exception. The fundamental constituent elements of any Python program are
Python keywords.
This tutorial will give you a basic overview of all Python keywords and a detailed discussion of some
important keywords that are frequently used.
Python keywords are unique words reserved with defined meanings and functions that we can only apply
for those functions. You'll never need to import any keyword into your program because they're
permanently present.
Python's built-in methods and classes are not the same as the keywords. Built-in methods and classes are
constantly present; however, they are not as limited in their application as keywords.
Assigning a particular meaning to Python keywords means you can't use them for other purposes in our
code. You'll get a message of SyntaxError if you attempt to do the same. If you attempt to assign anything
to a built-in method or type, you will not receive a SyntaxError message; however, it is still not a smart
idea.
Python contains thirty-five keywords in the most recent version, i.e., Python 3.8. Here we have shown a
complete list of Python keywords for the reader's reference.
In distinct versions of Python, the preceding keywords might be changed. Some extras may be
introduced, while others may be deleted. By writing the following statement into the coding window, you
can anytime retrieve the collection of keywords in the version you are working on.
Code
Output:
Three Python keywords are employed as values in this example. These are singular values, which we can
reuse indefinitely and every time correspond to the same entity. These values will most probably be seen
and used frequently.
Code
1. print( 4 == 4 )
2. print( 6 > 9 )
3. print( True or False )
4. print( 9 <= 28 )
5. print( 6 > 9 )
6. print( True and False )
Output:
True
False
True
True
False
False
Python Operators
Introduction:
In this article, we are discussing Python Operators. The operator is a symbol that performs a specific
operation between two operands, according to one definition. Operators serve as the foundation upon
which logic is constructed in a program in a particular programming language. In every programming
language, some operators perform several tasks. Same as other languages, Python also has some
operators, and these are given below -
o Arithmetic operators
o Comparison operators
o Assignment Operators
o Logical Operators
o Bitwise Operators
o Membership Operators
o Identity Operators
o Arithmetic Operators
Arithmetic Operators
Arithmetic operators used between two operands for a particular operation. There are many arithmetic
operators. It includes the exponent (**) operator as well as the + (addition), - (subtraction), *
(multiplication), / (divide), % (reminder), and // (floor division) operators.
Operator Description
+ (Addition) It is used to add two operands. For example, if a = 10, b = 10 => a+b = 20
- (Subtraction) It is used to subtract the second operand from the first operand. If the first operand is
less than the second operand, the value results negative. For example, if a = 20, b = 5
=> a - b = 15
/ (divide) It returns the quotient after dividing the first operand by the second operand. For
example, if a = 20, b = 10 => a/b = 2.0
* It is used to multiply one operand with the other. For example, if a = 20, b = 4 => a *
(Multiplication) b = 80
% (reminder) It returns the reminder after dividing the first operand by the second operand. For
example, if a = 20, b = 10 => a%b = 0
** (Exponent) As it calculates the first operand's power to the second operand, it is an exponent
operator.
// (Floor It provides the quotient's floor value, which is obtained by dividing the two operands.
division)
ow we give code examples of arithmetic operators in Python. The code is given below -
Output:
Now we compile the above code in Python, and after successful compilation, we run it. Then the output is
given below -
Comparison operator
Comparison operators mainly use for comparison purposes. Comparison operators compare the values of
the two operands and return a true or false Boolean value in accordance. The example of comparison
operators are ==, !=, <=, >=, >, <. In the below table, we explain the works of the operators.
Operator Description
== If the value of two operands is equal, then the condition becomes true.
!= If the value of two operands is not equal, then the condition becomes true.
<= The condition is met if the first operand is smaller than or equal to the second operand.
>= The condition is met if the first operand is greater than or equal to the second operand.
> If the first operand is greater than the second operand, then the condition becomes true.
< If the first operand is less than the second operand, then the condition becomes true.
Program Code:
Now we give code examples of Comparison operators in Python. The code is given below -
ADVERTISEMENT
Output:
Now we compile the above code in Python, and after successful compilation, we run it. Then the output is
given below -
Bitwise Operators
The two operands' values are processed bit by bit by the bitwise operators. The examples of Bitwise
operators are bitwise OR (|), bitwise AND (&), bitwise XOR (^), negation (~), Left shift (<<), and Right
shift (>>). Consider the case below.
For example,
1. if a = 7
2. b=6
3. then, binary (a) = 0111
4. binary (b) = 0110
5.
6. hence, a & b = 0011
7. a | b = 0111
8. a ^ b = 0100
9. ~ a = 1000
10. Let, Binary of x = 0101
11. Binary of y = 1000
12. Bitwise OR = 1101
13. 8 4 2 1
14. 1 1 0 1 = 8 + 4 + 1 = 13
15.
16. Bitwise AND = 0000
17. 0000 = 0
18.
19. Bitwise XOR = 1101
20. 8 4 2 1
21. 1 1 0 1 = 8 + 4 + 1 = 13
22. Negation of x = ~x = (-x) - 1 = (-5) - 1 = -6
23. ~x = -6
In the below table, we are explaining the works of the bitwise operators.
Operator Description
& (binary A 1 is copied to the result if both bits in two operands at the same location are 1. If not, 0
and) is copied.
| (binary or) The resulting bit will be 0 if both the bits are zero; otherwise, the resulting bit will be 1.
^ (binary xor) If the two bits are different, the outcome bit will be 1, else it will be 0.
~ (negation) The operand's bits are calculated as their negations, so if one bit is 0, the next bit will be
1, and vice versa.
<< (left shift) The number of bits in the right operand is multiplied by the leftward shift of the value of
the left operand.
>> (right The left operand is moved right by the number of bits present in the right operand.
shift)
Program Code:
Now we give code examples of Bitwise operators in Python. The code is given below -
Output:
Now we compile the above code in Python, and after successful compilation, we run it. Then the output is
given below -
a&b: 4
a|b: 7
a^b: 3
~a: -6
a<>b: 0
Logical Operators
The assessment of expressions to make decisions typically uses logical operators. The examples of logical
operators are and, or, and not. In the case of logical AND, if the first one is 0, it does not depend upon the
second one. In the case of logical OR, if the first one is 1, it does not depend on the second one. Python
supports the following logical operators. In the below table, we explain the works of the logical operators.
Operato Description
r
and The condition will also be true if the expression is true. If the two expressions a and b are the
same, then a and b must both be true.
or The condition will be true if one of the phrases is true. If a and b are the two expressions,
then an or b must be true if and is true and b is false.
not If an expression a is true, then not (a) will be false and vice versa.
Program Code:
Now we give code examples of arithmetic operators in Python. The code is given below -
Output:
Now we give code examples of Bitwise operators in Python. The code is given below -
We'll study how to write comments in our program in this article. We'll also learn about single-line
comments, multi-line comments, documentation strings, and other Python comments.
We may wish to describe the code we develop. We might wish to take notes of why a section of script
functions, for instance. We leverage the remarks to accomplish this. Formulas, procedures, and
sophisticated business logic are typically explained with comments. The Python interpreter overlooks the
remarks and solely interprets the script when running a program. Single-line comments, multi-line
comments, and documentation strings are the 3 types of comments in Python.
Our code is more comprehensible when we use comments in it. It assists us in recalling why specific
sections of code were created by making the program more understandable.
Aside from that, we can leverage comments to overlook specific code while evaluating other code
sections. This simple technique stops some lines from running or creates a fast pseudo-code for the
program.
Single-Line Comments
Single-line remarks in Python have shown to be effective for providing quick descriptions for parameters,
function definitions, and expressions. A single-line comment of Python is the one that has a hashtag # at
the beginning of it and continues until the finish of the line. If the comment continues to the next line, add
a hashtag to the subsequent line and resume the conversation. Consider the accompanying code snippet,
which shows how to use a single line comment:
Code
Output:
Everything following the # is omitted. As a result, we may put the program mentioned above in one line
as follows:
Code
1. print( 'This is not a comment' ) # this code is to show an example of a single-line comment
Output:
This program's output will be identical to the example above. The computer overlooks all content
following #.
Multi-Line Comments
Python does not provide the facility for multi-line comments. However, there are indeed many ways to
create multi-line comments.
With Multiple Hashtags (#)
In Python, we may use hashtags (#) multiple times to construct multiple lines of comments. Every line
with a (#) before it will be regarded as a single-line comment.
Code
1. # it is a
2. # comment
3. # extending to multiple lines
In this case, each line is considered a comment, and they are all omitted.
Because Python overlooks string expressions that aren't allocated to a variable, we can utilize them as
comments.
Code
We can observe that on running this code, there will be no output; thus, we utilize the strings inside triple
quotes(""") as multi-line comments.
Python Docstring
The strings enclosed in triple quotes that come immediately after the defined function are called Python
docstring. It's designed to link documentation developed for Python modules, methods, classes, and
functions together. It's placed just beneath the function, module, or class to explain what they perform.
The docstring is then readily accessible in Python using the __doc__ attribute.
Code
Output:
The python script file is saved with '. py' extension. After saving the python script, we can run it from the
Command Line. In the cmd, type keyword 'python' followed by the name of the file with which you saved
the python script.
After writing the code, we need to run the code to execute and obtain the output. On running the program,
we can check whether the code is written is correct and produces the desired output.
Run on IDLE
The python script file is saved with ‘.py’ extension. After saving the python script, we can run it from the
Command Line. In the cmd, type keyword ‘python’ followed by the name of the file with which you
saved the python script.
Example
Let us suppose, we have a python script saved with the name ‘hello.py’. To run it on command line, type
the following −
python hello.py
To run a python program on an IDE like PyCharm, we need to follow the given steps −
Create a new python file and save it with some name, say “hello.py”.You don’t need to specify
the extension as it will pick it automatically.
After writing the required code in the python file, we need to run it.
To run, Click on the Green Play Button at the top right corner of the IDE. The second way to
run is, Right click and select ‘Run File in Python Console’ option.
This will open a console box at the bottom and output will be shown there.
Interactive Mode
Interactive mode is the method to type and run python code in command line. In interactive mode, the
python code is written and run line by line in a sequential manner.To enter into interactive mode, open
Command Prompt and type ‘python’ and press Enter.
Write one line of code and press enter to execute it and enter the second line.
Example
To run the code in interactive mode, You must have python installed on your system. On typing
‘python’ , the version of the python installed on your system is displayed. This means that python is
installed on your system and we can move forward in running python scripts. On entering one line of
code i.e. print(“Hello World”) ,after pressing enter the “Hello World” is displayed.
We can run python script on a text editor. To do so,follow the following steps −
File handling simply means to open a file and to process it according to the required tasks. Python
facilitates several functions to create, read, write, append, delete and close files.
❏ Open File:
Syntax:
f = open(“filename“, “mode“)
Mode: This parameter specifies the mode in which the file should be opened.
r Read only mode Pointer starts from the beginning of the file.
r+ Read Write mode Pointer starts from the beginning of the file.
❏ Close File:
Syntax:
f.close()
❏ Read File:
f.read()
Syntax:
f.readline()
❏ Write File:
Syntax:
f.write(statement)
❏ Delete File:
Syntax:
import os
os.remove(“filename“)
Syntax:
import os
os.rmdir(“filename“)
Example:
f = open("pythonex.txt", "w")
f.write("HELLO PYTHON!\nPython facilitates several functions to create, read, write, append, delete and close files.")
f.close()
f = open("pythonex.txt", "r")
b = f.read()
print b
f.close()