Unit 1 Introduction To Python
Unit 1 Introduction To Python
What is Python?
Python is a popular programming language. It was created by Guido van Rossum, and released in
1991.
It is designed to be simple and easy to learn, making it an ideal choice for beginners. One of the key
strengths. of Python is its versatility.
It is used for:
software development,
mathematics,
system scripting.
Python can connect to database systems. It can also read and modify files.
Python can be used to handle big data and perform complex mathematics.
Python can be used for rapid prototyping, or for production-ready software development.
Why Python?
Python works on different platforms (Windows, Mac, Linux, Raspberry Pi, etc).
Python has syntax that allows developers to write programs with fewer lines than some
other programming languages.
Python runs on an interpreter system, meaning that code can be executed as soon as it is
written. This means that prototyping can be very quick.
Readability: Python's syntax is designed to be clear and reusable, making it easy for for both
beginners and experienced programmers to understand and write code.
Simplicity:- Python emphasizes simplicity and avoids complex syntax, making it easy for learn
and use compared to Other programming language.
Dynamic typing: Python is dynamically typed, meaning you don't to explicitly declare
variable types:
Large standard Library: Python provides a vast standard library with ready-to-use modules
and functions for various tasks, saving developers time and effort in implementing comman
Functionalities
Extensive Third-Party Libraries: Python has a vast ecosystem of third-party libraries and
frameworks that expand its capabilities in different domains, such as web development, data
analysis, and machine learning.
Integration Capabilities: Python can easily integrate, with other languages like C, C++, and
Java, allowing developers to leverage existing bases and libraries
Applications of Python
Python is widely used in various domains and offers numerous applications due to its
flexibility ease of use. Here are some key areas where python finds application:
Data Analysis and Visualization:- Python's rich ecosystem of libraries, including NumPy,
Pandas, and Matplotlib, make it a popular choice for data analysis and visualization It
enables professionals to process, manipulate and visualize data effectively.
Machine learning and Artificial Intelligence: Python has become the go-to language for
machine learning and Al projects. Libraries like Tensorflow, keras, and sakit-learn provide
powerful tools For implementing complex algorithms and training models
Automation and Scripting: Python's easy-to-read syntax and rapid development cycle make
it an ideal choice for automation and scripting and scripting tasks. It is commonly used for
tasks such as file manipulation, data parsing and system administration
Python was designed for readability, and has some similarities to the English language with
influence from mathematics.
Python uses new lines to complete a command, as opposed to other programming languages
which often use semicolons or parentheses.
Python relies on indentation, using whitespace, to define scope; such as the scope of loops,
functions and classes. Other programming languages often use curly-brackets for this
purpose.
Example
#Printing Hello World using python
The print() function is used to display the specified message or value on the console.
In this case, we pass the string "Hello, World!" as an argument to the print() function. The string is
enclosed in double quotes.
The # symbol indicates comment in Python . Comments are ignored by the interpreter and are used
to provide explanations or notes to the code.
Python Indentation:
In python indentation plays a crucial role in defining the structure and scope of code blocks. It is used
to group statements together and indicate which statemen belong to a particular block of code.
Python uses indentation instead of traditional braces or brackets of define code blocks.
The standard convention in Python is to use four spaces for indentation. It is recommended to be
consistent with indentation throughout your code to ensure readability and maintainability.
if condition
#code block!
Statement 1
Statement 2
statement 3
else:
#codeblock 2
Statement 4
statement 5
In above example, the if statement is followed by an indented block of code, which is considered as
the if-block
Modules in python:
Modules provide a way to organize your code logically, Instead of having all your cade in in a a single
file, you con split it into multiple modules based on their purpose. When you want to use the
functionality from a module , you can import it into your current program or another module.
This allows you to access and use functions, classes and variables defined within that module, you
can avoid writing the same code repeatedly and instead reuse the code defined in the module.
1. Built-in modules
2. External Modules
3. User-defined Modules
Built-in modules:
These are modules that come pre-installed with python. They are part of the standard library and
provide a wide range of functionalities. Built in modules are need for additional readily available for
use without the need for additional installations.
External Modules:
These are modules that are created by third-party developers and are not part of the standard
library. They extended Python's capabilities by providing additional functionalities for specific
purposes. External modules can be downloaded and installed using package managers like. pip
(python package index). Popular external modules include numpy for numerical computations.
These modules are created by the python programmers themselves. They allow users to organize
their code into separate files and reuse functionality across multiple programs. User-defined modules
can contain functions, classes, variables, and other code that can be imported and used in other
Python scripts or modules.
Comments in Python
Comments in Python are used to provide explanatory notes within the code that are not executed or
interpreted by the computer. They are helpful for improving code readability and for leaving
reminders or explanations for other developers who might work with the code in the future.
In Python, comments are denoted by the hash symbol (#) followed by the comment text. When the
Python interpreter encounters a comment, it ignores it and moves on to the next lines of code
Comments can be placed at the end of line or an a line by themselves. It's important to that
comments are meant for human readers and are not executed by the Python interpreter. Therefore,
they have no impact on the program's functionality or performance.
Types of comments
Single-line Comment
Multi-line Comment
1- Single-line comments
Single-line comments are used to add explanatory notes or comments on a single line of code. They
start with a hash symbol (#) (#) and continue until the end of the line Anything written after the hash
symbol is considered a comment and is ignored by the python interpreter.
Here's an example:
2. Multi-line Comments:
Multi-line comments, also known as block comments, allow you to add comments that spam
multiple lines. Python does not have a built-in syntax specifically for multi-line comments, but you
can achieve this by using triple quotes (either single or double) to create a string that is not assigned
to any variable Since it is not used elsewhere in the code, it arts as a comment.
Here's an example:
What is a pip?
In simple terms, pip is a package manager for python. It stands for "pip Installs Packages" or pip
install python. When working with python, you may need to use external libraries or modules that
provide additional functionalities beyond what the standard library offers. These libraries are often
developed by the Python Community and are available for anyone to use.
Pip makes it easy to install a package, manage and uninstall these external libraries. It helps you find
and download the libraries you need from the Python Package Index (PyPI), which is a repository of
Python packages maintained by the Community.
With pip, you can install a package by running a simple command in your terminal or command
prompt. It will automatically fetch the package from Papi and install it on your system, along with any
dependencies it requires!
Variables in Python
In Python, Variables are used to store values that can be used later in a program. You can think of
variables as containers that hold data. What makes python unique is that you don't need to explicitly
declare the type of a variable. You simply assign a value to a variable using the "=" operator.
For example, you can create a variable called "name" and assign it a value like this:
name = "Yadnyesh"
Here, "name" is the variable name, and "Yadnyesh" is the value assigned to it. Python will
automatically determine the type of variable based on the value assigned to it.
Variables in Python can hold different types of data ,such as numbers, strings, lists or even more
complex objects. You can change the value of a variable at any time by assigning a new value to it.
For instance:
age-25
Python also allows you to perform operations on variable. For example, you can add, substract,
multiply, or divide variables containing numbers. You can even combine variables of different types
using operators.
For instance:
x=5
y=3
greeting = "Hello"
name = "John"
message = greeting +" "+name # The value of 'message' will be "Hello John".
Variables provide a way to store and manipulate data in python, making it easier to work with
information throughput your program. By giving meaningful names to variables, you can make your
code more readable and understandable!
TOKENS IN PYTHON
(i) Keywords
(iv) Operators
(v) Punctuators
Keywords:
Keywords are predefined words with special meaning to the language compiler or interpreter. These
are reserved for special purpose and must not be used as normal identifier names. Keyword is a
word having special meaning reserved by programming language.
2. Identifiers (Names):
Identifiers are the names given to different parts of the program viz. variables, objects, classes,
functions, lists, dictionaries and so forth.
NOTE:
Myfile
DATE9_7_77
Z2T0Z9
FILE13
_HJI3_JK
MYFILE
The following are some invalid identifiers:
DATA-REC - contains special character - (hyphen) (other than A-Z, a-z and (underscore))
3. Literals/Values
Python allows several kinds of literals, which are being given below.
A string literal is a sequence of characters surrounded by quotes (single or double or triple quotes).
String literals can either be single line strings or multi-line strings.
Single line strings must terminate in one line i.e., the closing quotes should be on the same
line as that of the opening quotes. (See below)
Multiline strings are strings spread across multiple lines. With single and double quotes, each
line other that the concluding line has an end character as \ (backslash) but with triple
quotes, no backslash is needed at the end of intermediate lines. (see below)
Numeric literals are numeric values and these can be one of the following types:
(a) int (signed integers) often called just integers or ints, are positive or negative whole numbers
with no decimal point.
Decimal form: an integer beginning with digits 1-9. e.g., 1234, 4100 etc.
Octal form: an integer beginning with 00 (zero followed by letter o) e.g., 0035, 0077 etc. Here do
remember that for Octal, 8 and 9 are invalid digits.
Hexadecimal form: an integer beginning with 0x (zero followed by letter X) e.g., 0x73, OxAF etc. Here
remember that valid digits/letters for hexadecimal numbers are 0-9 and A-F.
(b) Floating Point Literals: Floating point literals or real literals floats represent real numbers and are
written with a decimal point dividing the integer and fractional parts are numbers having fractional
parts. These can be written in fractional form e.g., -13.0, 75, 7. etc. or in Exponent form e.g., 0.17E5,
3.E2, 6E4 etc.
(c) Complex number literals are of the form a + b), where a and b are floats and J (or) represents √-1,
which is an imaginary number). a is the real part of the number, and b is the imaginary part.
A Boolean literal in Python is used to represent one of the two Boolean values i.e., True (Boolean
true) or False (Boolean false). A Boolean literal can either have value as True or as False.
Python has one special literal, which is None. The None literal is used to indicate absence of value.
Python can also store literal collections, in the form of tuples and lists etc.
4. Operators
Operators are tokens that trigger some computation/action when applied to variables and other
objects in an expression.
The operators can be arithmetic operators (+, -, , /, %, *, //), bitwise operators (&, ^, 1), shift
operators (<<, >>), identity operators (is, is not), relational operators (>, <, >, <=, =, !=), logical
operators (and, or), assignment operator (), membership operators (in, not in), and arithmetic-
assignment operators (/, +, -, %, %, *, //-).
Arithmetic Operators:
Arithmetic Operators in python are used to perform mathematical calculations on numeric values.
The basic arithmetic operators include:
Addition (+): Adds two operands together. For example, if we have q = 10 and b = 10 then a + b
equals 20.
Subtraction (-): Subtracts the second operand from the first operand. If the first operand is smaller
than the second operand, the result will be negative For example if we have a = 20 and b = 5 , then
a-b equals 15.
Division (/): Divides the first operand by the other operand and returns the quotient. For example, if
we have a = 20 and b = 10 , then a/b equals 2.0.
Modulus (%): Returns the remainder, after dividing the first operand by the second operand. For
example, if we have a = 20 and b = 10 then a % b equals o.
Exponentiation (**) or power: Raises the first operand to the power of second operand.
Comparison Operators:
Comparison operator in python are used to compare two values and return a Boolean value (True or
False).
Assignment Operators:
Equal to (=): Assign the value on the right to the variable on the left.
Compound assignment operators (+=, -=, *=, /=): perform the specified arithmetic
operations and assign the result to variable.
Logical operators:
Logical operators in python are used to perform logical operations on Boolean values.
Logical AND (and): Returns true if both operands are true, otherwise false.
Logical OR (or): Returns true if one of them is true, otherwise false.
Logical Not (not): Returns the opposite boolean value of the operand.
Bitwise Operators:
Bitwise AND (&): Performs a bitwise AND operations on the binary representations of the
operands.
Bitwise OR(|): Performs a bitwise OR operation on the binary representations of the
operands.
Bitwise XOR (^): Performs a bitwise exclusive OR operation on the binary representation of
the operands.
Bitwise complement (~): Inverts the bits of the operands.
Left shift (<<): shifts the bit of the left operand to the left by the number of positions
specified by the right operand.
Right shift (>>): shift the bit of the left operand to the right by the number of positions
specified by right operand.
Membership Operators:
In: Returns true if both operands refer to the same object (sequence).
Not In: Returns true if both operands do not refers to the same object (sequence)
Identity operators:
5. Punctuators:
Punctuators are symbols that are used in programming languages to organize sentence structures,
and indicate the rhythm and emphasis of expressions, statements, and program structure.
**#\()[]{)@,:.=
Blocks in Python:
In programming, a block is a set of statements that are grouped and treated as a single unit. Blocks
are used to define the scope of variables, control the flow of execution in conditional statements and
loops, and encapsulate code in functions, methods, or classes.
In general programming, a block is a section of code enclosed within curly braces {}. It defines a
scope, where the enclosed statements are treated as a single unit. Blocks help in organizing code,
controlling the flow of execution, and defining the visibility and lifetime of variables within a
program.
Characteristics of Blocks:
Scope: Blocks define a scope, which is a region of code where a variable can be accessed and
manipulated. Variables declared within a block are typically only accessible within that block.
Control Structures: Blocks are used with control structures such as if, else, for, while, do-
while, and switch to group multiple statements and control the flow of execution.
Functions and Methods: In programming languages that support functions and methods,
blocks are used to define the body of the function or method.
1. Basic Block
A basic block is a sequence of instructions in a program with a single entry point and a single exit
point. It usually doesn't contain any jump or branch instructions.
x = 10
y = 20
z=x+y
2. Function Block
A function block contains a set of instructions that perform a specific task. It starts with a function
definition and ends with a return statement.
A conditional block contains code that is executed based on a certain condition. It is usually defined
using if, and else statements.
x = 10
if x > 5:
print("x is greater than 5")
else:
print("x is less than or equal to 5")
4. Loop Block
A loop block contains code that is executed repeatedly as long as a certain condition is true. It is
defined using for and while loops.
For Loop
for i in range(5):
print(i)
While Loop
x=0
while x < 5:
print(x)
x += 1
5. Try-Except Block
A try-except block is used for exception handling. The code inside the try block is executed, and if an
exception occurs, the code inside the except block is executed.
try:
result = 10 / 0
except ZeroDivisionError:
print("Cannot divide by zero")
6. Class Block
A class block contains the definition of a class in object-oriented programming. It can contain
attributes and methods.
class Dog:
def __init__(self, name):
self.name = name
def bark(self):
print(f"{self.name} says Woof!")
7. Scope Block
A scope block defines the visibility and accessibility of variables within a program. In Python,
indentation is used to define the scope of variables.
x = 10 # Global variable
def my_function():
y = 20 # Local variable
print(x) # Access global variable
print(y) # Access local variable
my_function()
In the example above, x is a global variable, and y is a local variable defined within the scope of
the my_function() block.
8. Nested Blocks
Nested blocks refer to blocks that are defined within another block. They can be found within loops,
conditional statements, or function blocks.
Nested Loops
for i in range(3):
for j in range(3):
print(i, j)
x = 10
if x > 5:
if x < 15:
print("x is between 5 and 15")
Understanding the different types of blocks in programming and how to effectively use them is
crucial for writing clean, organized, and maintainable code. Proper use of blocks helps in improving
the readability and structure of the code, making it easier to understand and debug.
In Python, whitespace refers to characters such as spaces, tabs, and newlines. These characters are
used to separate tokens in the code, but more importantly, they are used to define the indentation
levels of code blocks.
Spaces and Tabs: Python allows you to use either spaces or tabs for indentation, but it is
recommended to use spaces. Mixing spaces and tabs can lead to syntax errors, especially in
Python 3, where the interpreter does not allow inconsistent indentation.
Newlines: Newlines are used to separate statements. In Python, each statement usually ends
with a newline character, although you can use a backslash (\) to continue a statement on
the next line.
if True:
else:
In this example, the statements inside the if and else blocks are indented by four spaces. This
indentation tells Python which statements belong to which block.
As mentioned earlier, indentation is used to define code blocks in Python. The most common use
cases are in control flow statements (if,else, for, while) and function and class definitions.
# Function definition
def greet(name):
print(f"Hello, {name}!")
return
# For loop
for i in range(5):
print(i)
# Class definition
class MyClass:
def __init__(self):
self.value = 0
def increment(self):
self.value += 1
Separating Tokens
Whitespace is also used to separate tokens in Python. For example, spaces are used to separate
keywords, variable names, and operators.
# Addition operation
result = 1 + 2
In this example, the spaces between 1, +, and 2 help Python distinguish between different tokens.
Continuing Statements
You can use a backslash (\) to continue a statement on the next line, which is useful when a
statement is too long to fit on one line.
Indentation Depth
The standard indentation depth in Python is four spaces. This is recommended by the Python
community and is widely adopted in Python codebases. Most Python Integrated Development
Environments (IDEs) and text editors can be configured to use four spaces for indentation.
Blank Lines
Blank lines are used to separate logical sections of code. For example, you can use blank lines to
separate functions or classes in a module.
def function1():
def function2():
It is common to use spaces around operators for better readability. For example, use a = b + c instead
of a=b+c.
result = 10 / 2
result = 10/2
4. Best Practices for Using Whitespace
Consistency
Consistency is key when it comes to using whitespace in Python. Stick to using either spaces or tabs
for indentation, and avoid mixing them. It is recommended to use four spaces for indentation.
Readability
Use whitespace to improve the readability of your code. Add blank lines to separate logical sections,
and use spaces around operators and between tokens. However, avoid using too much whitespace,
as it can make the code look cluttered.
Dynamic typing:
Dynamic typing is one of Python's core features that sets it apart from statically typed languages. In
Python, variables are not bound to a specific type at declaration. Instead, the type is determined at
runtime based on the assigned value. This means that a single variable can hold data of different
types throughout its lifetime hence making Python a flexible and easy-to-use language for rapid
development and prototyping.
Example
Let's see a simple example demonstrating how a variable's type can change during execution:
x = 42
Output
Explanation:
This dynamic behavior allows Python developers to write flexible and concise code without
worrying about type declarations.
Benefits of Dynamic Typing
Flexibility: Variables can change types over time which can simplify code during rapid
prototyping or when handling data that may vary in type.
Ease of Use: Developers don't need to explicitly declare types, which can reduce boilerplate
code and make the language more accessible, especially to beginners.
Rapid Development: Since types are determined at runtime, developers can iterate quickly
without the overhead of static type checks during the coding process.
Runtime Errors – Type-related issues are detected only at runtime leading to unexpected
crashes if incompatible types are used.
Reduced Performance – Since types are determined dynamically, Python incurs extra
overhead compared to statically typed languages.
Code Maintainability Issues – Without explicit types understanding variable types in large
codebases can be difficult thereby making debugging harder.
Data Types:
Data types in Python refer to the different kinds of values that can be assigned to variables. They
determine the nature of the data and the operations that can be performed on them.
Python provides several built-in-data types, including: numeric, dictionary, Boolean, set, sequence
types and numeric has Integer, Complex Number, Float and Sequence Type has string, List and Tuple.
1. Numeric:
Python supports different numerical data Types, including integers (whole numbers), Floating-point
numbers (decimal numbers), and complex numbers (numbers with real and imaginary parts.
Integers (int): Integers represent whole numbers without any fractional part. For example,
age = 25.
Floating-point Numbers (Float): Floating-point numbers represent numbers with decimal
point or Fractions. For example, pi =3.14.
Complex Numbers (Complex): Complex numbers have a real and imaginary part. For ex: ス=
2+3j where j is suffix with it.
2. Dictionary:
Dictionaries are key-value pairs enclosed by curly braces. Each value is associated with a unique key
allowing for efficient lookup and retrieval, For example, person = {"name': 'John', 'age’ : 25, 'city’:
'New York'}
3. Boolean
Boolean (bool): Booleans represents truth values, either True or False. They are used for logical
operations and conditions for example, is_valid = True
4. Set:
Sets (set): sets are unordered collections of unique elements enclosed in curly braces. They are
useful for mathematical operations such as union, intersection and difference. For example,
5. Sequence Type:
Sequences represent a collection of elements and Include data types like strings, lists, and tuples.
Strings are used to store textual data, while lists and tuples are used to store ordered collections of
items.
strings (str): String represent sequences of character enclosed within single or double
quotes.
For example : name = 'John'
List(list): lists are ordered sequences of element enclosed in square brackets. Each element
be of any data type.
For example numbers = [1,2,3,4]
Tuples (tuple): Tuple are similar to lists but are immutable, meaning their elements, cannot
be changed once defined. They are enclosed in '()' parathesis
A Python program may contain various elements such as comments, statements, expressions etc.
Let us talk about the basic structure of a Python program.
As you can see that the above sample program contains various components like:
1. Expressions, which are any legal combination of symbols that represents a value.
2. Statements, which are programming instructions.
3. Comments, which are the additional readable information to clarify the source code.
4. Comments can be single line comments, that start with and multi-line comments that
can be either triple-quoted strings or multiple style comments.
5. Functions, which are named code-sections and can be reused by specifying their names
(function calls).
6. Block(s) or suite(s), which is a group of statements which are part of another statement
or a function. All statements inside a block or suite are indented at the same level.