Basics of Python Programming
Python was developed by Guido van Rossum in 1991 and has become one of
the most popular programming languages due to its versatility and simplicity.
It is commonly used for:
Software Development
Web Development (server-side)
Mathematics
Features of Python
1. Easy to Use: Python features a simple syntax that makes it user-friendly.
2. Interpreted Language: Code is executed and interpreted line by line,
simplifying debugging.
3. Cross-Platform Compatibility: Python can run seamlessly on Windows,
Linux, macOS, etc.
4. Expressive Language: Requires less code to achieve functionality, making
it intuitive and efficient.
5. Completeness: Comes with a wide range of built-in libraries and modules
for diverse applications.
6. Free & Open Source: Python can be downloaded for free, and its source
code is open for modification.
Shortcomings of Python
1. Fewer Libraries: Compared to other programming languages like C++ or
Java, Python has fewer built-in libraries.
2. Slow Language: As Python is an interpreted language, it executes
programs more slowly compared to compiled languages like C++ or Java.
3. Weak on Type-Binding: Python allows a single variable to hold different
data types, which can lead to runtime errors if not handled carefully.
Installing Python
Installing Python is quick and simple, requiring just two steps:
1. Download: Obtain the Python distribution from the official Python
website (python.org).
2. Install: Run the downloaded file and follow the installation process to set
up Python on your system.
Python Interpreter: How to Work in Python
After installing Python, you can work with it in two modes:
1. Interactive Mode
2. Script Mode
Python Interpreter: Interactive and Script Mode
1. Interactive Mode:
o Directly type and execute commands in the Python Shell.
o Example:
>>> print("Hello, World!")
Hello, World!
2. Script Mode:
o Write multiple lines of code in a .py file and execute it.
o Example: Save the following in example.py:
print("Hello, World!")
Run using:
python example.py
Structure of a Python Program
1. Modules and Imports: Import necessary libraries.
2. Statements: Python code is written line by line.
3. Functions (Optional): Reusable blocks of code.
Indentation
Python uses indentation (spaces/tabs) to define blocks of code.
Example:
if True:
print("Indented block") # Proper indentation
Identifiers, Keywords, Constants, and Variables
1. Identifiers: Names for variables, functions, etc. (e.g., my_variable).
2. Keywords: Reserved words like if, else, while.
3. Constants: Fixed values like PI = 3.14.
4. Variables: Store data values. Example:
x = 10 # x is a variable
Types of Operators and Precedence
1. Arithmetic: +, -, *, /, %, **.
2. Relational: >, <, >=, <=, ==, !=.
3. Logical: and, or, not.
4. Assignment: =, +=, -=, etc.
Operator Precedence in Python
Operator precedence determines the order in which operations are performed
in an expression. Here's a simplified hierarchy:
1. Parentheses (())
o Expressions inside parentheses are evaluated first.
o Example:
result = (2 + 3) * 4 # Output: 20
2. Exponents (**)
o Performed next, from right to left.
o Example:
result = 2 ** 3 ** 2 # Output: 512 (evaluated as 2 ** (3 ** 2))
3. Multiplication/Division/Modulus/Floor Division (*, /, %, //)
o Evaluated from left to right.
o Example:
result = 10 / 2 * 5 # Output: 25.0
Note: Floor Division (//)throws away the decimal or fractional part and gives the
largest whole number
4. Addition/Subtraction (+, -)
o Evaluated last, from left to right.
o Example:
result = 10 + 2 - 5 # Output: 7
Conclusion:
Operator Precedence: Parentheses → Exponents →
Multiplication/Division → Addition/Subtraction
Complete Example
result = 10 + 2 * 3 ** 2 / 4 - 1
# Step-by-step:
# 1. Exponents: 3 ** 2 → 9
# 2. Multiplication/Division: 2 * 9 → 18, 18 / 4 → 4.5
# 3. Addition/Subtraction: 10 + 4.5 → 14.5, 14.5 - 1 → 13.5
print(result) # Output: 13.5
Data Types
1. Basic Data Types:
o Numeric (int, float, complex)
o Text (str)
o Boolean (bool)
1. Mutable Data Types
Definition: These are data types whose values can be modified after creation.
Examples:
o List: You can add, remove, or change elements in a list.
my_list = [1, 2, 3]
my_list[1] = 5 # Changes the second element to 5
o Dict: You can add, update, or delete key-value pairs.
my_dict = {"a": 1, "b": 2}
my_dict["c"] = 3 # Adds a new key-value pair
2. Immutable Data Types
Definition: These are data types whose values cannot be changed after creation. Any
operation that seems to modify them creates a new object instead.
Examples:
o Int: Changing an integer results in a new object.
x = 10
x = x + 5 # Creates a new integer object
o Float: Similar behavior to integers.
String: Modifying a string creates a new string object.
s = "hello"
s = s + " world" #
Mutable objects can be directly modified without creating a new object.
Immutable objects require creating a new object for any modification.
Statements, Expressions, and Evaluation
1. Statement: A single instruction (e.g., x = 5).
2. Expression: A combination of values and operators (e.g., x + y).
3. Evaluation: The process of computing an expression’s value.
Input and Output Statements
1. Input: Use input() to take user input.
Example:
name = input("Enter your name: ")
2. Output: Use print() to display output.
Example:
print("Hello, World!")
Data Type Conversion in Python
Data type conversion is the process of converting one data type into another.
Python provides two types of conversion:
1. Implicit Type Conversion
Automatically done by Python.
Happens when mixing compatible types.
Example:
x = 10 # Integer
y = 3.5 # Float
result = x + y # x is implicitly converted to float
print(result) # Output: 13.5
2. Explicit Type Conversion (Type Casting)
Done manually using built-in functions.
Commonly used conversion functions:
o int(): Converts to integer.
o float(): Converts to float.
o str(): Converts to string.
o list(), tuple(), set(): Converts between collections.
Examples:
# Integer to String
x = 10
print(str(x)) # Output: "10"
# String to Integer
s = "123"
print(int(s)) # Output: 123
# Float to Integer
f = 3.7
print(int(f)) # Output: 3 (truncates decimal)
Debugging
Process of identifying and fixing errors in a program.
Common tools: print() statements, Python debugger (pdb).