Unit 1 - Introduction To Python Programming
Unit 1 - Introduction To Python Programming
Unit 1 - Introduction To Python Programming
Python is a high-level, interpreted programming language known for its simplicity and
readability. Created by Guido van Rossum and first released in 1991, Python's design
philosophy emphasizes code readability and simplicity, allowing programmers to express
concepts in fewer lines of code compared to languages like C++ or Java.
Applications of Python
Web Development: Building web applications and services using frameworks like
Django and Flask.
Data Science and Analytics: Analyzing data, performing statistical analysis, and
building machine learning models.
Artificial Intelligence and Machine Learning: Developing AI and ML algorithms
using libraries like TensorFlow and PyTorch.
Automation and Scripting: Automating repetitive tasks and writing scripts for
system administration.
Scientific Computing: Conducting complex scientific calculations and simulations
using libraries like SciPy and NumPy.
Game Development: Creating simple games and interactive applications.
Network Programming: Building network applications and protocols.
Desktop Applications: Developing graphical user interface (GUI) applications.
Python's versatility, readability, and extensive ecosystem make it a powerful tool for a wide
range of applications, from simple scripting to complex machine learning models. Its ongoing
development and community support ensure that it remains a relevant and valuable language
for both beginners and experienced programmers.
Keywords in Python
Keywords in Python are reserved words that have specific meanings and functions in the
language. These words cannot be used as identifiers (names of variables, functions, classes,
etc.) because they are part of the syntax.
Python keywords are case-sensitive and must be used exactly as they are defined.
3. as:
o Used to create an alias while importing a module.
import numpy as np
try:
result = 10 / 0
except ZeroDivisionError as e:
print(f"An error occurred: {e}")
4. break, continue:
o Control flow statements to exit or skip the current iteration of a loop.
for i in range(10):
if i == 5:
break # Exit the loop
print(i)
5. class:
o Used to define a new class.
class MyClass:
def __init__(self, value):
self.value = value
6. def:
o Used to define a new function.
def my_function():
print("Hello, World!")
1. False
2. None
3. True
4. and
5. as
6. assert
7. async
8. await
9. break
10. class
11. continue
12. def
13. del
14. elif
15. else
16. except
17. finally
18. for
19. from
20. global
21. if
22. import
23. in
24. is
25. lambda
26. nonlocal
27. not
28. or
29. pass
30. raise
31. return
32. try
33. while
34. with
35. yield
Identifiers in Python
Identifiers in Python are names used to identify variables, functions, classes, modules,
and other objects.
An identifier starts with a letter A to Z or a to z or an underscore (_) followed by zero
or more letters, underscores, and digits (0 to 9).
1. Descriptive Names: Use meaningful and descriptive names for identifiers to make
your code more readable.
# Good
total_sum = 100
user_name = "Alice"
# Bad
x = 100
y = "Alice"
user_age = 25
total_price = 100.5
def calculate_area(radius):
return 3.14 * radius * radius
class Person:
def __init__(self, name, age):
self.name = name
self.age = age
3. Avoid Single Character Names: Except for variables with a limited scope like loop
counters.
for i in range(10):
print(i)
Literals
Literals in Python are fixed values that are used to represent data directly in the code. They
are the simplest form of data in Python and can be of various types, such as numbers, strings,
and booleans.
Types of Literals
1. Numeric Literals
2. String Literals
3. Boolean Literals
4. Special Literals
5. Collection Literals
1. Numeric Literals
Numeric literals are used to represent numbers. They can be of three types: integers, floating-
point numbers, and complex numbers.
decimal = 10
binary = 0b1010 # Binary literal
octal = 0o12 # Octal literal
hexadecimal = 0xA # Hexadecimal literal
Floating-Point Literals: Numbers with a fractional part.
float_num = 10.5
float_exp = 1.5e2 # Scientific notation (1.5 * 10^2)
complex_num = 3 + 4j
2. String Literals
String literals are sequences of characters enclosed in single, double, triple single, or triple
double quotes.
Single-line Strings:
single_quote_str = 'Hello'
double_quote_str = "World"
Multi-line Strings:
triple_single_quote_str = '''This is a
multi-line string'''
3. Boolean Literals
is_true = True
is_false = False
4. Special Literals
Python has one special literal, None, which represents the absence of a value or a null value.
nothing = None
5. Collection Literals
Collection literals are used to represent collections of items. These include lists, tuples,
dictionaries, and sets.
List Literals:
list_literal = [1, 2, 3, 4]
Tuple Literals:
tuple_literal = (1, 2, 3, 4)
Dictionary Literals:
Set Literals:
set_literal = {1, 2, 3, 4}
Examples
Here are some examples to illustrate the use of different literals in Python:
# Numeric Literals
integer_literal = 42
print(integer_literal)
float_literal = 3.14
complex_literal = 2 + 3j
# String Literals
single_line_str = 'Hello, World!'
multi_line_str = """This is a
multi-line string"""
# Boolean Literals
true_literal = True
false_literal = False
# Special Literal
none_literal = None
# Collection Literals
list_literal = [1, 2, 3, 4]
tuple_literal = (1, 2, 3, 4)
dict_literal = {'name': 'Alice', 'age': 30}
set_literal = {1, 2, 3, 4}
Understanding literals is fundamental for working with data in Python, as they are the
building blocks for creating variables and working with data in your programs.
Operators in Python
Operators are special symbols that perform operations on variables and values. Python
supports a variety of operators, each serving different purposes. They can be classified into
several categories:
1. Arithmetic Operators
2. Comparison Operators
3. Logical Operators
4. Bitwise Operators
5. Assignment Operators
6. Membership Operators
7. Identity Operators
1. Arithmetic Operators
Operat Exampl
Description
or e
+ Addition a + b
- Subtraction a - b
Multiplicatio
* a * b
n
/ Division a / b
% Modulus a % b
Exponentiati
** a ** b
on
Floor
// a // b
Division
2. Comparison Operators
Comparison operators are used to compare two values and return a boolean result.
Operat Exampl
Description
or e
== Equal to a == b
!= Not equal to a != b
Greater than or
>= a >= b
equal to
Logical
and a and b
AND
or Logical OR a or b
Logical
not not a
NOT
4. Bitwise Operators
Operat Exampl
Description
or e
` Bitwise OR a ` b
^ Bitwise XOR a ^ b
~ Bitwise NOT ~a
Bitwise left
<< a << 1
shift
Bitwise right
>> a >> 1
shift
Operat
Description Example
or
= Assign a = 5
Bitwise OR and
` =`
assign
6. Membership Operators
Operat
Description Example
or
specified value
7. Identity Operators
Identity operators are used to compare the memory locations of two objects.
Operat
Description Example
or
# Arithmetic Operators
a = 10
b = 3
print(a + b) # Addition
print(a - b) # Subtraction
print(a * b) # Multiplication
print(a / b) # Division
print(a % b) # Modulus
print(a ** b) # Exponentiation
print(a // b) # Floor Division
# Comparison Operators
print(a == b) # Equal to
print(a != b) # Not equal to
print(a > b) # Greater than
print(a < b) # Less than
print(a >= b) # Greater than or equal to
print(a <= b) # Less than or equal to
# Logical Operators
print(a > 5 and b < 5) # Logical AND
print(a > 5 or b > 5) # Logical OR
print(not(a > 5)) # Logical NOT
# Bitwise Operators
print(a & b) # Bitwise AND
print(a | b) # Bitwise OR
print(a ^ b) # Bitwise XOR
print(~a) # Bitwise NOT
print(a << 1) # Bitwise left shift
print(a >> 1) # Bitwise right shift
# Assignment Operators
c = 10
c += 5
print(c) # Add and assign
# Membership Operators
my_list = [1, 2, 3, 4]
print(2 in my_list) # True
print(5 not in my_list) # True
# Identity Operators
x = 5
y = 5
print(x is y) # True
print(x is not y) # False
Understanding and using these operators correctly allows you to perform a wide variety of
operations in Python, making your code more functional and expressive.
Punctuators in Python
In Python, punctuators (or punctuation characters) are special symbols used in the syntax of
the language to perform various operations. Here’s an overview of the most common
punctuators in Python and their usage:
1. Parentheses ()
2. Square Brackets []
3. Curly Brackets {}
4. Colon :
5. Comma ,
6. Dot .
9.Backslash \
These punctuators are essential to writing syntactically correct and functional Python code.
Python Interpreter
The Python interpreter and interactive mode are essential tools for writing and testing Python
code. Here’s a detailed look at each:
The Python interpreter is a program that reads and executes Python code. It can execute code
from a script (a .py file) or interactively. When you run a Python script, the interpreter reads
the file, compiles it to bytecode, and then executes the bytecode on the Python virtual
machine (PVM).
1. Save your Python code in a file with a .py extension (e.g., script.py).
2. Open a terminal or command prompt.
3. Run the script by typing:
python script.py
or
python3 script.py
Interactive mode allows you to interact directly with the Python interpreter. You can type and
execute Python code one line at a time, which is useful for testing, debugging, and
experimenting with code snippets.
python
or
python3
You will see a prompt (usually >>>) indicating that you are in interactive mode.
In interactive mode, you can type Python commands and see immediate results. For example:
1. Immediate Feedback: You can see the results of expressions immediately after
typing them.
2. Testing and Debugging: It’s convenient for quickly testing small code snippets or
debugging.
3. Built-in Functions and Libraries: You have access to all built-in functions and
standard libraries.
4. Help and Documentation: You can use the help() function to get information about
modules, functions, and objects.
>>> help(print)
Help on built-in function print in module builtins:
print(...)
print(value, ..., sep=' ', end='\n', file=sys.stdout,
flush=False)
Prints the values to a stream, or to sys.stdout by default.
5. Exiting Interactive Mode: To exit, you can type exit() or use the shortcut Ctrl+D
(on Unix/Linux/Mac) or Ctrl+Z followed by Enter (on Windows).
While the Python interactive mode is very useful for quick tasks, many developers use
Integrated Development Environments (IDEs) for more extensive development work. Popular
Python IDEs include:
Values
Values are the core data that programs manipulate. Examples of values are numbers and
strings. Values can be assigned to variables and passed to functions.
Types
Types define the kind of data a value represents and what operations can be performed on it.
Python has several built-in data types, each with specific characteristics and uses.
1. Numeric Types
Integers (int)
o Whole numbers, positive or negative, without a decimal point.
o Examples: 1, 42, -7
Floating-point numbers (float)
o Numbers with a decimal point.
o Examples: 3.14, -0.001, 2.0
Complex numbers (complex)
o Numbers with a real and an imaginary part.
o Examples: 3 + 4j, -1 - 2j
2. Sequence Types
Strings (str)
o Ordered sequences of characters.
o Enclosed in single quotes ('), double quotes ("), or triple quotes ('''
or """).
o Examples: 'hello', "world", """Python"""
Lists (list)
o Ordered, mutable sequences of elements.
o Enclosed in square brackets ([]).
o Examples: [1, 2, 3], ['a', 'b', 'c']
Tuples (tuple)
o Ordered, immutable sequences of elements.
o Enclosed in parentheses (()).
o Examples: (1, 2, 3), ('a', 'b', 'c')
3. Mapping Types
Dictionaries (dict)
o Unordered collections of key-value pairs.
o Enclosed in curly braces ({}).
o Examples: {'name': 'Alice', 'age': 30}, {1: 'one', 2: 'two'}
4. Boolean Type
Booleans (bool)
o Represents truth values.
o Only two possible values: True and False.
is_active = True
is_logged_in = False
6. None Type
None (NoneType)
o Represents the absence of a value or a null value.
o Only one possible value: None.
result = None
Type Checking
You can check the type of a value using the type() function:
python
Copy code
print(type(42)) # <class 'int'>
print(type(3.14)) # <class 'float'>
print(type("hello")) # <class 'str'>
print(type([1, 2, 3])) # <class 'list'>
print(type((1, 2, 3))) # <class 'tuple'>
print(type({'a': 1})) # <class 'dict'>
print(type({1, 2, 3})) # <class 'set'>
print(type(True)) # <class 'bool'>
print(type(None)) # <class 'NoneType'>
Type Conversion
You can convert values from one type to another using built-in functions like int(),
float(), str(), list(), tuple(), set(), dict(), and bool():
python
Copy code
x = 42
y = float(x) # Converts int to float
print(y) # 42.0
s = "123"
n = int(s) # Converts str to int
print(n) # 123
lst = [1, 2, 3]
t = tuple(lst) # Converts list to tuple
print(t) # (1, 2, 3)
Understanding values and types is crucial for effective programming in Python, as it ensures
correct data manipulation and utilization of Python's extensive features and capabilities.
Variables
Variables in Python are used to store data values. They act as placeholders for data that can
be manipulated throughout the program. Here’s a detailed look at variables in Python:
In Python, you declare a variable by assigning it a value using the = operator. There is no
need to declare the type of the variable explicitly, as Python is a dynamically typed language.
python
Copy code
# Integer variable
age = 25
# Floating-point variable
pi = 3.14
# String variable
name = "Alice"
# Boolean variable
is_student = True
# List variable
numbers = [1, 2, 3, 4, 5]
# Dictionary variable
person = {"name": "Alice", "age": 25}
Variable Naming Rules
Variable names must start with a letter (a-z, A-Z) or an underscore ( _).
The rest of the name can contain letters, digits (0-9), and underscores.
Variable names are case-sensitive (myVar and myvar are different
variables).
Variable names should not be Python reserved keywords (e.g., for, while,
if, else, etc.).
Reassigning Variables
You can change the value of a variable by assigning it a new value. The type of the variable
can also change because Python is dynamically typed.
python
Copy code
x = 5
print(x) # Output: 5
x = "Hello"
print(x) # Output: Hello
x = [1, 2, 3]
print(x) # Output: [1, 2, 3]
Multiple Assignments
python
Copy code
a, b, c = 1, 2, 3
print(a) # Output: 1
print(b) # Output: 2
print(c) # Output: 3
Swapping the values of two variables can be done easily without needing a temporary
variable.
python
Copy code
a = 5
b = 10
# Swapping values
a, b = b, a
print(a) # Output: 10
print(b) # Output: 5
Variable Scope
The scope of a variable determines where it can be accessed within the code.
Global Scope: Variables declared outside of any function are in the global
scope and can be accessed anywhere in the code.
Local Scope: Variables declared within a function are in the local scope
and can only be accessed within that function.
Global Variables
python
Copy code
x = "global"
def my_function():
print(x) # Accesses the global variable
python
Copy code
x = "global"
def my_function():
global x
x = "local"
print(x) # Modifies the global variable
Constants
Python doesn’t have built-in constant types, but by convention, variables that should not
change are written in uppercase.
python
Copy code
PI = 3.14159
GRAVITY = 9.81
While Python allows reassignment of these variables, by convention, they are treated as
constants.
Type Annotations
In Python 3.5 and later, you can use type annotations to specify the expected type of a
variable. This is mainly for documentation and doesn't affect the execution of the code.
python
Copy code
age: int = 25
name: str = "Alice"
pi: float = 3.14
Understanding variables is essential for writing efficient and readable Python code. Proper
naming, scoping, and usage can significantly improve code maintainability and clarity.
Expressions
n Python, expressions are combinations of values, variables, operators, and function calls that
are evaluated to produce another value. Expressions are fundamental to any programming
language, as they form the building blocks of programs.
Types of Expressions
1. Arithmetic Expressions
python
Copy code
# Addition
result = 5 + 3 # result is 8
# Subtraction
result = 10 - 4 # result is 6
# Multiplication
result = 7 * 6 # result is 42
# Division
result = 8 / 2 # result is 4.0
# Floor Division
result = 9 // 2 # result is 4
# Modulus
result = 10 % 3 # result is 1
# Exponentiation
result = 2 ** 3 # result is 8
2. Comparison Expressions
Comparison expressions use comparison operators to compare two values and return a
boolean value (True or False).
python
Copy code
# Equal to
result = (5 == 5) # result is True
# Not equal to
result = (5 != 4) # result is True
# Greater than
result = (7 > 3) # result is True
# Less than
result = (3 < 7) # result is True
python
Copy code
# Logical AND
result = (5 > 3) and (7 > 5) # result is True
# Logical OR
result = (5 > 3) or (7 < 5) # result is True
# Logical NOT
result = not (5 > 3) # result is False
result = 5 << 1 # result is 10 (binary 101 << 1 is 1010)
Compound Expressions
Importance of Expressions
Expressions are essential for creating logic and functionality in programs. They are used in
assignments, conditionals, loops, function arguments, and many other constructs.
Understanding and effectively using expressions is key to writing efficient and readable
Python code.
Statements
In Python, statements are instructions that the Python interpreter can execute. Unlike
expressions, which evaluate to a value, statements perform actions. Here's an overview of the
different types of statements in Python:
Types of Statements
1. Assignment Statements
python
Copy code
x = 5
y = 10
name = "Alice"
2. Expression Statements
Expression statements evaluate expressions and then discard the result. They are often used to
call functions or methods.
python
Copy code
print("Hello, World!")
3. Conditional Statements
Conditional statements perform actions based on conditions. They include if, elif, and
else.
python
Copy code
x = 10
if x > 5:
print("x is greater than 5")
elif x == 5:
print("x is equal to 5")
else:
print("x is less than 5")
4. Loop Statements
Loop statements repeatedly execute a block of code. They include for and while loops.
For Loop
python
Copy code
for i in range(5):
print(i)
While Loop
python
Copy code
count = 0
while count < 5:
print(count)
count += 1
5. Break, Continue, and Pass Statements
python
Copy code
for i in range(10):
if i == 5:
break
print(i) # Output: 0, 1, 2, 3, 4
Continue: Skips the rest of the current loop iteration and continues with the next
iteration.
python
Copy code
for i in range(10):
if i % 2 == 0:
continue
print(i) # Output: 1, 3, 5, 7, 9
python
Copy code
def greet(name):
print(f"Hello, {name}!")
python
Copy code
def add(a, b):
return a + b
Import statements are used to import modules and make their functions and classes available
in your code.
python
Copy code
import math
print(math.sqrt(16)) # Output: 4.0
Importance of Statements
Statements are the building blocks of Python programs. They control the flow of execution,
perform actions, and define the structure of the code. Understanding and using statements
effectively is crucial for writing functional and efficient Python programs.
Precedence of Operators
In Python, operator precedence determines the order in which operations are performed in an
expression. Operators with higher precedence are evaluated before operators with lower
precedence. If operators have the same precedence, their associativity determines the order of
evaluation.
Here's a table of Python operators, listed from highest precedence to lowest precedence:
1. Parentheses: ()
2. Exponentiation: **
3. Unary plus, minus, and bitwise NOT: +x, -x, ~x
4. Multiplication, division, floor division, and modulus: *, /, //, %
5. Addition and subtraction: +, -
6. Bitwise shifts: <<, >>
7. Bitwise AND: &
8. Bitwise XOR: ^
9. Bitwise OR: |
10. Comparison operators: ==, !=, >, >=, <, <=, is, is not, in, not in
11. Boolean NOT: not x
12. Boolean AND: and
13. Boolean OR: or
14. Assignment operators: =, +=, -=, *=, /=, //=, %=, **=, &=, |=, ^=, >>=, <<=
15. Conditional expressions: if elser
16. Lambda expressions: lambda
Comments in Python
In Python, comments are used to annotate code with explanations, notes, or reminders.
Comments are ignored by the Python interpreter during execution and are purely for human
readers. They help improve code readability, document functionality, and explain complex
logic.
Types of Comments
1. Single-Line Comments
Single-line comments begin with the # character and continue until the end of the line. They
are typically used for short comments or annotations.
python
Copy code
# This is a single-line comment
x = 5 # Assigning the value 5 to variable x
2. Multi-Line Comments
Python does not have a built-in syntax specifically for multi-line comments like some other
programming languages. However, you can use triple quotes (""" or ''') to create multi-line
string literals, which Python treats as comments if not assigned to a variable or used in an
expression.
python
Copy code
"""
This is a multi-line comment.
It can span multiple lines.
"""
3. Docstrings
Docstrings are similar to multi-line comments but are used to document functions, classes,
methods, and modules. They are enclosed in triple quotes and can span multiple lines. Unlike
regular comments, docstrings are accessible via Python's __doc__ attribute and are used by
documentation generation tools.
python
Copy code
def add(a, b):
"""
This function adds two numbers.
Parameters:
a (int or float): First number
b (int or float): Second number
Returns:
int or float: Sum of a and b
"""
return a + b
Example Usage
python
Copy code
# Calculate the area of a rectangle
length = 10 # Length of the rectangle
width = 5 # Width of the rectangle
"""
This block of code is used to calculate the area
of a rectangle. It multiplies the length and width
variables to get the area. It then stores the result
in the area variable.
"""
def greet(name):
"""
This function greets a person by printing a message.
Parameters:
name (str): The name of the person to greet.
Returns:
None
"""
print(f"Hello, {name}!")
Summary
Comments in Python are invaluable for documenting code, explaining logic, and improving
readability. By using comments effectively, you can make your code easier to understand for
both yourself and others who may read or maintain it in the future.
Modules in Python
Modules are files containing Python code. They can define functions, classes, and variables.
Python modules are saved with the extension .py.
Importing a Module: You can use the import statement to bring a module into your
script.
python
Copy code
import math
print(math.sqrt(16)) # Output: 4.0
Creating Your Own Module: Simply create a .py file with your functions and
classes.
# my_module.py
def add(a, b):
return a + b
# main.py
import my_module
print(my_module.add(2, 3)) # Output: 5
Functions in Python
Functions are blocks of reusable code that perform a specific task. They help in organizing
code into manageable sections.
Defining a Function:
def greet(name):
"""This function greets a person with their name."""
print(f"Hello, {name}!")
The flow of execution refers to the order in which statements are executed in a script. For
functions, the flow of execution is as follows:
Example:
def print_message():
print("Hello, World!")
Output:
r
Copy code
Before function call
Hello, World!
After function call
Parameters and Arguments
Parameters are the variables listed inside the parentheses in the function definition.
Types of Arguments
1. Positional Arguments:
o Arguments passed to a function in the correct positional order.
2. Keyword Arguments:
o Arguments passed to a function by explicitly stating the parameter
name.
3. Default Arguments:
o Parameters that assume a default value if no argument is provided.
These concepts form the foundation of Python programming, enabling you to write modular,
reusable, and organized code.
Strings
Strings are Arrays
a = "Hello, World!"
print(a[1])
for x in "banana":
print(x)
a = "Hello, World!"
print(len(a))
b = "Hello, World!"
print(b[2:5])
b = "Hello, World!"
print(b[2:])
b = "Hello, World!"
print(b[-5:-2])
1. String Slices
String slicing in Python allows you to access a part of a string. The syntax for slicing is:
python
Copy code
string[start:end:step]
Examples:
python
Copy code
s = "Hello, World!"
print(s[0:5]) # Output: Hello
print(s[7:]) # Output: World!
print(s[:5]) # Output: Hello
print(s[::2]) # Output: Hlo ol!
print(s[::-1]) # Output: !dlroW ,olleH
2. Immutability
In Python, strings are immutable. This means that once a string is created, it cannot be
changed. Any operation that modifies a string will create a new string.
Examples:
python
Copy code
s = "Hello"
s[0] = 'h' # This will raise a TypeError
python
Copy code
s = "Hello"
s = 'h' + s[1:] # Output: 'hello'
Python provides various built-in methods to work with strings. Here are some commonly
used string methods:
python
Copy code
s = " Hello, World! "
print(s.upper()) # Output: " HELLO, WORLD! "
print(s.lower()) # Output: " hello, world! "
print(s.strip()) # Output: "Hello, World!"
print(s.split(',')) # Output: [' Hello', ' World! ']
print("-".join(['a', 'b', 'c'])) # Output: "a-b-c"
print(s.find("World")) # Output: 10
print(s.replace("World", "Universe")) # Output: " Hello, Universe! "
4. String Module
The string module in Python provides additional functions and constants to work with
strings. Some commonly used constants include:
Examples:
python
Copy code
import string
print(string.ascii_letters) # Output:
'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ'
print(string.digits) # Output: '0123456789'
print(string.punctuation) # Output: '!"#$%&\'()*+,-./:;<=>?@[\\]^_`{|}~'
These aspects of strings in Python allow for versatile and powerful manipulation and usage of
string data. If you have any specific questions or need further details on any of these topics,
feel free to ask!