PYTHON NOTES
UNIT-1
CO 1 Interpret the fundamental Python syntax and semantics and be fluent in the use of
Python control flow statements
PythonIDE:
PythonIDE(IntegratedDevelopmentEnvironment)understandyourcodemuchbetter
thana
[Link],codelining,testingand
[Link]
complicatedtouse.
ListofsomefamouspythonIDEareasfollows:
1. PyCharm
2. Jupyter
3. Qtdesigner
4. Spyder5. Atom
Python Variables
Python Variable is containers that store values. Python is not “statically typed”.
We do not need to declare variables before using them or declare their type. A
variable is created the moment we first assign a value to it. A Python variable is a
name given to a memory location. It is the basic unit of storage in a program. In
this article, we will see how to define a variable in python
Syntax,
a=5
b=”Hello”
c=4.6
print(a)
print(b)
print(c)
output:
5
Hello
4.6
PYTHON BASIC OPERATORS
1. An operator is a symbol that represents an operation that may be
performed on one or more operands.
2. Operators are constructs used to modify the values of operands.
3. Operators that take one operand are called unary operators.
4. Operators that take two operands are called binary operators.
5. Based on functionality operators are categories into following seven
types :
i. Arithmetic operators.
ii. Assignment operators.
iii. Bitwise operators.
iv. Comparison operators.
v. Identity operators.
vi. Logical operators.
vii. Membership operators
Arithmetic operators : These operators are used to perform arithmetic
operation such as addition, subtraction, multiplication and division.
Table 1.16.1. List of arithmetic operators.
Operator Description Example
+ Addition operator to add two operands. 10 + 20 = 30
– Subtraction operator to subtract two operands. 10 – 20 = –10
× Multiplication operator to multiply two operands. 10 × 20 = 200
/ Division operator to divide left hand by 5 / 2 = 2.5
right hand operator.
** Exponential operator to calculate power. 5 ** 2 = 25
% Modulus operator to find remainder. 5 % 2 = 1
/ / Floor division operator to find the quotient and 5 / / 2 = 2
remove the fractional part.
Comparison operators : These operators are used to compare values. It is
also called relational operators. The result of these operator is always a
Boolean value i.e., true or false.
= = Operator to check whether two operand 10 = = 20, false
are equal.
! = or <> Operator to check whether two operand 10 ! = 20, true
are not equal.
> Operator to check whether first operand 10 > 20, false
is greater than second operand.
< Operator to check whether first operand 10 < 20, true
is smaller than second operand.
> = Operator to check whether first operand 10 > = 20, false
is greater than or equal to second operand.
< = Operator to check whether first operand 10 < = 20, true
Assignment operators : This operator is used to store right side operands
in the left side operand.
= Store right side operand in left side operand. a = b + c
+ = Add right side operand to left side operand and a + = b or
store the result in left side operand a = a + b
– = Subtract right side operand to left side operand a – = b or
and store the result in left side operand a = a – b
* = Multiply right side operand with left side operand a * = b or
and store the result in left side operand a = a * b
/ = Divide left side operand by right side operand a / = b or
and store the result in left side operand a = a / b
% = Find the modulus and store the remainder a % = b or
in left side operand a = a % b
* * = Find the exponential and store the result a * * = b or
in left side operand a = a * * b
/ / = Find the floor division and store the result a / / = b or
in left side operand a = a / / b
UNDERSTANDING PYTHON BLOCKS
In Python, blocks are fundamental for structuring your code. They group together
statements that are executed as a unit and define things like scope and flow control.
Here's a breakdown of the key points:
What are Blocks?
A block is a collection of Python statements grouped by indentation.
All statements indented at the same level belong to the same block.
Increased indentation creates nested blocks.
Examples of Blocks:
Function Body: The indented lines within a function definition create a block that
defines the function's logic.
Conditional Statements: The indented statements following an if, elif, or else
statement form a block that executes only when the condition is true.
Loops: The indented statements following a for or while loop form a block that
executes repeatedly based on the loop's condition.
Entire Script: A Python script itself is considered a block, where all the statements are
executed sequentially.
Why Use Blocks?
Scope: Blocks control the visibility of variables. Variables defined within a block are
only accessible within that block and nested blocks indented further within it. This helps
prevent naming conflicts and keeps your code organized.
Flow Control: Blocks allow you to group statements that execute together based on
conditions or loops. This makes your code more readable and easier to maintain.
Indentation is Key!
Unlike many other programming languages that use curly braces {} to define blocks,
Python relies solely on indentation.
Proper indentation (typically 4 spaces) is crucial for Python to recognize blocks
correctly.
Inconsistent indentation can lead to errors.
Additional Points:
Blocks can contain other blocks, creating nested structures for complex logic.
Some interactive commands in the Python interpreter can also be considered single-
statement blocks.
By understanding Python blocks and indentation, you'll be well on your way to writing
clear, well-structured, and maintainable Python code.
PYTHON DATA TYPES
In Python, data types define the kind of value a variable can hold and the operations
that can be performed on it. Understanding data types is essential for working
effectively with Python. Here's a breakdown of the common data types:
Numeric Types:
int: Represents whole numbers (positive, negative, or zero) with unlimited precision.
float: Represents floating-point numbers (numbers with decimal places) for
approximate real numbers.
complex: Represents complex numbers (numbers with a real and imaginary part).
String Type:
str: Represents sequences of characters, used for text data enclosed in single or
double quotes.
Sequence Types:
list: An ordered, changeable collection of items enclosed in square brackets []. Items
can be of different data types.
tuple: An ordered, immutable collection of items enclosed in parentheses (). Elements
cannot be changed after creation.
range: Represents a sequence of numbers within a specified range. Useful for loops.
Other Built-in Types:
bool: Represents Boolean values, True or False.
set: An unordered collection of unique items enclosed in curly braces {}. Useful for
checking membership and removing duplicates.
dict: An unordered collection of key-value pairs enclosed in curly braces {}. Keys are
used to access values.
bytes: Represents binary data sequences.
bytearray: A mutable version of bytes for manipulating binary data.
memoryview: Allows memory sharing between objects.
None: Represents the absence of a value.
How to Check Data Type:
You can use the type() function to determine the data type of a variable in Python.
Example:
Python
age = 30 # int
salary = 12345.67 # float
message = "Hello, world!" # str
numbers = [1, 2, 3] # list
is_valid = True # bool
Understanding data types is crucial for writing correct and efficient Python code.
Choose the appropriate data type based on the kind of data you're working with to
ensure your code functions as expected.
DECLARING AND USING NUMERIC DATA TYPES
numeric data types are fundamental for storing and manipulating numerical values in
Python. Here's a breakdown of the common numeric data types and how to use them:
1. int (integer):
Represents whole numbers (positive, negative, or zero) with unlimited precision.
In Python, integers don't have a specific size limit.
Example:
Python
age = 30
num_items = -100
2. float (floating-point):
Represents real numbers with decimal places.
Used for approximate or continuous values.
By default, float uses about 15 decimal places of precision.
Example:
Python
pi = 3.14159 # Can store only upto 15 decimal places accurately
avogadro_constant = 6.0221413e23 # Scientific notation for large numbers
3. complex:
Represents complex numbers, which consist of a real part and an imaginary part.
Imaginary unit is denoted by 'j'.
Example:
Python
z = 3 + 4j
Declaring and Using:
You simply assign values to variables using the data type or without explicitly
mentioning it. Python automatically assigns the data type based on the value assigned.
Python
age = 25 # int
price = 19.99 # float
is_complex = True # bool (not a numeric data type, but included for
demonstration)
By understanding and using numeric data types effectively, you can perform various
numerical computations and data analysis tasks in Python.
PRACTICE PYTHON QUESTIONS
1. What is Python? What are the benefits of using Python
Python is a high-level, interpreted, general-purpose programming language. Being a
general-purpose language, it can be used to build almost any type of application with
the right tools/libraries. Additionally, python supports objects, modules, threads,
exception-handling, and automatic memory management which help in modelling real-
world problems and building applications to solve these problems.
Benefits of using Python:
Python is a general-purpose programming language that has a simple, easy-to-learn
syntax that emphasizes readability and therefore reduces the cost of program
maintenance. Moreover, the language is capable of scripting, is completely open-
source, and supports third-party packages encouraging modularity and code reuse.
Its high-level data structures, combined with dynamic typing and dynamic binding,
attract a huge community of developers for Rapid Application Development and
deployment.
2. What is a dynamically typed language?
Before we understand a dynamically typed language, we should learn about what typing
is. Typing refers to type-checking in programming languages. In a strongly-typed
language, such as Python, "1" + 2 will result in a type error since these languages don't
allow for "type-coercion" (implicit conversion of data types). On the other hand, a
weakly-typed language, such as Javascript, will simply output "12" as result.
Type-checking can be done at two stages -
Static - Data Types are checked before execution.
Dynamic - Data Types are checked during execution.
Python is an interpreted language, executes each statement line by line and thus type-
checking is done on the fly, during execution. Hence, Python is a Dynamically Typed
Language.
3. What is an Interpreted language?
An Interpreted language executes its statements line by line. Languages such as
Python, Javascript, R, PHP, and Ruby are prime examples of Interpreted languages.
Programs written in an interpreted language runs directly from the source code, with no
intermediary compilation step.
4. What is PEP 8 and why is it important?
PEP stands for Python Enhancement Proposal. A PEP is an official design document
providing information to the Python community, or describing a new feature for Python
or its processes. PEP 8 is especially important since it documents the style guidelines
for
Python Code. Apparently contributing to the Python open-source community requires
you to follow these style guidelines sincerely and strictly.
5. What is Scope in Python?
Every object in Python functions within a scope. A scope is a block of code where an
object in Python remains relevant. Namespaces uniquely identify all the objects inside a
program. However, these namespaces also have a scope defined for them where you
could use their objects without any prefix. A few examples of scope created during code
execution in Python are as follows:
A local scope refers to the local objects available in the current function.
A global scope refers to the objects available throughout the code execution since their
inception.
A module-level scope refers to the global objects of the current module accessible in
the program.
An outermost scope refers to all the built-in names callable in the program. The
objects in this scope are searched last to find the name referenced.
Note: Local scope objects can be synced with global scope objects using keywords
such as global.