Unit 1
Unit 1
Unit 1
(Unit 1)
I Introduction to Python: Python variables, Python basic Operators, Understanding python blocks.
Python Data Types, Declaring and using Numeric data types: int, float etc. 03
Introduction of 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 makes development and debugging fast because no compilation step is included in Python
development, and the edit-test-debug cycle is very fast.
Python has many web-based assets, open-source projects, and a vibrant community. Learning the
language, working together on projects, and contributing to the Python ecosystem are all made very
easy for developers.
Because of its straightforward language framework, Python is easier to understand and write code in.
This makes it a fantastic programming language for novices. Additionally, it assists seasoned
programmers in writing clearer, error-free code.
Python is an open-source, cost-free programming language. It is utilized in several sectors and
disciplines as a result.
In Python, code readability and maintainability are important. As a result, even if the code was
developed by someone else, it is easy to understand and adapt by some other developer.
Python has many third-party libraries that can be used to make its functionality easier. These libraries
cover many domains, for example, web development, scientific computing, data analysis, and more.
Python Cycles:
1. Python‟s programming cycle is dramatically shorter than that of traditional programming cycle.
2. In Python, there are no compile or link steps.
3. Python programs simply import modules at runtime and use the objects they contain. Because of
this, Python programs run immediately after changes are made.
4. In cases where dynamic module reloading can be used, it is even possible to change and reload
parts of a running program without stopping it at all.
5. Python‟s impact on the programming cycle is as follows:
1
Ratnesh Kumar Shukla (Computer Science & Engineering)
Since Python is interpreted, there is a rapid turnaround after program changes. And because Python‟s
parser is embedded in Python-based
systems, it is easy to modify programs at runtime.
Python IDE( Integrated Development Environment):
1. IDE is a software package that consists of several tools for developing and testing the software.
2. An IDE helps the developer by automating the process.
3. IDEs integrate many tools that are designed for SDLC.
4. IDEs were introduced to diminish the coding and typing errors.
5. Some of the Python IDEs are :
a. PyCharm : PyCharm assists the developers to be more productive and provides smart suggestions.
It saves time by taking care of routine tasks, hence increases productivity.
Features of PyCharm :
i. It has smart code navigation, good code editor, a function for quick refactoring.
ii. The integrated activities with PyCharm are profiling, testing, debugging, remote development, and
deployments.
iii. PyCharm supports Python web development frameworks, Angular JS, JavaScript, CSS, HTML
and live editing functions.
b. Spyder : Spyder is widely used for data science works. It is mostly used to create a secure and
scientific environment for Python. Spyder Python uses PyQt (Python plug-in) which a developer can
add as an extension.
Features of Spyder :
i. It has good syntax highlighting and auto code completion
features.
ii. Spyder Python explores and edits variables directly from GUI.
iii. It performs very well in multi-language editor.
c. PyDev : It is an external plug-in for Eclipse and is very popular as Python interpreter.
Features of PyDev :
i. PyDev has strong parameters like refactoring, debugging, type hinting, code analysis, and code
coverage function.
ii. PyDev supports tokens browser, PyLint integration, interactive console, remote debugger, Unittest
integration, etc.
d. IDLE (Integrated Development and Learning Environment): IDLE is a basic IDE mainly used
by beginner level developer.
i. IDLE Python is a cross-platform IDE, hence it increases the flexibility for users.
ii. It is developed only in Python in collaboration with Tkinter GUI toolkit.
iii. The feature of multi-window text editor in IDLE has some great functions like smart indentation,
call tips, Python colorizing, and undo option.
2
Ratnesh Kumar Shukla (Computer Science & Engineering)
e. Visual studio : It enables development for various platforms and has its own marketplace for
extensions.
Features of visual studio :
i. It supports Python coding in visual studio, debugging, and other activities.
ii. It has both paid and free versions in the market with great features.
Python Basic Syntax:
There is no use of curly braces or semicolon in Python programming language. It is English-like
language. But Python uses the indentation to define a block of code. Indentation is nothing but adding
whitespace before the statement when it is needed.
For example -
def func():
statement 1
statement 2
…………………
…………………
statement N
In this example, the statements that are the same level to the right belong to the function. Generally,
we can use four whitespaces to define indentation.
Instead of Semicolon as used in other languages, Python ends its statements with a NewLine
character.
Python is a case-sensitive language, which means that uppercase and lowercase letters are treated
differently. For example, 'name' and 'Name' are two different variables in Python.
In Python, comments can be added using the '#' symbol. Any text written after the '#' symbol is
considered a comment and is ignored by the interpreter. This trick is useful for adding notes to the
code or temporarily disabling a code block. It also helps in understanding the code better by some
other developers.
'If', 'otherwise', 'for', 'while', 'try', 'except', and 'finally' are a few reserved keywords in Python that
cannot be used as variable names. These terms are used in the language for particular reasons and
have fixed meanings. If you use these keywords, your code may include errors, or the interpreter may
reject them as potential new Variables.
Python Features: Python provides many useful features to the programmer. These features make it
the most popular and widely used language. We have listed below few-essential features of Python.
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.
Expressive Language: It allows programmers to express complex concepts in just a few lines of code
or reduces Developer's Time.
Interpreted Language: Python does not require compilation, allowing rapid development and
testing. It uses Interpreter instead of Compiler.
Object-Oriented Language: It supports object-oriented programming, making writing reusable and
modular code easy.
Open Source Language: Python is open source and free to use, distribute and modify.
Extensible: Python can be extended with modules written in C, C++, or other languages.
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.
GUI Programming Support: Python provides several GUI frameworks, such as Tkinter and PyQt,
allowing developers to create desktop applications easily.
Integrated: Python can easily integrate with other languages and technologies, such as C/C++, Java,
and . NET.
Embeddable: Python code can be embedded into other applications as a scripting language.
Dynamic Memory Allocation: Python automatically manages memory allocation, making it easier
for developers to write complex programs without worrying about memory management.
3
Ratnesh Kumar Shukla (Computer Science & Engineering)
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.
Versatility: Python is a universal language in various domains such as web development, machine
learning, data analysis, scientific computing, and more.
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.
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.
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.
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.
Big Data and Machine Learning: Python has become the go-to language for big data and machine
learning. Python has become popular among data scientists and machine learning engineers with
libraries like NumPy, Pandas, Scikit-learn, TensorFlow, and more.
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.
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.
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.
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.
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.
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.
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.
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.
Enterprise Applications: Python can be used to develop large-scale enterprise applications with
features such as distributed computing, networking, and parallel processing.
3D CAD Applications: Python can be used for 3D computer-aided design (CAD) applications
through libraries such as Blender.
Machine Learning: Python is widely used for machine learning due to its simplicity, ease of use, and
availability of powerful machine learning libraries.
Computer Vision or Image Processing Applications: Python can be used for computer vision and
image processing applications through powerful libraries such as OpenCV and Scikit-image.
Speech Recognition: Python can be used for speech recognition applications through libraries such as
Speech Recognition and PyAudio.
Scientific computing: Libraries like NumPy, SciPy, and Pandas provide advanced numerical
computing capabilities for tasks like data analysis, machine learning, and more.
Education: Python's easy-to-learn syntax and availability of many resources make it an ideal
language for teaching programming to beginners.
4
Ratnesh Kumar Shukla (Computer Science & Engineering)
Testing: Python is used for writing automated tests, providing frameworks like unit tests and pytest
that help write test cases and generate reports.
Gaming: Python has libraries like Pygame, which provide a platform for developing games using
Python.
IoT: Python is used in IoT for developing scripts and applications for devices like Raspberry Pi,
Arduino, and others.
Networking: Python is used in networking for developing scripts and applications for network
automation, monitoring, and management.
DevOps: Python is widely used in DevOps for automation and scripting of infrastructure
management, configuration management, and deployment processes.
Finance: Python has libraries like Pandas, Scikit-learn, and Statsmodels for financial modeling and
analysis.
Audio and Music: Python has libraries like Pyaudio, which is used for audio processing, synthesis,
and analysis, and Music21, which is used for music analysis and generation.
Writing scripts: Python is used for writing utility scripts to automate tasks like file operations, web
scraping, and data processing.
Python Popular Frameworks and Libraries
Python has wide range of libraries and frameworks widely used in various fields such as machine
learning, artificial intelligence, web applications, etc. We define some popular frameworks and
libraries of Python as follows.
5
Ratnesh Kumar Shukla (Computer Science & Engineering)
6
Ratnesh Kumar Shukla (Computer Science & Engineering)
7
Ratnesh Kumar Shukla (Computer Science & Engineering)
8
Ratnesh Kumar Shukla (Computer Science & Engineering)
9
Ratnesh Kumar Shukla (Computer Science & Engineering)
10
Ratnesh Kumar Shukla (Computer Science & Engineering)
Python variables: Variable is a name that is used to refer to memory location. Python variable is also
known as an identifier and used to hold value.
In Python, we don't need to specify the type of variable because Python is a infer language and smart
enough to get variable type.
Variable names can be a group of both the letters and digits, but they have to begin with a letter or an
underscore.
It is recommended to use lowercase letters for the variable name. Rahul and rahul both are two
different variables.
Identifier Naming: Variables are the example of identifiers. An Identifier is used to identify the
literals used in the program. The rules to name an identifier are given below.
The first character of the variable must be an alphabet or underscore ( _ ).
All the characters except the first character may be an alphabet of lower-case(a-z), upper-case
(A-Z), underscore, or digit (0-9).
Identifier name must not contain any white-space, or special character (!, @, #, %, ^, &, *).
Identifier name must not be similar to any keyword defined in the language.
Identifier names are case sensitive; for example, my name, and MyName is not the same.
Examples of valid identifiers: a123, _n, n_9, etc.
Examples of invalid identifiers: 1a, n%4, n 9, etc.
Declaring Variable and Assigning Values: Python does not bind us to declare a variable before
using it in the application. It allows us to create a variable at the required time.
We don't need to declare explicitly variable in Python. When we assign any value to the variable, that
variable is declared automatically.
The equal (=) operator is used to assign value to a variable.
Python Variable Types:
There are two types of variables in Python - Local variable and Global variable. Let's understand the
following variables.
Local Variable: Local variables are the variables that declared inside the function and have scope
within the function. Let's understand the following example.
Example –
# Declaring a function
11
Ratnesh Kumar Shukla (Computer Science & Engineering)
def add():
# Defining local variables. They has scope only within a function
a = 20
b = 30
c=a+b
print("The sum is:", c)
# Calling a function
add()
Output:
The sum is: 50
Global Variables: Global variables can be used throughout the program, and its scope is in the entire
program. We can use global variables inside or outside the function.
A variable declared outside the function is the global variable by default. Python provides the global
keyword to use global variable inside the function. If we don't use the global keyword, the function
treats it as a local variable. Let's understand the following example.
Example –
# Declare a variable and initialize it
x = 101
# Global variable in function
def mainFunction():
# printing a global variable
global x
print(x)
# modifying a global variable
x = 'Welcome To Javatpoint'
print(x)
mainFunction()
print(x)
Output:
101
Welcome To Javatpoint
Welcome To Javatpoint
Explanation: In the above code, we declare a global variable x and assign a value to it. Next, we
defined a function and accessed the declared variable using the global keyword inside the function.
Now we can modify its value. Then, we assigned a new string value to the variable x.
Delete a variable: We can delete the variable using the del keyword. The syntax is given below.
Syntax -
del <variable_name>
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 -
# Assigning a value to x
x=6
print(x)
# deleting a variable.
del x
print(x)
Output:
6
Traceback (most recent call last):
print(x)
12
Ratnesh Kumar Shukla (Computer Science & Engineering)
Maximum Possible Value of an Integer in Python: Unlike the other programming languages,
Python doesn't have long int or float data types. It treats all integer values as an int data type. Here,
the question arises. What is the maximum possible value can hold by the variable in Python? Consider
the following example.
Example -
# A Python program to display that we can store
# large numbers in Python
a = 10000000000000000000000000000000000000000000
a=a+1
print(type(a))
print (a)
Output:
<class 'int'>
10000000000000000000000000000000000000000001
As we can see in the above example, we assigned a large integer value to variable x and checked its
type. It printed class <int> not long int. Hence, there is no limitation number by bits and we can
expand to the limit of our memory.
Python doesn't have any special data type to store larger numbers.
Print Single and Multiple Variables in Python: We can print multiple variables within the single
print statement. Below are the example of single and multiple printing values.
Example - 1 (Printing Single Variable)
# printing single value
a=5
print(a)
print((a))
Output:
5
5
Output:
56
12345678
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 –
Arithmetic operators
Comparison operators
Assignment Operators
Logical Operators
Bitwise Operators
13
Ratnesh Kumar Shukla (Computer Science & Engineering)
Membership Operators
Identity 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
* (Multiplication) It is used to multiply one operand with the other. For example, if a = 20, b = 4
=> a * 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
// (Floor division) It provides the quotient's floor value, which is obtained by dividing the two
operands.
Program Code:
a = 32 # Initialize the value of a
b=6 # Initialize the value of b
print('Addition of two numbers:',a+b)
print('Subtraction of two numbers:',a-b)
print('Multiplication of two numbers:',a*b)
print('Division of two numbers:',a/b)
print('Reminder of two numbers:',a%b)
print('Exponent of two numbers:',a**b)
print('Floor division of two numbers:',a//b)
Output: Now we compile the above code in Python, and after successful compilation, we run it. Then
the output is given below -
Addition of two numbers: 38
Subtraction of two numbers: 26
Multiplication of two numbers: 192
Division of two numbers: 5.333333333333333
Reminder of two numbers: 2
Exponent of two numbers: 1073741824
Floor division of two numbers: 5
14
Ratnesh Kumar Shukla (Computer Science & Engineering)
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 –
Output: Now we compile the above code in Python, and after successful compilation, we run it. Then
the output is given below -
Assignment Operators: Using the assignment operators, the right expression's value is assigned to
the left operand. There are some examples of assignment operators like =, +=, -=, *=, %=, **=, //=. In
the below table, we explain the works of the operators.
15
Ratnesh Kumar Shukla (Computer Science & Engineering)
Operator Description
+= By adding the value of the right operand by the value of the left operand, the left
operand receives a changed value. For example, if a = 10, b = 20 => a+ = b will be
equal to a = a+ b and therefore, a = 30.
-= It decreases the value of the left operand by the value of the right operand and assigns
the modified value back to left operand. For example, if a = 20, b = 10 => a- = b will
be equal to a = a- b and therefore, a = 10.
*= It multiplies the value of the left operand by the value of the right operand and assigns
the modified value back to then the left operand. For example, if a = 10, b = 20 => a*
= b will be equal to a = a* b and therefore, a = 200.
%= It divides the value of the left operand by the value of the right operand and assigns
the reminder back to the left operand. For example, if a = 20, b = 10 => a % = b will
be equal to a = a % b and therefore, a = 0.
**= a**=b will be equal to a=a**b, for example, if a = 4, b =2, a**=b will assign 4**2 =
16 to a.
//= A//=b will be equal to a = a// b, for example, if a = 4, b = 3, a//=b will assign 4//3 = 1
to a.
Program Code: Now we give code examples of Assignment 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: False
a+=b: 38
a-=b: 26
a*=b: 192
a%=b: 2
a**=b: 1073741824
a//=b: 5
16
Ratnesh Kumar Shukla (Computer Science & Engineering)
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-
if a = 7
b=6
then, binary (a) = 0111
binary (b) = 0110
In the below table, we are explaining the works of the bitwise operators.
Operator Description
& (binary and) A 1 is copied to the result if both bits in two operands at the same location are 1. If
not, 0 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 shift) The left operand is moved right by the number of bits present in the right operand.
Program Code: Now we give code examples of Bitwise operators in Python. The code is given
below -
17
Ratnesh Kumar Shukla (Computer Science & Engineering)
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.
Operator Description
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 -
a=5 # initialize the value of a
print(Is this statement true?:',a > 3 and a < 5)
print('Any one statement is true?:',a > 3 or a < 5)
print('Each statement is true then return False and vice-versa:',(not(a > 3 and a < 5)))
Output:
Now we give code examples of Bitwise operators in Python. The code is given below -
Is this statement true?: False
Any one statement is true?: True
Each statement is true then return False and vice-versa: True
Membership Operators: The membership of a value inside a Python data structure can be verified
using Python membership operators. The result is true if the value is in the data structure; otherwise, it
returns false.
18
Ratnesh Kumar Shukla (Computer Science & Engineering)
Operator Description
not in If the first operand is not present in the second operand, the
evaluation is true (list, tuple, or dictionary).
Program Code: Now we give code examples of Membership operators in Python. The code is given
below -
x = ["Rose", "Lotus"]
print(' Is value Present?', "Rose" in x)
print(' Is value not Present?', "Riya" not in x)
Output:
Now we compile the above code in Python, and after successful compilation, we run it. Then the
output is given below -
Is value Present? True
Is value not Present? True
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.
Program Code: Now we give code examples of Identity operators in Python. The code is given
below -
a = ["Rose", "Lotus"]
b = ["Rose", "Lotus"]
c=a
print(a is c)
print(a is not c)
print(a is b)
print(a is not b)
print(a == b)
print(a != b)
Output:
Now we compile the above code in python, and after successful compilation, we run it. Then the
output is given below -
True
False
False
True
True
False
Operator Precedence:
The order in which the operators are examined is crucial to understand since it tells us which operator
needs to be considered first. Below is a list of the Python operators' precedence tables.
Operator Description
19
Ratnesh Kumar Shukla (Computer Science & Engineering)
is given precedence.
* / % // the division of the floor, the modules, the division, and the multiplication.
<= < > >= Comparison operators (less than, less than equal to, greater than, greater
then equal to).
Understanding python blocks: In Python, a block is a group of statements that are indented together.
Blocks are used to define the scope of variables and to control the flow of execution.
if condition:
# This is a block of statements
# indented by four spaces
The statements in a block are executed as a unit. This means that if one statement in the block raises an
exception, the remaining statements in the block will not be executed.
Blocks are also used to define the scope of variables. The scope of a variable is the part of the program
where the variable is accessible. The scope of a variable in a block is limited to the block itself. This
means that a variable defined in a block cannot be accessed outside of the block.
def my_function():
# This is a block of statements
# indented by four spaces
x = 10
print(x)
20
Ratnesh Kumar Shukla (Computer Science & Engineering)
if condition:
# This is another block of statements
# indented by four spaces
y = 20
print(y)
In the first example, the function my_function() defines a block of statements. The statements in the
block are indented by four spaces. The variable x is defined in the block and is only accessible within
the block.
In the second example, the if statement defines a block of statements. The statements in the block are
indented by four spaces. The variable y is defined in the block and is only accessible within the block.
Here are some of the rules for Python block syntax:
Blocks must be indented by four spaces.
Statements in a block must be indented by the same amount of space.
The scope of a variable in a block is limited to the block itself.
I hope this article helps you understand Python block syntax.
Here are some additional tips for understanding Python block syntax:
Use a linter to help you indent your code correctly.
Use a debugger to step through your code and see how blocks are executed.
Use the help() function to learn more about the Python block syntax.
I hope these tips help you write more readable and maintainable Python code.
Python Data Types: Every value has a data type, 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=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.
a=10
b="Hi Python"
c = 10.5
print(type(a))
print(type(b))
print(type(c))
Output:
<type 'int'>
<type 'str'>
<type 'float'>
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
21
Ratnesh Kumar Shukla (Computer Science & Engineering)
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,
a=5
print("The type of a", type(a))
b = 40.5
print("The type of b", type(b))
c = 1+3j
print("The type of c", type(c))
print(" c is a complex number", isinstance(1+3j,complex))
Output:
The type of a <class 'int'>
The type of b <class 'float'>
The type of c <class 'complex'>
c is complex number: True
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.
22
Ratnesh Kumar Shukla (Computer Science & Engineering)
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.
Example:
str = "string using double quotes"
print(str)
s = '''''A multiline
string'''
print(s)
Output:
string using double quotes
A multiline
string
Example -
str1 = 'hello javatpoint' #string str1
str2 = ' how are you' #string str2
print (str1[0:2]) #printing first two character using slice operator
print (str1[4]) #printing 4th character of the string
print (str1*2) #printing the string twice
print (str1 + str2) #printing the concatenation of str1 and str2
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 (*).
Look at the following example.
Example:
list1 = [1, "hi", "Python", 2]
#Checking type of given list
print(type(list1))
# List slicing
print (list1[3:])
# List slicing
print (list1[0:2])
23
Ratnesh Kumar Shukla (Computer Science & Engineering)
Output:
[1, 'hi', 'Python', 2]
[2]
[1, 'hi']
[1, 'hi', 'Python', 2, 1, 'hi', 'Python', 2]
[1, 'hi', 'Python', 2, 1, 'hi', 'Python', 2, 1, 'hi', 'Python', 2]
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:
tup = ("hi", "Python", 2)
# Checking type of tup
print (type(tup))
# Tuple slicing
print (tup[1:])
print (tup[0:1])
# Printing dictionary
print (d)
24
Ratnesh Kumar Shukla (Computer Science & Engineering)
print (d.keys())
print (d.values())
Output:
1st name is Jimmy
2nd name is mike
{1: 'Jimmy', 2: 'Alex', 3: 'john', 4: 'mike'}
dict_keys([1, 2, 3, 4])
dict_values(['Jimmy', 'Alex', 'john', 'mike'])
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.
Example.
# Python program to check the boolean type
print(type(True))
print(type(False))
print(false)
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.
Example.
# Creating Empty set
set1 = set()
set2.add(10)
print(set2)
25
Ratnesh Kumar Shukla (Computer Science & Engineering)
Python Numeric Data type: In Python, numeric data type is used to hold numeric values.
Integers, floating-point numbers and complex numbers fall under Python numbers category. They are
defined as int, float and complex classes in Python.
float - holds floating decimal points and it's accurate up to 15 decimal places.
We can use the type() function to know which class a variable or a value belongs to.
Example,
num1 = 5
print(num1, 'is of type', type(num1))
num2 = 2.0
print(num2, 'is of type', type(num2))
num3 = 1+2j
print(num3, 'is of type', type(num3))
Run Code
Output
In the above example, we have created three variables named num1, num2 and num3 with
values 5, 5.0, and 1+2j respectively.
We have also used the type() function to know which class a certain variable belongs to.
Since,
5 is an integer value, type() returns int as the class of num1 i.e <class 'int'>
2.0 is a floating value, type() returns float as the class of num2 i.e <class 'float'>
1 + 2j is a complex number, type() returns complex as the class of num3 i.e <class 'complex'>
26
Ratnesh Kumar Shukla (Computer Science & Engineering)
List is an ordered collection of similar or different types of items separated by commas and enclosed
within brackets [ ]. For example,
Here, we have created a list named languages with 3 string values inside it.
Access List Items
To access items from a list, we use the index number (0, 1, 2 ...). For example,
languages = ["Swift", "Java", "Python"]
In the above example, we have used the index values to access items from the languages list.
languages[0] - access first item from languages i.e. Swift
languages[2] - access third item from languages i.e. Python
To learn more about lists, visit Python List.
Python Tuple Data Type: Tuple is an ordered sequence of items same as a list. The only difference
is that tuples are immutable. Tuples once created cannot be modified.
In Python, we use the parentheses () to store items of a tuple. For example,
Here, product is a tuple with a string value Xbox and integer value 499.99.
Python String Data Type: String is a sequence of characters represented by either single or double
quotes. For example,
name = 'Python'
print(name)
27
Ratnesh Kumar Shukla (Computer Science & Engineering)
Output:
Python
Python for beginners
In the above example, we have created string-type variables: name and message with
values 'Python' and 'Python for beginners' respectively.
Python Set Data Type: Set is an unordered collection of unique items. Set is defined by values
separated by commas inside braces { }. For example,
# create a set named student_id
student_id = {112, 114, 116, 118, 115}
Output:
print(capital_city)
Run Code
Output:
28
Ratnesh Kumar Shukla (Computer Science & Engineering)
Output:
Value: 124.23
Data Type: <class 'float'>
29
Ratnesh Kumar Shukla (Computer Science & Engineering)
print("Sum:",num_sum)
print("Data type of num_sum:",type(num_sum))
Run Code
Output:
num_string = int(num_string)
Here, we have used int() to perform explicit type conversion of num_string to integer type.
After converting num_string to an integer value, Python is able to add these two variables.
Finally, we got the num_sum value i.e 35 and data type to be int.
Interpreter: The Python interpreter works as a computer converter that converts high-level language
to low-level machine language, which is essential for the computer to understand the code written by
a programmer. Python codes are executed by an interpreter called CPython, which is written in C
language and executes instructions in a block of code one line after another.
Lexing
Parsing
Creation of byte code
Conversion to machine-executable code
Returning output
Step 1: Lexing: The first step of analyzing a code block in Python starts with Lexing, wherein the
single line of code being executed by the interpreter is converted into smaller parts. Each of these
parts is called a token, and these tokens are generated by the lexer, which is a part of the Python
30
Ratnesh Kumar Shukla (Computer Science & Engineering)
interpreter. Essentially, this can be considered to be a step in which the interpreter breaks down the
user instruction into small pieces, to process it piecewise.
Step 2: Parsing: In this step, another component of the Python interpreter called the Parser performs
the process of Parsing. Now essentially, Parsing is a process in which the tokens generated in the
Lexing stage into a structure called Abstract Syntax Tree. This tree shows the relationship between the
tokens generated from a particular line of code. This is where the Python interpreter also checks for
syntax errors, and if an error is found, the interpreter stops translating code and shows an error
message.
Step 3: Creation of Byte Code: After successful completion of the Parsing stage, the compiler
(another part of Python interpreter) converts the Abstract Syntax Tree into an intermediate language
code, called bytecode . This is a compiled version of the original code which is a low-level, platform
independent representation. This byte code is stored in a file with the same name as the original
source file, but with a „.pyc‟ extension instead of „.py‟ . This is a step completely hidden from the
developer which happens internally, and is performed as executing byte code is much faster than
original code statements.
Step 4: Conversion to Machine-executable Code: One of the most integral parts of the Python
interpreter is the Python Virtual Machine, or PVM. It is this part of the compiler which truly executes
a Python program. The PVM is the actual runtime engine of Python, and can be summarized as a big
loop which iterates through the byte code instructions stored in the file with .pyc extension statement
wise. Then it converts the statements into machine code, that is binary (0s and 1s). It also integrates
and loads the inputs and libraries involved in the program, so that the required instructions can be
carried out successfully. The PVM is the part of the interpreter that truly executes Python scripts.
Step 5: Returning Output: After the code is converted to binary, it is executed by the interpreter. If
there is an error, it displays the message and exits. Such an error is called a runtime error. If there is
no runtime error during program execution, then the interpreter prints the output and exits
successfully.
Text books:
1. Wesley J. Chun, “Core Python Applications Programming”, 3rd Edition, Pearson Education, 2016
2. Lambert, Fundamentals of Python: First Programs with MindTap, 2nd 1st edition, Cengage
Learning publication
3. Charles Dierbach, “Introduction to Computer Science using Python”, Wiley, 2015
4. Jeeva Jose & P.Sojan Lal, “Introduction to Computing and Problem Solving with PYTHON”,
Khanna Publishers, New Delhi,
2016
5. Downey, A. et al., “How to think like a Computer Scientist: Learning with Python”, John Wiley,
2015
6. Mark Lutz, “Learning Python”, 5th edition, Orelly Publication, 2013, ISBN 978- 1449355739
7. John Zelle, “Python Programming: An Introduction to Computer Science”, Second edition, Course
Technology Cengage
Learning Publications, 2013, ISBN 978- 1590282410
8. Michel Dawson, “Python Programming for Absolute Beginers”, Third Edition, Course Technology
Cengage Learning
Publications, 2013, ISBN 978-1435455009
9. David Beazley, Brian Jones., “Python Cookbook”, Third Edition, Orelly Publication, 2013, ISBN
978-1449340377.
31