Python_minor_mod1
Python_minor_mod1
Introduction to Python, Features of Python, Different methods to run Python,Python IDE, Comments,
Indentation, Identifiers,Keywords, Variables, Standard Data Types, Input Output Functions, Import functions,
range function, Operators and Operands, Precedence of Operators, Associativity, Type Conversion, Multiple
Assignment, Expressions and Statements, Evaluation of Expressions, Boolean Expressions.
FEATURES
Easy to Learn and Use:
Python has a simple and clean syntax, making it easy for beginners to learn and use.
High-Level Language:
Python allows programmers to write instructions using human-friendly syntax and hides low-
level machine details.
Interpreted Language:
Python code is not compiled into machine code directly. It is executed line-by-line by the
Python interpreter, which makes debugging and testing easier.
Interactive:
Users can interact directly with the Python interpreter using the interactive shell (REPL) to
write and test code.
Dynamically Typed:
You don’t need to declare variable types. Python automatically detects the type at runtime.
Free and Open Source:
Python is free to download and use. It is also open source, with a large community contributing
to its development.
1
Portable Language:
Python runs on almost all major platforms. As long as a compatible interpreter is installed,
Python code runs the same across different systems.
Extendable:
You can add low-level modules (written in C, C++, etc.) to the Python interpreter to optimize
performance or customize functionality.
Database Support:
Python provides built-in and third-party libraries to connect and interact with major
commercial databases.
GUI Programming:
Python supports GUI development through libraries like Tkinter, PyQt, and others. These can
be used across platforms like Windows, macOS, and Unix.
Scalable:
Python supports clean code structure and modular programming, making it suitable for
developing large-scale applications.
Supports Multiple Programming Paradigms:
Python supports functional, structured, and object-oriented programming (OOP).
Scripting and Application Development:
Python can be used both as a scripting language and for developing complex applications,
using bytecode compilation.
Automatic Garbage Collection:
Python automatically manages memory and reclaims unused memory using its built-in garbage
collector.
Integratable:
Python can easily integrate with other languages like C, C++, and Java.
Powerful:
Python offers features like dynamic typing, built-in data types and tools, an extensive standard
library, third-party modules (e.g., NumPy, SciPy), and automatic memory management.
2
You can also download Python documentation in HTML, PDF, and PostScript formats from:
🔗 https://www.python.org/doc/
python distributions are available for various platforms. You simply need to download the
appropriate binary file for your system and install it.
If a binary version is not available for your platform, you will need a C compiler to compile the
source code manually. This approach allows for greater flexibility in choosing features during
installation.
Installing Python on various platforms −
Unix and Linux Installation
Open a web browser and go to:
🔗 https://www.python.org/downloads/
Download the zipped source code for Unix/Linux.
Extract the downloaded files.
(Optional) Edit the Modules/Setup file to customize features.
Run the following commands in your terminal:
./configure
make
make install
Python will be installed at the default location:
/usr/local/bin for executables and
/usr/local/lib/python312/ for libraries, where 312 refers to Python version 3.12.
Windows Installation
Installing the Latest Version of Python on Windows (Python 3.13.x)
1. Download the Installer
o Open a web browser and go to the official Python download page:
🔗 https://www.python.org/downloads/
o Click on the latest Python version for Windows (e.g., Python 3.13.3) and download
the Windows installer (e.g., python-3.13.3-amd64.exe for 64-bit systems).
2. Run the Installer
o Locate the downloaded .exe file and double-click to run it.
o On the first screen of the installer:
✅ Check the box that says “Add Python to PATH” (very important).
Click on “Install Now” to begin installation using default settings.
3. Wait for Installation to Complete
3
o The installer will set up Python, pip (Python package manager), and the standard
library.
o Once done, you will see the “Setup was successful” screen.
4. Verify the Installation
o Open the Command Prompt (press Win + R, type cmd, and hit Enter).
o Type:
python --version
This should display the installed version, e.g., Python 3.13.3.
o Also try:
pip --version
to confirm pip was installed.
You can execute complete Python programs (saved with .py extension) via the command line:
Command format:
Windows:
C:\> python script.py
Linux/macOS:
$ python3 script.py
o The script file is saved with a .py extension.
o On Unix/Linux, the script has execution permissions (chmod +x script.py) if using a shebang line
(#!/usr/bin/env python3).
4
3.Using IDLE (Python’s Built-in IDE)
5
Steps to Run a Python Script using IDLE:
1. Open a text editor (e.g., Notepad or directly within IDLE).
2. Write the Python code and save the file with a .py extension.
(Example: demo.py — default directory might be C:\Users\<YourName>\)
3. Open IDLE (Python GUI).
4. From the File menu, choose Open and select your saved .py file.
5. The code will open in the Python Editor window.
6. Go to the Run menu and click Run Module (or simply press F5).
7. The output of the script will be displayed in the Python Shell window.
Example:
If you saved a file named demo.py with the following content:
print("Hello, Python!")
Running it through the steps above will display in the Python Shell:
Hello, Python!
2.PyCharm
Powerful Python IDE developed by JetBrains.
Available in two versions:
o Community Edition (free)
6
o Professional Edition (paid, includes web development and database tools)
Features:
o Smart code navigation and refactoring
o Integrated debugger and test runner
o Virtual environment and package management
o Django support (Professional version)
Platform: Windows, macOS, Linux
3.Jupyter Notebook / JupyterLab
Ideal for data science, machine learning, and research.
Allows code, output, markdown, and visualizations in the same document.
Often used with Anaconda distribution.
Features:
o Interactive coding with live output
o Integration with NumPy, pandas, matplotlib, etc.
o Supports multiple programming languages via kernels
4.Thonny
Beginner-friendly IDE designed for learning Python.
Simple interface with features like variable explorer and step-by-step debugger.
Good for schools and students.
Pre-installed with Python and easy to set up.
5.Spyder
Scientific Python IDE for data analysis and research.
Often used by scientists and engineers.
Built-in IPython console, variable explorer, and plotting support.
Python Interpreter
Python is an interpreted language – it runs code line by line, not all at once like compiled
languages.
Python does not convert code directly into machine code. Instead, it first converts the code
into bytecode.
The Python interpreter handles two main steps when running a program:
1. Compilation:
Python source code (.py file) is compiled into bytecode (.pyc file) which is a
more efficient, intermediate format..
Bytecode is saved in a folder called __pycache directory and help speed up
future execution.
7
2. Interpretation:
The Python Virtual Machine (PVM) reads and executes the bytecode.
It converts bytecode into machine-level instructions that the computer
understands.
The interpreter acts as both:
o A translator (from Python code to bytecode),
o And a runtime environment (executing the program).
Example of Interpreted Languages: Python, JavaScript, Ruby, PHP, Perl
Example of Compiled Languages: C, C++, C#, COBOL
Key Features of the Python Interpreter
The interpreter includes the Python Virtual Machine (PVM), which abstracts the underlying
hardware and ensures portability.
The most widely used implementation of the Python interpreter is CPython, written in C.
Python interpreters often include a REPL (Read-Eval-Print Loop), allowing developers to
interactively execute and test Python code snippets.
PYTHON COMMENTS
Comments in Python are lines of text that the interpreter ignores during execution.
They are used to explain the code, making it more readable and maintainable.
Single-line Comments
A comment starts with a # symbol. Everything after # on that line is ignored by Python.
# This is a comment
print("Hello, World!")
Comments can also appear at the end of a code line:
print("Hello, World!") # This is a comment
Multi-line Comments
Option 1: Multiple # symbols for each line
# This is a comment
# written in
# more than just one line
Option 2: Triple-quoted strings (''' or """)
You can use triple quotes for multiline comments.
These are ignored if not assigned to a variable.
"""
This is a comment
written in
8
more than just one line
"""
print("Hello, World!")
Note: Technically, triple-quoted strings are not true comments but multi-line string literals.
However, when unassigned, they are treated like comments.
Indentation in Python
In Python, indentation is used to define blocks of code. It tells the Python interpreter that a group of
statements belongs to a specific block. All statements with the same level of indentation are
considered part of the same block. Indentation is achieved using whitespace (spaces or tabs) at the
beginning of each line.
Example:
if 10 > 5:
print("This is true!")
print("I am tab indentation")
print("I have no indentation")
o The first two print statements are indented by 4 spaces, so they belong to the if block.
o The third print statement is not indented, so it is outside the if block.
9
Letters:
Uppercase and lowercase alphabets A–Z, a–z
Digits:
Numeric characters 0–9
Special Symbols:
Symbols used in expressions and syntax +, -, *, /, (, ), {}, [], =, <, >, etc.
Whitespaces:
Non-printing characters used for spacing
o Space
o Tab (\t)
o Newline (\n)
o Carriage return (\r)
o Form feed (\f)
Other Characters:
Python supports all ASCII characters and Unicode characters. These can be used in strings,
identifiers, or other data elements.
TOKENS
A token is the smallest individual unit in a python program. All statements and instructions in a
program are built with tokens. Python breaks each logical line into a sequence of elementary lexical
components Known as Tokens.
Python has the following tokens:
(i) Keyword
(ii) Identifiers
(iii) Literals
(iv) Operators
(v) Punctuator
KEYWORDS
Keywords are special words used by Python interpreter to recognize the structure of program.
As these words have specific meaning for interpreter, they cannot be used for any other purpose.
E.g. int, float,True,elif,else,break,as etc
For checking/displaying the list of keywords available in python use
>>>import keyword
>>>print(keyword.kwlist)
10
IDENTIFIERS
An Identifier is a name used to identify a variable, function, class, module or object.
E.g.: Sum, total_marks, regno, num1, Column31, _Total
Rules for Identifier:
It consist of letters and digits in any order except that the first character must be a letter letter
or an underscore (_) but no a digit.
The underscore (_) counts as a character.
Spaces are not allowed.
Special Characters are not allowed. Such as @,$ etc.
An identifier must not be a keyword of Python.
Variable names should be meaningful which easily depicts the logic.
Uppercase and lowercase are treated differently.
PYTHON LITERALS
Literals are fixed values or data items used directly in a program’s source code.
They are also known as constants because their value does not change during program execution.
Python supports several types of literals:
1. String Literals
Represent sequences of characters enclosed in single (') or double (") quotes.
Example:
a = "hello"
2. Numeric Literals
Integer Literals: Whole numbers without a decimal point.
Example:
p=2
a = 100
Floating Point Literals: Numbers with decimal points.
Example:
salary = 15000.00
3. Boolean Literals
Represent truth values: True and False (case-sensitive).
Used to represent logical values.
Example:
bool_1 = (6 > 10)
print(bool_1) # Output: False
11
4. Special Literal – None
Represents the absence of a value or a null value.
Often used to indicate that a variable has not been assigned a value yet.
Example:
value1 = 20
value2 = None
print(value1) # Output: 20
print(value2) # Output: None (no visible result in some contexts)
PUNCTUATORS/DELIMITERS
Punctuators (or delimiters) are symbols used in Python to organize the structure of programs. They
define the boundaries of statements, expressions, function calls, indexing, code blocks, and more
example
OPERATORS
Operators are special symbols in Python used to perform operations on variables and values.
The variables on which operations are performed are called operands.
Operators can be unary (work on one operand) or binary (work on two operands).
12
2. Comparison (Relational) Operators
Compare two values and return True or False.
= Assign c=a+b
4. Bitwise Operators
Bitwise operator works on bits and performs bit by bit operation.
Let a = 60 (0011 1100) and b = 13 (0000 1101)
Operator Description Example
& returns 1 if both the bits are 1, otherwise 0. (a & b)=12
(Binary AND) (means 0000 1100)
| eturns 1 if any of the bits is 1. If both the bits are 0, (a | b) = 61
(Binary OR) then it returns 0. (means 0011 1101)
^ returns 1 if one of the bits is 0 and the other bit is 1. (a ^ b) = 49
Binary XOR If both the bits are 0 or 1, then it returns 0. (means 0011 0001)
~ bitwise NOT operator (~), which expects just one (~a ) = -61
argument, making it the only unary bitwise
13
Binary Ones operator. It performs logical negation on a given (means 1100 0011 in 2's
Complement number by flipping all of its bits: complement form due to a
signed binary number.
<< The left operands value is moved left by the number a << 2 = 240
Binary Left of bits specified by the right operand. (means 1111 0000)
Shift
>> The left operands value is moved right by the a >> 2 = 15
Binary Right number of bits specified by the right operand. (means 0000 1111)
Shift
5. Logical Operators
Used to combine conditional statements.
6. Membership Operators
Check membership in a sequence like string, list, or tuple.
7. Identity Operators
Check if two variables refer to the same object.
14
Here 5 - 7 is an expression.There can be more than one operator in an expression.To evaluate these
types of expressions there is a rule of precedence in Python. It guides the order in which these
operations are carried out.
Precedence Operators
Highest () Parentheses
** Exponentiation
+x, -x, ~x Unary operations
*, /, //, %
+, -
<<, >>
&
^
`
Comparisons: ==, !=, >, <, >=, <=, is, is not, in, not in
not
and
Lowest or
ASSOCIATIVITY OF OPERATORS
Associativity is the order in which an expression is evaluated that has multiple operators of the same
precedence. Left to Right: Most operators follow this.
Right to Left: Only ** (exponentiation).
Example:
12 + 3 * 4 - 6 / 2
= 12 + 12 - 3.0
= 21.0
Note:
Comparisons like x < y < z mean: x < y and y < z, not nested comparisons.
Assignment and comparison operators are non-associative.
15
Example:
a = 10
b = 10.5
c = True
d = 1 + 5j
print(type(a)) # <class 'int'>
print(type(b)) # <class 'float'>
print(type(c)) # <class 'bool'>
print(type(d)) # <class 'complex'>
o = 0o12 # octal
print(o) # 10
h = 0x12 # hexadecimal
print(h) # 18
16
x = int('100') # converting string to int
print(x) # 100
2. Float (float)
Represents real numbers with a fractional part.
Can also use scientific notation using e or E.
Examples:
f = 1.2
print(f) # 1.2
print(type(f)) # <class 'float'>
f = 1e3
print(f) # 1000.0
f = float('5.5')
print(f) # 5.5
3. Complex (complex)
Represents a complex number in the form (real part) + (imaginary part)j
Use j or J to denote the imaginary part.
Examples:
a=5
print(type(a)) # <class 'int'>
b = 5.0
print(type(b)) # <class 'float'>
c = 2 + 4j
print(type(c)) # <class 'complex'>
Sequence Data Types
A sequence is an ordered collection of elements. It allows multiple values to be stored efficiently.
Main sequence types:
String
List
Tuple
1. String (str)
A string is a sequence of characters enclosed in single, double, or triple quotes.
Python has no char type; a single character is a string of length one.
17
Examples:
String1 = 'Welcome to the Geeks World'
print("Single Quotes:", String1)
Python Expressions
An expression is a combination of values, variables, operators, and function calls that
produces a result.
Expressions are evaluated to a single value.
18
Example:
x=5
y=3
z = x + y # This is an expression. z will be 8.
Evaluation of an expression
Evaluation means computing the result of the expression.
x=5
y=3
z = x + y # z = 8 after evaluation
19
locals (optional)- a mapping object. Dictionary is the standard and commonly used mapping
type in Python.
Example:
x=1
print(eval('x + 1')) # Output: 2
print() FUNCTION
The print() function prints the specified message to the screen, or other standard output device.
The message can be a string, or any other object, the object will be converted into a string
before written to the screen.
Syntax:
print(object(s), sep=' ', end='\n', file=sys.stdout, flush=False)
Parameter Description
object(s) One or more objects to be printed
sep Optional. Separator between objects. Default: space
end Optional. What to print at the end. Default: newline \n
file Optional. Where to print. Default: screen
flush Optional. True to flush the output buffer
Examples:
print("Hello", "World") # Output: Hello World
print("Hello", "World", sep="---") # Output: Hello---World
print("Hello", end=" ") # Output: Hello (without newline)
print("How are you?") # Output: How are you?
Variables
In Python, variables are used to store data values. Python is a dynamically-typed language, meaning
you don't need to declare the type of a variable explicitly—it is determined automatically based on
the value assigned.
Key Features of Python Variables:
Dynamic Typing: A variable can hold different types of values during execution.
a= 10 # Integer
x = "Hello" # String
No Declaration Needed: Variables are created when you assign a value to them.
name= "Alice"
age = 25
Multiple Assignments:
Python supports simultaneous assignment to multiple variables.
20
Syntax
Var1,var2,var3,……..=exp1,exp2,exp3..expn
Python simultaneously evaluates all the expressions on the right and assign them to a corresponding
variable on the left.
Assigning the same value to multiple variables:
a=b=c=5
Assigning different values to multiple variables in one line:
x, y, z = 1, 2, 3
Variable Naming Rules:
Must start with a letter or an underscore (_).
Cannot start with a number.
Can only contain alphanumeric characters and underscores.
Case-sensitive (myVar and myvar are different).
Variable Types: Python supports various data types, such as:
Integer: x = 10
Float: y = 3.14
String: name = "Alice"
Boolean: is_active = True
List: fruits = ["apple", "banana"]
Tuple: coordinates = (10, 20)
Dictionary: person = {"name": "Alice", "age": 25}
Type Checking: Use the type() function to check the type of a variable.
x = 10
print(type(x)) # Output: <class 'int'>
range() Function
The range() function returns a sequence of numbers, starting from 0 by default, and increments by 1
(by default), and stops before a specified number.
Syntax
range(start, stop, step)
Parameter Description
start Optional. An integer number specifying at which position to start. Default is 0
stop Required. An integer number specifying at which position to stop (not included).
step Optional. An integer number specifying the incrementation. Default is 1
21
Example
for i in range(5):
print(i, end=" ")
print()
Output:
01234
range() allows the user to generate a series of numbers within a given range. Depending on how
many arguments the user is passing to the function, the user can decide where that series of numbers
will begin and end, as well as how big the difference will be between one number and the next.
Import in Python
In Python, modules help organize code into reusable files. They allow you to import and use
functions, classes and variables from other scripts. The import statement is the most common way to
bring external functionality into your Python program.
Importing a Module
The most common way to use a module is by importing it with the import statement. This allows
access to all the functions and variables defined in the module.
Example:
22
import math
pie = math.pi
print("Value of pi:", pie)
Output
Value of pi: 3.141592653589793
Output
3.141592653589793
23
Output
Square root of 25: 5.0
Type Conversion
The Type Conversion is the process of converting the value of one data type to another data type. In
general, Type Conversion classified into two types
1. Implicit Type Conversion (Coercion)
2. Explicit Type Conversion( Type Casting )
Implicit Type Conversion :
In Implicit type conversion, Python interpreter automatically converts one data type to another data
type.In this Type Conversion the python interpreter converts lower datatype to higher datatype to
avoid data loss.
num1 = 15 #int
num2 = 4.5 #float
num3 = num1 + num2
print("Value of num3:",num3)
print("Datatype of num3:",type(num3))
output
Value of num3: 19.5
datatype of num3: <class 'float'>
In the above example, we are trying to add two variable values(num1 is integer datatype & num2 is
folat datatype),but resultant variable(num3) is float datatype, because python interpreter converts
lower datatype(integer) to higher datatype(float) to avoid data loss.
24
Explicit Type Conversion ( Type Casting ) :
In Explicit type conversion, The user converts one data type to another data type.In this Type
Conversion the user converts higher datatype to lower datatype or lower datatype to higher datatype.
With explicit type conversion, there is a risk of data loss since we are forcing an expression to be
changed in some specific data type. An Explicit type conversion is also called as Type Casting in
Python
Example2
a = float(2) # returns 2.0
b = float(3.2) # returns 3.2
c = float("6") # returns 6.0
d = float("6.2") # returns 6.2
print(a)
25
print(b)
print(c)
print(d)
output
2.0
3.2
6.0
6.2
Expressions in Python
An expression is a combination of operators and operands that is interpreted to produce some other
value. In any programming language, an expression is evaluated as per the precedence of its
operators. So that if there is more than one operator in an expression, their precedence decides which
operation will be performed first. We have many different types of expressions in Python.
1. Constant Expressions: These are the expressions that have constant values only.
Example:
# Constant Expressions
x = 15 + 1.3
print(x)
Output
16.3
26
Output
52
28
480
3.3333333333333335
3. Integral Expressions: These are the kind of expressions that produce only integer results after all
computations and type conversions.
Example:
# Integral Expressions
a = 13
b = 12.0
c = a + int(b)
print(c)
Output
25
4. Floating Expressions: These are the kind of expressions which produce floating point numbers as
result after all computations and type conversions.
Example:
# Floating Expressions
a = 13
b=5
c=a/b
print(c)
Output
2.6
27
Output
22
52
22
Statement in Python
A Python statement is an instruction that the Python interpreter can execute. There are different types
of statements in Python language as Assignment statements, Conditional statements, Looping
statements, etc. The token character NEWLINE is used to end a statement in Python. It signifies that
each line of a Python script contains a statement. These all help the user to get the required output.
28
Declared using parentheses () :
n = (1 * 2 * 3 + 7 + 8 + 9)
Boolean expressions
A boolean expression is an expression that is either true or false. The following examples use the
operator ==, which compares two operands and produces True if they are equal and False otherwise:
Example
print(5 == 6)
print("Is five equal 5 to the result of 3 + 2?")
print(5 == (3 + 2))
print("Does five equal six?")
print(5 == 6)
The == operator is one of six common comparison operators which all produce a bool result.
x == y # Produce True if ... x is equal to y
x != y # ... x is not equal to y
x>y # ... x is greater than y
x<y # ... x is less than y
x >= y # ... x is greater than or equal to y
x <= y # ... x is less than or equal to y
bool() Function: This built-in function can evaluate any value and return its Boolean equivalent.
Most values with content (non-empty strings, non-zero numbers, non-empty lists, tuples,
dictionaries, sets) evaluate to True.
29
Empty strings, the number 0, and empty collections evaluate to False.
Python
print(bool("Hello")) # True
print(bool(0)) # False
print(bool([])) # False
Usage of Boolean Expressions:
Boolean expressions are fundamental for controlling program flow, especially in:
Conditional statements (if, elif, else): To execute specific blocks of code based on whether a
condition is True or False.
Loops (while): To determine whether a loop should continue iterating.
Function returns: Functions can return True or False to indicate success, failure, or a specific state.
30