Introduction to Python
Python is a high-level, interpreted, general-purpose programming
language created by Guido van Rossum in 1991.
Features of Python
•Easy to Learn and Use: Python has a simple, clean syntax that's similar to plain
English. This reduces the time and effort required to learn the language.
•High-level Language: Programmers don't need to worry about low-level details like
memory management.
•Interpreted Language: The Python interpreter executes code line by line, which
makes it easier to debug programs.
•Platform Independent: Python programs can run on various operating systems like
Windows, macOS, and Linux without any changes.
•Extensive Libraries: Python has a vast collection of built-in libraries and third-party
modules that provide pre-written code for different tasks, saving development time.
•Dynamically Typed: You don't need to declare the data type of a variable. Python
automatically assigns the data type during execution.
Execution Modes of Python
Python code can be executed in two primary modes:
. Interactive Mode 💻
In interactive mode, the Python interpreter executes code as soon as you type it. It's
a great way to test out small snippets of code and get immediate feedback.
2. Script Mode 📜
In script mode, you write your Python code in a file, usually with a .py extension. The
entire file (script) is then executed by the interpreter.
Python Character Set:
A character set is a set of valid characters that a programming language can
recognize. Python recognizes all characters supported by Unicode, including:
•Alphabets: A-Z, a-z
•Digits: 0-9
•Special Characters: ! @ # $ % ^ & * ( ) _ - + = { } [ ] | \ : ; " ' < > , . ? /
•Whitespace Characters: space, tab, newline
Python Tokens
A token or a lexical unit is the smallest individual unit in a program. Python
breaks down a program into a series of tokens.
Keywords
Punctuators
Python
Tokens
Identifiers
Operators
Literals
Python Tokens
1. Keywords 🔑
Keywords are reserved words with a special meaning and function in the language. They cannot be
used as variable names or for any other purpose. Python has a fixed set of keywords.
•Examples: if, else, for, while, def, class, import, True, False, None.
2. Identifiers 🆔
An identifier is a name given to an entity like a variable, function, class, etc. Identifiers are used to
uniquely identify elements in a program.
•Rules for naming identifiers:
•They can contain letters (a-z, A-Z), digits (0-9), and the underscore _.
•They must start with a letter or an underscore.
•They are case-sensitive (e.g., myVar and myvar are different).
•Keywords cannot be used as identifiers.
•Examples: my_variable, age, studentName, _count.
Python Tokens
3. Literals 📝
Literals are fixed data values in a program. They are the actual values that you assign to
variables or use in expressions.
•String Literals: A sequence of characters enclosed in single quotes ('...'), double quotes ("..."),
or triple quotes ('''...''' or """...""").
•Example: "Hello", 'Python', '''Multi-line string'''.
•Numeric Literals:
•Integer: Whole numbers (e.g., 10, -5).
•Float: Numbers with a decimal point (e.g., 3.14, -0.5).
•Complex: Numbers with a real and imaginary part (e.g., 2 + 3j).
•Boolean Literals: Represent one of two values: True or False.
•Special Literal None: Represents the absence of a value.
Python Tokens
4. Operators ➕
Operators are symbols that perform operations on values and variables.
•Arithmetic Operators: +, -, *, /, % (modulo), ** (exponentiation), // (floor division).
•Relational Operators: == (equal to), != (not equal to), > (greater than), < (less than), >= (greater
than or equal to), <= (less than or equal to).
•Logical Operators: and, or, not.
5. Punctuators 📌
Punctuators are symbols that structure and organize statements.
•Examples: ( ), [ ], { }, ,, ., :, ;, @, =, etc.
Variables
A variable is a named storage location in memory used to store data. In Python, you
don't need to declare a variable's type. You simply assign a value to it, and Python
automatically determines the data type.
•Assignment: Use the = operator to assign a value to a variable.
•Example age = 16 # 'age' is a variable holding the
integer value 16
name = "Charlie" # 'name' is a variable holding the
string value "Charlie"
Concept of L-value and R-value
•L-value: Refers to a memory location that can appear on the left side of assignment operator
(=).
•R-value: Refers to data/value that can appear on the right side of assignment operator (=).
Example:
x = 10
•x → L-value (variable name)
•10 → R-value (constant)
Assigning Values to a Variable
Assigning Same Value to Multiple Variable
a = b = c = 10
Assigning Multiple Values to Multiple Variable
a,b,c = 10,20,30
Dynamic Typing and Static Typing
Dynamic Typing: A variable pointing to a value of a certain type, can be made to
point to a value/object of different type. This is called Dynamic Typing.
How it works:
•my_variable = 10 (The interpreter infers my_variable is an integer.)
•my_variable = "hello" (This is valid. The interpreter re-infers my_variable as a string.)
Examples: Python, JavaScript, Ruby, and PHP.
Static Typing
In statically typed languages, a variable's type is known at compile time. This means you must
explicitly declare the data type of a variable, and once it's set, it can't be changed. The compiler
checks for type mismatches before the program can execute.
•How it works:
•int my_number = 10;
•my_number = "hello"; (This will cause a compile-time error because my_number was
declared as an integer, and you're trying to assign a string to it.)
Examples: C, C++, Java, C#, Swift, and Go.
Use of Comments 💬
Comments are lines of code that the Python interpreter ignores during execution. They are used to
explain the code, making it more readable and understandable for humans.
•Single-line Comments: Start with the # symbol. Everything after the # on that line is a comment.
•Example:
# This is a single-line comment
age = 20 # Assigning a value to the 'age' variable
Multi-line Comments (Docstrings): Enclose the text within triple quotes ('''...''' or """..."""). While
technically string literals, they are commonly used as multi-line comments when not assigned to a
variable.
•Example: """
This is a multi-line comment.
It explains the purpose of the program.
"""
Data Types in Python
In Python, a data type is a classification that specifies which type of value a variable has
and what type of mathematical, relational or logical operations can be applied to it.
Data Types
Number Boolean Sequence None Mapping
Integer String
Floating List
Point
Complex Tuple
Data Types in Python
1. Number 🔢
Number types store numeric values. Python has three built-in numeric data types:
•Integer (int): Represents whole numbers, positive or negative, without a fractional part.
•Example: age = 17, year = 2024, temperature = -10
•Floating-point (float): Represents real numbers with a decimal point.
•Example: pi = 3.14, price = 99.99, gravity = 9.8
•Complex (complex): Represents numbers in the form a + bj, where a is the real part and b is the
imaginary part. It's used primarily in scientific computing and engineering.
•Example: z = 5 + 2j, c = -3 - 7j
2. Boolean (bool) ✔️
The Boolean data type represents one of two values: True or False. It's used for logical
operations and conditional statements.
•Example:
is_student = True
is_adult = False
print(10 > 5) # Output: True
print(10 == 20) # Output: False
Data Types in Python
3. Sequence 📝
A sequence is an ordered collection of items. Python has three fundamental sequence types:
•String (str): A sequence of characters enclosed in single ('...'), double ("..."), or triple ('''...''' or
"""...""") quotes.
•Strings are immutable, meaning their content cannot be changed after creation.
•Example: name = "Rohit", message = 'Hello World!’
•List (list): An ordered and mutable collection of items. A list can contain items of different data
types. It is enclosed in square brackets [ ].
•Example: numbers = [1, 2, 3, 4, 5], student_info = ["Ajay", 17, 95.5]
•Tuple (tuple): An ordered and immutable collection of items. It is enclosed in parentheses ( ).
Tuples are generally faster than lists and are used for data that shouldn't change.
•Example: coordinates = (10, 20), colors = ('red', 'green', 'blue')
4. None Type 🚫
The None type represents the absence of a value or a null value. It is not the same as 0, an empty string
"", or False. The None keyword is an object of the NoneType data type.
Data Types in Python
5. Mapping (dict) 🗺️
A dictionary is an unordered, mutable collection of key-value pairs. It is enclosed in curly braces
{ }. Each key must be unique and immutable (e.g., numbers, strings, or tuples), and it maps to a
corresponding value. Example:
person = {"name": "Sonia", "age": 16, "city": "Delhi"}
print(person["age"]) # Output: 16
Mutable vs. Immutable Data Types
•Mutable Data Types: An object is mutable if its state (content) can be changed after it is
created. When you modify a mutable object, it remains at the same memory location.
•Examples: list, dict, set
•Immutable Data Types: An object is immutable if its state cannot be changed after it is created.
Any operation that seems to modify an immutable object actually creates a new object in memory
with the updated content.
•Examples: int, float, complex, str, tuple, bool, NoneType
Mutable vs. Immutable Data Types
Example Program
# Mutable (List)
my_list = [10, 20, 30]
print(id(my_list))
my_list.append(40)
print(my_list)
print(id(my_list)) # The memory address remains the
same
# Immutable (String)
my_string = "Hello"
print(id(my_string))
new_string = my_string + " World"
print(new_string)
print(id(new_string)) # A new memory address is created
Expressions and Statements
Statements
A statement is a command or an instruction that the Python interpreter can execute. It's a complete line
of code.
•Examples:
•An assignment statement: x = 10
•A print statement: print("Hello")
•A conditional statement: if x > 5:
Expressions
An expression is a combination of operators, literals, and variables that evaluates to a single value. It's a
part of a statement.
•Examples:
•5 + 3 (evaluates to 8)
•x * 2 (if x is 10, this evaluates to 20)
•"Hello" + " World" (evaluates to "Hello World")
•x > 5 (evaluates to True or False)
Precedence of Operators:
The precedence of operators determines the order in which operators in an expression are evaluated.
Operators with higher precedence are evaluated before those with lower precedence.
•Parentheses (): The highest precedence. Expressions inside parentheses are evaluated first.
•Exponentiation **: Next highest.
•Multiplication, Division, Modulo *, /, %, //: Same precedence. Evaluated from left to right.
•Addition, Subtraction +, -: Same precedence. Evaluated from left to right.
•Relational Operators <, >, <=, >=, ==, !=: Next.
•Logical Operators not, and, or: Lowest precedence.
Type Conversion (Type Casting)
Type conversion is the process of converting a variable's data type from one type
to another.
1. Implicit Type Conversion (Automatic)
Implicit conversion is performed automatically by the Python interpreter when a mix of
data types is involved in an expression. The conversion happens from a smaller data
type to a larger one to prevent data loss.
num_int = 10
num_float = 5.5
result = num_int + num_float
print(result)
print(type(result))
Type Conversion (Type Casting)
2. Explicit Type Conversion (Manual)
Explicit conversion (or type casting) is when the programmer manually converts a data type to
another using built-in functions. This is done when implicit conversion is not possible or
desirable.
•Functions used:
•int(): Converts to an integer.
•float(): Converts to a float.
•str(): Converts to a string.
•Examples:
# String to integer
age_str = "25"
age_int = int(age_str)
print(age_int)
# Float to integer (data loss occurs)
price_float = 29.99
price_int = int(price_float)
print(price_int)
Types of Errors in Programming
In computer science, an error is a problem or a flaw in a program that can prevent it
from running correctly.
1. Syntax Errors 🚫
A syntax error occurs when a programmer writes code that violates the grammatical rules of the
programming language. The interpreter or compiler cannot understand the code and stops its execution.
These are the most common type of errors for beginners and are often called "compiler errors" or "parsing
errors."
•When it occurs: During the parsing phase, before the program even begins to execute.
•Example:
print("Hello, World!" # Missing a closing parenthesis
Types of Errors in Programming
2. Run-time Errors 💥
A run-time error, also known as an exception, occurs when the program is syntactically correct
and starts executing, but a problem arises during its execution that the program cannot handle.
The program stops unexpectedly and terminates.
When it occurs: After the program has started running, but before it has completed.
Examples:
a = int(input(“Enter first number : “))
b= int(input(“Enter second number : “))
c=a/b
print(“Quotient = “, c)
The above code will give error if the input value of b is 0.
•Error Message: ZeroDivisionError: division by zero
Types of Errors in Programming
3. Logical Errors 🤔
A logical error is the hardest to find because the program runs without crashing, but it
produces an incorrect or unexpected result. The syntax is perfect, and no exceptions are
raised. The problem lies in the programmer's logic or algorithm.
•When it occurs: The program runs completely but gives a wrong answer.
•Example:
# Program to calculate the average of three
numbers
num1 = 10
num2 = 20
num3 = 30
average = num1 + num2 + num3 / 3 # Incorrect
logic
print("The average is:", average)
•Expected Output: 20.0
•Actual Output: 40.0 (because of operator precedence, it first calculates 30 / 3 and then
adds it to 10 and 20).