Introduction to Python
• Basics of Python programming. Python interpreter-interactive and script mode, the structure
of a program.
• Indentation, identifiers. Keywords. Constants, variables types of operators precedence of
operators, data
• Types, mutable and immutable data types,
• statements, expressions, evaluation and comments, input and output statements
• Data type conversion, debugging.
• Control Statements: if-else if-elif-else, while loop, for loop
What is Python?
• High-level programming language
• Easy to read and write
• Interpreted language (code runs directly, no need to compile)
Key Features
• Simple syntax similar to English
• Dynamic typing (no need to declare variable types)
• Supports multiple programming paradigms (procedural, object-oriented, functional)
• Extensive standard library and third-party modules
• Large community and support
Installing Python
1. Download from the official website ([Link])
2. Follow the installation instructions for your operating system
Running Python Code (Interactive and Script mode)
1. Interactive mode: Type python in your terminal/command prompt
2. Script mode: Write code in a file with a .py extension and run it using python [Link]
The structure of a Python program
A simple python program to add two numbers
15
Indentation
❖ Indentation refers to adding white spaces before lines of code in a python program.
❖ Indentation in Python is used to create a group of statements that are executed as a block.
Example:
Identifiers
• Names given to various program elements such as variables, functions, classes, etc.
• Rules:
o Must start with a letter (a-z, A-Z) or an underscore (_)
o Followed by letters, digits (0-9), or underscores
o Case-sensitive (e.g. var and Var are different)
o Cannot be a reserved keyword
Keywords
• Reserved words with special meaning in Python
• Cannot be used as identifiers
• Examples: False, class, finally, is, return, None, continue, for, lambda, try, etc.
Constants
• Fixed values that do not change during program execution
• Examples: numbers (5, 3.14), strings ("Hello", 'World')
• In Python, constants are usually defined in all uppercase letters as a convention (e.g., PI = 3.14)
Variables
• Named storage locations in memory used to store data
• Created by assigning a value using the assignment operator (=)
• Examples: x = 5, name = "Alice"
• Variable names should be descriptive and follow identifier rules
Types of Operators
• Arithmetic Operators: + (addition), - (subtraction), * (multiplication), / (division), % (modulus), **
(exponentiation), // (floor division)
• Comparison (Relational) Operators: == (equal to), != (not equal to), > (greater than), < (less than),
>= (greater than or equal to), <= (less than or equal to)
• Assignment Operators: = (assignment), += (add and assign), -= (subtract and assign), *= (multiply
and assign), /= (divide and assign), %= (modulus and assign), **= (exponent and assign), //= (floor
division and assign)
• Logical Operators: and, or, not
• Bitwise Operators: & (AND), | (OR), ^ (XOR), ~ (NOT), << (left shift), >> (right shift)
• Membership Operators: in, not in
• Identity Operators: is, is not
16
Precedence of Operators
• Determines the order in which operators are evaluated in an expression
• Operators with higher precedence are evaluated before those with lower precedence
• Precedence order (from highest to lowest):
1. ** (exponentiation)
2. ~ (bitwise NOT), + (unary plus), - (unary minus)
3. *, /, //, % (multiplication, division, floor division, modulus)
4. +, - (addition, subtraction)
5. >>, << (right shift, left shift)
6. & (bitwise AND)
7. ^ (bitwise XOR)
8. | (bitwise OR)
9. ==, !=, >, >=, <, <= (comparison operators)
10. =, +=, -=, *=, /=, %=, **=, //=, &=, |=, ^=, >>=, <<= (assignment operators)
11. not (logical NOT)
12. and (logical AND)
13. or (logical OR)
• Parentheses () can be used to override precedence and force a specific order of evaluation.
Data Types
• Numeric Types
o int: Integer values (e.g., 1, 42, -7)
o float: Floating-point (decimal) values (e.g., 3.14, -0.001)
o complex: Complex numbers (e.g., 2 + 3j)
• Sequence Types
o str: String of characters (e.g., "hello", 'world')
o list: Ordered, mutable collection (e.g., [1, 2, 3], ['a', 'b', 'c'])
o tuple: Ordered, immutable collection (e.g., (1, 2, 3), ('a', 'b', 'c'))
o range: Sequence of numbers (e.g., range(10), range(1, 5))
• Mapping Type
o dict: Key-value pairs (e.g., {'name': 'Alice', 'age': 25})
• Set Types
o set: Unordered collection of unique elements (e.g., {1, 2, 3}, {'a', 'b', 'c'})
• Boolean Type
o bool: Boolean values True or False
• None Type
o None: Represents the absence of a value (e.g., None)
Mutable and Immutable Data Types
• Mutable Data Types
o Can be changed after creation (e.g., modifying elements, adding or removing elements)
o Examples:
▪ list: my_list = [1, 2, 3] (can add, remove, or change elements)
▪ dict: my_dict = {'key': 'value'} (can add, remove, or change key-value pairs)
▪ set: my_set = {1, 2, 3} (can add or remove elements)
• Immutable Data Types
o Cannot be changed after creation (any modification creates a new object)
o Examples:
▪ int: my_int = 5 (cannot change the value directly)
17
▪ float: my_float = 3.14 (cannot change the value directly)
▪ str: my_str = "hello" (cannot change characters directly)
▪ tuple: my_tuple = (1, 2, 3) (cannot change elements)
Statements
• Instructions executed by the Python interpreter.
• Types of statements:
o Expression statements: Evaluate an expression (e.g., a + b).
o Assignment statements: Assign values to variables (e.g., x = 5).
o Control flow statements: Direct the flow of execution (e.g., if, for, while, break, continue).
o Function definition: Define a function (e.g., def my_function():).
Expressions
• Combinations of variables, operators, and values that yield a result.
• Examples:
o Arithmetic expressions: 2 + 3.
o Logical expressions: a and b.
o String expressions: "Hello" + " " + "World".
• Can be part of a larger statement.
Evaluation
• The process of computing the result of an expression.
• Python evaluates expressions using the rules of precedence and associativity.
Comments
• Used to annotate code and make it more understandable.
• Single-line comments: Begin with # (e.g., # This is a comment).
• Multi-line comments: Enclosed in triple quotes (e.g., '''This is a multi-line comment''').
Input and Output Statements
• Input:
o input(): Reads a line of text input from the user (e.g., name = input("Enter your name: ")).
o Always returns a string.
• Output:
o print(): Outputs text or variables to the console (e.g., print("Hello, World!")).
o Can accept multiple arguments separated by commas (e.g., print("Name:", name)).
o Optional arguments like sep and end to customize the output (e.g., print("Hello", "World",
sep="-")).
Data Type Conversion
• Converting one data type to another.
• Common functions:
o int(): Converts a value to an integer (e.g., int("42")).
o float(): Converts a value to a float (e.g., float("3.14")).
o str(): Converts a value to a string (e.g., str(42)).
o list(): Converts a value to a list (e.g., list("abc") results in ['a', 'b', 'c']).
o tuple(): Converts a value to a tuple (e.g., tuple([1, 2, 3])).
o set(): Converts a value to a set (e.g., set([1, 2, 2, 3])).
18
o dict(): Converts a value to a dictionary (when applicable, e.g., dict([('a', 1), ('b', 2)])).
Debugging in Python
• Definition:
o The process of finding and fixing errors or bugs in your code.
• Common Debugging Techniques:
o Print Statements: Insert print() statements in your code to check values of variables and
program flow (e.g., print("Checkpoint reached"), print("Value of x:", x)).
o Using Assertions: assert statement to check if a condition is True, and if not, it raises an
AssertionError (e.g., assert x > 0, "x must be positive").
Control Statements in Python
• If Statement:
o Executes a block of code if a condition is true.
o Example:
• If-Else Statement:
o Executes one block of code if a condition is true, and another block if it is false.
o Example:
• If-elif-else Statement:
o Checks multiple conditions in sequence, executing the first block of code where the condition
is true.
o Example:
• While Loop:
o Repeats a block of code as long as a condition is true.
o Example:
o Can use break to exit the loop prematurely.
o Can use continue to skip to the next iteration.
For Loop
• For Loop:
19