0% found this document useful (0 votes)
27 views44 pages

Python UNIT-I

The document provides an overview of Python programming fundamentals, covering topics such as the introduction to Python, programming modes (Interactive and Script), Python tokens, variables, and memory management. It highlights key features of Python, its applications, and the differences between Interactive and Script modes, along with rules for using tokens and creating variables. Additionally, it discusses variable types, naming conventions, and the concept of dynamic typing in Python.

Uploaded by

shankar
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
27 views44 pages

Python UNIT-I

The document provides an overview of Python programming fundamentals, covering topics such as the introduction to Python, programming modes (Interactive and Script), Python tokens, variables, and memory management. It highlights key features of Python, its applications, and the differences between Interactive and Script modes, along with rules for using tokens and creating variables. Additionally, it discusses variable types, naming conventions, and the concept of dynamic typing in Python.

Uploaded by

shankar
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd

Python Programming

UNIT-I Fundamentals and Basics


Table of Contents
1. Introduction to Python
2. Python Programming Modes
3. Python Tokens
4. Variables and Memory Management
5. Python Keywords
6. Comments and Documentation
7. Literals in Python
8. Data Types
9. Indentation and Code Blocks
10. Operators and Precedence
11. Expressions and Statements
12. Input and Output Operations
13. Sequential Programming Approach

1. Introduction to Python
1.1 What is Python?
Python is a high-level, interpreted programming language created by Guido van Rossum
and released in 1991. The language was named after the British comedy group Monty
Python, reflecting the creator's aim to make programming fun. It emphasizes code
readability with its notable use of significant whitespace and simple, clear syntax to bridge
the gap between C and shell scripting.

1.2 Key Features of Python


• Easy to Learn: Simple, clear syntax
• Interpreted Language: No compilation needed
• Dynamically Typed: No need to declare variable types
• Object-Oriented: Supports object-oriented programming
• Rich Standard Library: Extensive built-in functions and modules
• Platform Independent: Runs on various operating systems
• Open Source: Free to use and distribute

1.3 Applications of Python


• Web Development
• Data Science and Analytics
• Artificial Intelligence and Machine Learning
• Scientific Computing
• Game Development
• Automation and Scripting
• Internet of Things (IoT)

2. Python Programming Modes


Python offers two primary ways to interact with the interpreter: Interactive Mode and
Script Mode. Each mode has its own advantages, and limitations.

When to Use Script Mode?

🔹 When writing full programs (automation scripts, data analysis, web development).
🔹 When working with large codebases (multiple functions, modules, or classes).
🔹 When performance is important (batch processing, file handling).
🔹 When using external libraries (NumPy, Pandas, TensorFlow, etc.).
When to Use Interactive Mode?

🔹 For quick testing of small code snippets.


🔹 For exploring Python features and syntax.
🔹 For performing quick calculations like a calculator.
🔹 For debugging code by checking variable values.
🔹 For learning Python interactively as a beginner.

2.1 Interactive Mode (REPL)


The Interactive mode, also known as REPL (Read-Eval-Print Loop), allows users to execute
Python commands one at a time and see immediate results. It is useful for quick testing,
debugging, and learning. When you enter interactive mode, Python waits for your input,
evaluates it, and then prints the result before prompting you for another command.

Features of Interactive Mode:


• Immediate feedback
• Great for testing small code snippets
• Useful for learning and debugging
• Commands are forgotten once the session ends

Example Interactive Session:


>>> print("Hello, World!")
Hello, World!
>>> 2 + 3
5
>>> name = "Python"
>>> print(name)
Python

Working in Interactive Mode


In interactive mode, you can:
• Execute basic Python commands
>>> print("Hello, Python Interactive Mode!")
Hello, Python Interactive Mode!

• Perform mathematical calculations


>>> 5 + 3
8
>>> 10 * 2
20
>>> 20 / 4
5.0
• Use built-in functions
>>> max(5, 10, 15)
15
>>> len("Python")
6

• Import and test modules


>>> import math
>>> math.sqrt(25)
5.0
>>> math.pi
3.141592653589793

• Define functions and classes


>>> def greet(name):
... return "Hello, " + name
...
>>> greet("Alice")
'Hello, Alice'

• Use loops and conditionals


>>> for i in range(5):
... print(i)
...
0
1
2
3
4

Advantages of Python Interactive Mode


✅ Quick Testing: Test small code snippets without creating a file.
✅ Immediate Feedback: See results instantly after each command.
✅ Easy Debugging: Quickly check values and test logic.
✅ No Need for a Code Editor: You don’t need to save files to run code.

Limitations of Python Interactive Mode


❌ Code is not saved: Once you exit, your commands are lost unless copied.
❌ Not suitable for large programs: Writing multi-line scripts is difficult.
❌ Limited debugging tools: No built-in debugging features like an IDE.

2.2 Script Mode


Python Script Mode allows users to write Python programs in a file (with a .py extension)
and execute them later. Unlike Interactive Mode, which executes commands one by one,
Script Mode runs the entire script at once. This mode is used for developing larger and
more complex programs..

Features of Script Mode:


• Code is saved for future use
• Can handle complex programs
• Better for larger applications
• Supports module imports and function definitions

Example Script (hello.py):


# This is a simple Python script
print("Welcome to Python Programming!")
name = input("Enter your name: ")
print(f"Hello, {name}!")

Advantages of Python Script Mode

✅ Code is reusable – Scripts can be saved and executed multiple times.


✅ Better organization – Ideal for writing large programs.
✅ Supports multi-line execution – Unlike interactive mode, scripts support structured
code with functions, loops, and conditions.
✅ Efficient debugging – IDEs provide debugging tools for finding errors in scripts.
✅ Can be automated – Scripts can be scheduled to run automatically.

Limitations of Python Script Mode

❌ No instant feedback – Unlike interactive mode, you won’t see results immediately.
❌ Debugging is slower – If an error occurs, you need to modify and re-run the script.
❌ Not ideal for quick testing – Interactive mode is better for testing small snippets of
code.
2.3 Comparing Interactive and Script Modes
Feature Interactive Mode Script Mode
Execution Line by line Entire file
Storage Temporary Permanent
Use Case Testing, Learning Development
Complexit Simple operations Complex programs
y
Reusability Limited High

3. Python Tokens
3.1 Understanding Tokens
Python tokens are the smallest meaningful individual units in a Python program, which the
interpreter recognizes and processes to execute the code. Every Python program is made
up of tokens, categorized into five main types.
Tokenization Process in Python
Python’s interpreter converts the raw source code into tokens using a process called
tokenization. The process involves:
1. Lexical Analysis: The interpreter reads the code line-by-line and breaks it down into
tokens (keywords, identifiers, operators, etc.).
2. Parsing: The tokens are analyzed to understand their meaning in the context of the
program.
Ex: x=10+5 Is broken down into the following tokens:
🔹 x (Identifier)
🔹 = (Assignment Operator)
🔹 10 (Literal)
🔹 + (Arithmetic Operator)
🔹 5 (Literal)
The interpreter then interprets these tokens based on Python’s syntax rules.

3.2 Types of Tokens


1. Identifiers
2. Keywords
3. Literals
4. Operators
5. Delimiters(Special Symbols)

3.3 Rules for Tokens


Python tokens are the basic building blocks of a Python program. To use them correctly,
certain rules must be followed. Below are the key rules for each type of Python token:
1. Rules for Identifiers
 Identifiers must start with a letter (A-Z or a-z) or an underscore (_).
 After the first letter, they can contain letters, digits (0-9), or underscores.
 Identifiers cannot be the same as Python keywords.
 Identifiers are case-sensitive (e.g., Var and var are different).
 Python allows identifiers to start with an underscore (_), often used for special or
private variables.
✅ Valid Examples:
my_variable = 10
_data123 = "Python"
CamelCaseIdentifier = "Valid"
❌ Invalid Examples:
1name = "John" # SyntaxError: Identifiers cannot start with a digit
@age = 25 # SyntaxError: Identifiers cannot contain special characters (@)
def = 10 # SyntaxError: Cannot use a keyword as an identifier.

2. Rules for Keywords


 Keywords cannot be used as variable names, function names, or identifiers.
 Python keywords are case-sensitive (e.g., True is valid, but true is not).
 There are no spaces allowed within keywords.
 Python does not allow the creation of new keywords.
✅ Valid Example:
if True:
print("Valid use of a keyword")
❌ Invalid Example:
if = 10 # SyntaxError: 'if' is a keyword
3. Rules for Literals
 String literals must be enclosed in single ('), double ("), or triple quotes (''' or
""").
 Numeric literals can be integers, floating-point numbers, or complex numbers.
 Boolean literals can only be True or False (case-sensitive).
 None literal (None) represents the absence of a value.
✅ Valid Examples:
name = "Alice" # String Literal
age = 30 # Integer Literal
pi = 3.14 # Float Literal
is_active = True # Boolean Literal
x = None # None Literal
❌ Invalid Examples:
name = Alice # NameError: Strings must be in quotes
age = 3,14 # SyntaxError: Use a dot (.) for decimal numbers instead of a comma (,)
4. Rules for Operators
 Operators must be used with appropriate data types (e.g., + for numbers or strings
but not both).
 Comparison and logical operators return boolean values (True or False).
 Assignment operators (=, +=, -=) assign values to variables.
 Membership (in, not in) and identity operators (is, is not) are used for checking
membership and object identity.
✅ Valid Examples:
a = 10 + 5 # Addition Operator
b = 15 > 10 # Comparison Operator, returns True
c = "hello" in "hello world" # Membership Operator, returns True
❌ Invalid Examples:
x = 10 / 0 # ZeroDivisionError: Cannot divide by zero
y = "10" + 5 # TypeError: Cannot add a string and an integer.
5. Delimiters (Rules for Special Symbols)
 : is required after function, class, and loop definitions.
 Parentheses () are used for function calls and tuple definitions.
 Square brackets [] are used for lists and indexing.
 Curly brackets {} are used for dictionaries and sets.
 # is used for single-line comments, while triple quotes (""" """) are used for multi-
line comments.
✅ Valid Examples:
def greet(): # Colon used in function definition
print("Hello, Python!")

list_numbers = [1, 2, 3] # Square brackets for lists


dict_data = {"name": "John", "age": 25} # Curly braces for dictionaries.
❌ Invalid Examples:
def greet() # SyntaxError: Missing colon (:) after function definition
list_numbers = {1, 2, 3] # SyntaxError: Mismatched brackets.

Example of Different Tokens:


x = 10 # 'x' is an identifier, '=' is an operator, '10' is a
literal
if x > 5: # 'if' is a keyword, '>' is an operator
print(x) # 'print' is a built-in function, '()' are delimiters

Summary of Python Token Rules

Token Type Rules

Keywords Cannot be used as identifiers, case-sensitive, no spaces allowed

Identifiers Must start with a letter or _, can contain letters, digits, or _, case-sensitive

Literals Strings in quotes, numbers as integers/floats, Boolean as True or False

Operators Must be used with correct data types, assignment (=) vs. comparison (==)

Special Symbols Used for syntax ((), {}, [], :), comments (#, """ """)
4. Variables and Memory Management
In Python, a variable is a name or reference that refers to a value stored in the computer's
memory. Variables are used to store data so that you can manipulate, access, and modify it
throughout your program. Let's go over the concept of variables in Python in a detailed
manner.
4.1 What is a Variable?
A variable in Python is like a container that holds a value, and this value can change (hence
the name "variable"). The variable itself is a reference or label to the memory location
where the actual data is stored.
4.2 Creating Variables in Python
To create a variable in Python, all you need to do is assign a value to it using the =
(assignment operator). The syntax is: variable_name = value
Here, variable_name is the name you choose for the variable, and value is the data you
assign to that variable.

4.3 Variable Naming Rules


In Python, there are a few rules and conventions to follow when naming variables:
 Variable names must start with a letter (a-z, A-Z) or an underscore (_).
 The rest of the variable name can include letters, numbers (0-9), and underscores
(_).
 Variable names are case-sensitive, meaning myVar and myvar are two different
variables.
 Variable names cannot be Python reserved keywords like if, for, while, int, etc.

Valid Variable Names:


name = "John"
age_1 = 25
_private = True
myVariable = "Hello"

Invalid Variable Names:


2name = "John" # Cannot start with number
my-var = 10 # Hyphen not allowed
class = "Python" # Cannot use keyword

4.4 Types of Variables


Python is a dynamically typed language, which means you don't need to specify the type of
a variable when you create it. Python automatically assigns the type based on the value
assigned to the variable. The major types of variables in Python are:
 Integers (int): Whole numbers.
 Floating-point numbers (float): Decimal numbers.
 Strings (str): Textual data enclosed in single (') or double (") quotes.
 Booleans (bool): True or False values.
 Lists, Tuples, Sets, Dictionaries: These are more complex data types that can hold
multiple values.
Examples:
x=5 # integer
y = 3.14 # float
name = "John" # string
is_active = True # Boolean
You can check the type of a variable using the type() function. This function returns the
type of the object stored in the variable.
Example:
x=5
print(type(x)) # Output: <class 'int'>
y = "Zeeshan"
print(type(y)) # Output: <class 'str'>
4.5 Reassigning Variables
You can reassign new values to a variable at any time. Python allows you to assign different
types to the same variable:
x=5 # x is an integer
x = "Hello" # Now x is a string
x = 3.14 # Now x is a float
4.6 Multiple Variable Assignment
In Python, you can assign values to multiple variables in a single line using the following
syntax:
a, b, c = 10, 20, 30
Here, the value 10 is assigned to a, 20 to b, and 30 to c.
4.7 Constants in Python
Unlike some other programming languages, Python doesn't have a built-in constant type.
However, the convention is to write constant variable names in all uppercase letters to
signify that they should not be changed.
PI = 3.14159 # This is a constant (by convention, it shouldn't be changed)
4.8. Global vs Local Variables
 Local Variables: These are defined inside a function and can only be accessed within
that function.
 Global Variables: These are defined outside of any function and can be accessed from
anywhere in the program.
Example:
x = 10 # Global variable
def my_function():
y = 20 # Local variable
print(x) # Can access global variable
print(y) # Can access local variable
my_function()
4.9 Dynamic Typing and Type Casting
Python is dynamically typed, which means that the type of the variable is determined at
runtime based on the value assigned. You can also change the type of a variable explicitly
using type casting.
Example of dynamic typing:
x = 10 # x is an integer
x = "Hello" # Now x is a string
Example of type casting:
x = "123"
y = int(x) # Casting string to integer
print(type(y)) # Output: <class 'int'>
4.10 Best Practices for Variables
 Choose descriptive and meaningful names for variables. For example, use age
instead of a, and user_name instead of x.
 Follow PEP 8 (Python's style guide) for variable naming. This includes using
snake_case (lowercase letters and underscores) for variable names.
Example:
first_name = "John"
last_name = "Doe"

4.11 Memory Management


Python has an efficient memory management system that includes:
1. Automatic memory allocation
2. Garbage collection
3. Reference counting
4. Memory pools (PyMalloc)
1. Automatic Memory Allocation: Python memory is divided into different sections:
Stack Memory: Stores function calls, local variables. When a function is called, Python
creates a stack frame for it.
Example: def my_func():
a = 10 # 'a' is stored in stack memory
return a
my_func()

Heap Memory:,. Stores all Python objects like lists, dictionaries, and class instances and
dynamically allocated memory
Example: list1 = [1, 2, 3] # The list is stored in heap memory
4.12 Conclusion
In Python, variables are a fundamental part of any program. They allow you to store,
modify, and reference data. With Python's dynamic typing, variables can hold any data type
without needing explicit type definitions. Understanding how to create, assign, and
manipulate variables is key to writing Python programs.
5. Python Keywords
5.1 What are Keywords?
Keywords are reserved words that have special meanings in Python. They cannot be used
as variable names or identifiers. In Python the list of keywords can be viewed using the
keyword module.
import keyword
print(keyword.kwlist)

5.2 List of Python Keywords


False await else import pass
None break except in raise
True class finally is return
and continue for lambda try
as def from nonlocal while
assert del global not with
async elif if or yield

5.3 Common Keywords and Their Uses

Control Flow Keywords:


# if-elif-else
if x > 0:
print("Positive")
elif x < 0:
print("Negative")
else:
print("Zero")

# while loop
while condition:
# code block

# for loop
for item in sequence:
# code block

Function and Class Keywords:


# Function definition
def function_name():
pass

# Class definition
class ClassName:
pass
Exception Handling Keywords:
try:
# code that might raise an exception
except Exception:
# handle exception
finally:
# always executed

1. False

Explanation: The False keyword represents a boolean value of false. It is used in logical
operations and control flow statements.

Example:

print(False)

Output:

False

2. None

Explanation: The None keyword represents the absence of a value or a null value. It is
commonly used to indicate that a variable has no assigned value.

Example:

x = None

print(x)

Output:

None

3. True

Explanation: The True keyword represents a boolean value of true. It is used in logical
operations and conditions.
Example:

print(True)

Output:

True

4. and

Explanation: The and keyword is used as a logical operator that returns True if both
conditions are True.

Example:

print(True and False)

Output:

False

5. as

Explanation: The as keyword is used to create an alias when importing a module.

Example:

import math as m

print(m.sqrt(16))

Output:

4.0

6. assert

Explanation: The assert keyword is used for debugging; it raises an error if the condition
evaluates to False.

Example:

x=5

y = 10
assert x < y

print("Assertion Passed")

Output:

Assertion Passed

7. async:

Explanation: The async keyword in Python is used for writing asynchronous code, allowing
for non-blocking execution. It is primarily used with the await keyword to define
coroutines, which enable efficient execution of tasks like I/O operations (network requests,
file handling, etc.) without freezing the entire program.

import asyncio
async def task1():
print("Task 1 started")
await asyncio.sleep(3)
print("Task 1 completed")
async def task2():
print("Task 2 started")
await asyncio.sleep(1)
print("Task 2 completed")
async def main():
await asyncio.gather(task1(), task2()) # Run both tasks concurrently
asyncio.run(main())

Output:
Task 1 started
Task 2 started
(1 second delay)
Task 2 completed
(2 seconds delay)
Task 1 completed
8.await

Explanation: The await keyword in Python is used inside an asynchronous function


(defined with async def) to pause execution until the awaited coroutine or task completes.
It enables non-blocking execution, allowing other tasks to run concurrently.

Output:

import asyncio

async def my_function():


print("Task started")
await asyncio.sleep(2) # Non-blocking sleep for 2 seconds
print("Task finished")
asyncio.run(my_function())

Output:
Task started
(2 seconds delay)
Task finished

9. break

Explanation: The break keyword is used to exit a loop prematurely when a certain
condition is met. It is commonly used in for and while loops.

Example:

for i in range(5):

if i == 3:

break

print(i)

Output:

10. class
Explanation: The class keyword in Python is used to define a class, which is a blueprint for
creating objects. A class allows you to bundle data (attributes) and functions (methods)
together, supporting the principles of object-oriented programming (OOP) such as
encapsulation, inheritance, and polymorphism.

Example:

# Defining a class(Defines a blueprint for creating "Person" objects.)

class Person:

# Constructor to initialize object attributes(Initializes each Person with a name and age.)

def __init__(self, name, age):

self.name = name # Instance attribute

self.age = age # Instance attribute

# Method to introduce the person(Prints a message introducing the person.)

def introduce(self):

print(f"Hello, my name is {self.name} and I am {self.age} years old.")

# Creating objects (instances) of the class(person1 with name and age, Person2 with name
and age)

person1 = Person("abc", 25)

person2 = Person("xyz", 30)

# Calling the method

person1.introduce()

person2.introduce()

Output:

Hello, my name is abc and I am 25 years old.

Hello, my name is xyz and I am 30 years old.


11. continue

Explanation: The continue keyword in Python is used inside loops (for or while) to skip the
current iteration and move to the next one. It does not terminate the loop but simply jumps
to the next iteration.

Example:

for i in range(5):

if i == 2:

continue

print(i)

Output:

12. def

Explanation: The def keyword in Python is used to define a function. A function is a reusable
block of code that performs a specific task. The def keyword is followed by the function
name, parentheses (), and a colon : to start the function body.

Example:

1) def greet():

return "Hello, World!"

print(greet())

Output:

Hello, World!

2) def greet(name):
print(f"Hello, {name}!")
# Calling the function with an argument
greet("Alice")
greet("Bob")
Output:
Hello, Alice!
Hello, Bob!

13. del

Explanation: The del keyword in Python is used to delete objects, variables, list elements,
dictionary keys, or attributes of an object. It helps manage memory by removing
unnecessary references to objects.

Example:

Deleting a variable:

x = 10
print(x) # Output: 10
del x
print(x) # Raises NameError: name 'x' is not defined

Deleting an Element from a List (Using Index)


my_list = [1, 2, 3, 4, 5]
del my_list[2] # Deletes element at index 2 (third element)
print(my_list)
Output: [1, 2, 4, 5]

Deleting a Slice from a list:


my_list = [10, 20, 30, 40, 50]
del my_list[1:3] # Deletes elements at index 1 and 2
print(my_list)
Output: [10, 40, 50]

Deleting a Dictionary Key:


my_dict = {'a': 1, 'b': 2, 'c': 3}
del my_dict['b'] # Removes key 'b' from the dictionary
print(my_dict)
Output: {'a': 1, 'c': 3}

14. elif
Explanation: The elif keyword in Python is used for multiple conditional statements in an
if-elif-else structure. It allows checking multiple conditions sequentially, where only the
first true condition executes.

Example:

num = 15
if num < 10:
print("Number is less than 10")
elif num < 20:
print("Number is between 10 and 20")
elif num < 30:
print("Number is between 20 and 30")
else:
print("Number is 30 or more")
Output:
Number is between 10 and 20

15. else

Explanation: The else keyword in Python is used to define a block of code that executes
when the preceding conditional statements (if, elif, try-except, loops) fail. It works in
various contexts such as if-else statements, try-except blocks, and loops.

Example:

x=5

if x > 10:

print("Greater than 10")

else:

print("Less than or equal to 10")

Output:

Less than or equal to 10

16. except

Explanation: The except keyword in Python is used in the context of exception handling.
The except keyword is used to handle exceptions and prevent crashes in Python programs.
An exception is an error that occurs during program execution. When an exception occurs,
Python stops executing the program and looks for a way to handle the error.

Example:

try:

x = 10 / 0

except ZeroDivisionError:

print("Cannot divide by zero!")

Output:

Cannot divide by zero!

17. finally

Explanation: The finally keyword is used in exception handling to define a block of code
that executes regardless of whether an exception occurs or not.

Example:

try:

x = 10 / 0

except:

print("Error Occurred")

finally:

print("Execution Completed")

Output:

Error Occurred

Execution Completed

18. for

Explanation: The for keyword is used to create loops that iterate over a sequence (e.g.,
lists, tuples, strings, or ranges).

Example:
for i in range(3):

print(i)

Output:

19. from

Explanation: The from keyword in Python is primarily used for importing modules or
specific attributes from a module. It helps in optimizing imports by allowing you to import
only what you need.

Example:

from math import sqrt

print(sqrt(25))

Output:

5.0

20. global

Explanation: The global keyword in Python is used to declare a global variable inside a
function, allowing modifications to a variable defined outside the function's local scope.
Normally, variables inside a function are local by default, meaning they do not affect
variables outside the function unless explicitly declared as global

Example:

x = 10 # Global variable

def modify():

global x # Declaring x as global

x = 20 # Now modifying the global x

print("Inside function:", x)
modify()

print("Outside function:", x)

Output:

Inside function: 20

Outside function: 20

21. if

Explanation: The if keyword is used to introduce a conditional statement. It allows the


program to execute a block of code only if a specified condition is True. If the condition
evaluates to False, the code inside the if block is skipped.

Example:

x = 10

if x > 5:

print("x is greater than 5")

Output:

x is greater than 5

22. import

Explanation: The import keyword is used to bring external modules or packages into the
current Python script. This allows you to access and use functions and classes from other
Python files or libraries.

Example:

import math

print(math.pi)

Output:

3.141592653589793
23. in

Explanation: The in keyword in Python is used for membership testing and iteration. It is
primarily used in two scenarios.
1)Membership Testing: To check if a value exists in a sequence (like lists, tuples, sets,
dictionaries, or strings).
2) Iteration: Used in for loops to iterate over iterable objects.
It returns True if the value is found and False otherwise.

Example:

print(2 in [1, 2, 3])

Output:

True

24. is

Explanation: The is keyword is used to compare whether two variables point to the same
object in memory, rather than checking if their values are equal.

Example:

x = [1, 2, 3]

y=x

print(x is y)

Output:

True

25. lambda

Explanation: The lambda keyword is used to define small, anonymous functions in a single
line. These functions can take any number of arguments but can only contain a single
expression, that return a value without requiring a return statement.

Example:

square = lambda x: x * x
print(square(5))

Output:

25

26. nonlocal

Explanation: The nonlocal keyword is used inside nested functions to modify a variable
defined in an outer (but non-global) function.

Example:

def outer():

x = "Hello"

def inner():

nonlocal x

x = "World"

inner()

print(x)

outer()

Output:

World

27. not

Explanation: The not keyword is used to negate a boolean expression, returning the
opposite logical value.

Example:

print(not False)

Output:

True

28. or
Explanation: The or keyword is used in logical expressions to return True if at least one of
the conditions is true.

Example:

print(True or False)

Output:

True

29. pass

Explanation: The pass keyword in Python is a null statement that serves as a placeholder
where code is syntactically required but should do nothing when executed. It allows you to
write code structures that you plan to implement later without causing syntax errors.

Example:

def my_function():

pass # Placeholder for future code

print("Function defined but not implemented yet.")

Output:

Function defined but not implemented yet

30. raise

Explanation: The raise keyword in Python is used to explicitly throw an exception during
program execution. It allows programmers to trigger exceptions manually when a specific
condition occurs.

Example:

age = -5

if age < 0:

raise ValueError("Age cannot be negative")

Output:

Traceback (most recent call last):

File "main.py", line 3, in <module>


raise ValueError("Age cannot be negative")

ValueError: Age cannot be negative

31. return

Explanation: The return keyword is used to exit a function and send back a value to the
caller.

Example:

def add(a, b):

return a + b

print(add(3, 4))

Output:

32. try

Explanation: The try keyword is used to define a block of code in which exceptions might
occur. It is usually paired with except to handle errors gracefully.

Example:

try:

x = 10 / 0

except ZeroDivisionError:

print("Cannot divide by zero")

Output:

Cannot divide by zero

33. while

Explanation: The while keyword is used to create loops that execute repeatedly while a
given condition is True.

Example:

x=0
while x < 3:

print(x)

x += 1

Output:

34. with

Explanation: The with keyword is used to simplify resource management, such as file
handling, ensuring that the resource is properly cleaned up after use.

Example:

with open("test.txt", "w") as file:

file.write("Hello World")

35. yield

Explanation: The yield keyword is used in generator functions to return values one at a
time, allowing iteration without storing the entire sequence in memory. The keyword yield
is similar to return, but instead of terminating the function, it pauses the function and
allows it to be resumed later. When a function contains yield, it becomes a generator
function. Unlike normal functions that return a single value, a generator can produce a
sequence of values over time.

Example:

def generator():

yield 1

yield 2

yield 3

for value in generator():

print(value)
Output:

6. Comments and Documentation


6.1 Single-line Comments
Single-line comments start with # and continue to the end of the line.
# This is a single-line comment
x = 5 # This assigns 5 to x

6.2 Multi-line Comments (Docstrings)


Multi-line comments use triple quotes and are often used for documentation.
"""
This is a multi-line comment
It can span multiple lines
Used for documentation
"""

def calculate_area(radius):
"""
Calculates the area of a circle.

Args:
radius (float): The radius of the circle

Returns:
float: The area of the circle
"""
return 3.14159 * radius ** 2
7. Literals in Python
7.1 Understanding Literals
Literals are data items that have a fixed value. They represent themselves and are the
simplest form of data in Python.

7.2 Types of Literals

7.2.1 Numeric Literals


# Integer literals
x = 10 # Decimal
y = 0b1010 # Binary
z = 0o12 # Octal
w = 0xA # Hexadecimal

# Float literals
pi = 3.14159
e = 2.71828
scientific = 1.23e-4

7.2.2 String Literals


# Single quotes
single = 'Hello'

# Double quotes
double = "Hello"

# Triple quotes
multi = """This is a
multi-line
string"""

# Raw string
raw = r"C:\Users\name"

# Unicode string
unicode = u"Hello World"

7.2.3 Boolean Literals


true_value = True
false_value = False

7.2.4 None Literal


empty = None

7.2.5 Special String Literal Operations


# String concatenation
greeting = "Hello" + " " + "World"
# String repetition
stars = "*" * 5 # *****

# String formatting
name = "Alice"
age = 25
formatted = f"{name} is {age} years old"

8. Data Types
8.1 Numeric Types

8.1.1 Integer (int)


# Integer examples
x = 5
y = -17
big_num = 1_000_000 # Using underscore for readability

8.1.2 Float
# Float examples
pi = 3.14159
e = 2.71828
small = 1.23e-4

8.1.3 Complex
# Complex number examples
c1 = 3 + 4j
c2 = complex(3, 4)

8.2 Sequence Types

8.2.1 String (str)


# String examples
name = "Python"
char = name[0] # Accessing individual character
slice = name[1:4] # Slicing

8.2.2 List
# List examples
numbers = [1, 2, 3, 4, 5]
mixed = [1, "hello", 3.14, True]
nested = [1, [2, 3], 4]

# List operations
numbers.append(6)
numbers.extend([7, 8])
numbers.insert(0, 0)
8.2.3 Tuple
# Tuple examples
coordinates = (3, 4)
nested_tuple = (1, (2, 3), 4)

# Tuple unpacking
x, y = coordinates

8.3 Mapping Type

8.3.1 Dictionary (dict)


# Dictionary examples
person = {
"name": "John",
"age": 30,
"city": "New York"
}

# Dictionary operations
person["email"] = "john@example.com"
age = person.get("age")

8.4 Set Types

8.4.1 Set
# Set examples
unique_numbers = {1, 2, 3, 4, 5}
fruits = {"apple", "banana", "orange"}

# Set operations
unique_numbers.add(6)
unique_numbers.remove(1)

8.4.2 Frozen Set


# Frozen set example
immutable_set = frozenset([1, 2, 3])

8.5 Boolean Type


# Boolean examples
is_valid = True
is_empty = False

# Boolean operations
result = is_valid and not is_empty

8.6 None Type


# None example
value = None
8.7 Type Conversion
# Type conversion examples
str_num = "123"
num = int(str_num) # String to integer
float_num = float(num) # Integer to float
str_back = str(num) # Integer to string

9. Indentation and Code Blocks


9.1 Understanding Indentation
Python uses indentation to define code blocks, unlike other languages that use braces or
keywords.

9.2 Indentation Rules


• Standard indentation is 4 spaces
• Must be consistent within the same block
• Increases after certain statements (if, for, while, def, class)
• Decreases to indicate the end of a block

9.3 Examples of Proper Indentation

9.3.1 If Statements
if condition:
# First level indentation
statement1
statement2
if another_condition:
# Second level indentation
statement3
statement4
else:
# Back to first level
statement5

9.3.2 Loops
for i in range(5):
# Loop body indented
print(i)
if i % 2 == 0:
# Nested block further indented
print("Even number")

9.3.3 Functions
def calculate_square(number):
# Function body indented
square = number ** 2
if square > 100:
# Nested block
return "Large number"
return square

9.4 Common Indentation Errors


# IndentationError: unexpected indent
def function():
statement # Should be indented

# IndentationError: unindent does not match any outer indentation


level
if True:
print("Hello")
print("World") # Wrong indentation level

10. Operators and Precedence


10.1 Arithmetic Operators
# Basic arithmetic
a = 10
b = 3

addition = a + b # 13
subtraction = a - b # 7
multiplication = a * b # 30
division = a / b # 3.3333...
floor_division = a // b # 3
modulus = a % b # 1
exponent = a ** b # 1000

10.2 Comparison Operators


x = 5
y = 10

equal = x == y # False
not_equal = x != y # True
greater_than = x > y # False
less_than = x < y # True
greater_equal = x >= y # False
less_equal = x <= y # True

10.3 Logical Operators


p = True
q = False

and_result = p and q # False


or_result = p or q # True
not_result = not p # False
10.4 Assignment Operators
# Simple assignment
x = 5

# Compound assignment
x += 3 # x = x + 3
x -= 2 # x = x - 2
x *= 4 # x = x * 4
x /= 2 # x = x / 2
x //= 3 # x = x // 3
x %= 3 # x = x % 3
x **= 2 # x = x ** 2

10.5 Bitwise Operators


a = 60 # 60 = 0011 1100
b = 13 # 13 = 0000 1101

# Bitwise AND
c = a & b # 12 = 0000 1100

# Bitwise OR
d = a | b # 61 = 0011 1101

# Bitwise XOR
e = a ^ b # 49 = 0011 0001

# Bitwise NOT
f = ~a # -61 = 1100 0011

# Left shift
g = a << 2 # 240 = 1111 0000

# Right shift
h = a >> 2 # 15 = 0000 1111

10.6 Identity Operators


x = ["apple", "banana"]
y = ["apple", "banana"]
z = x

is_same = x is z # True
is_not_same = x is y # False

10.7 Membership Operators


```python fruits = [“apple”, “banana”, “cherry”]
in_list = “apple” in fruits # True
10.8 Operator Precedence
Python follows a specific order of operations when evaluating expressions. Here’s the
precedence from highest to lowest:
6. Parentheses and Brackets (), [], {}
7. Exponentiation **
8. Unary operators +x, -x, ~x
9. Multiplication/Division *, /, //, %
10. Addition/Subtraction +, -
11. Bitwise shifts <<, >>
12. Bitwise AND &
13. Bitwise XOR ^
14. Bitwise OR |
15. Comparison operators ==, !=, >, >=, <, <=
16. Logical operators not, and, or

Example of Operator Precedence:


# Expression evaluation following precedence
result = 2 + 3 * 4 ** 2 # 50, not 100
result = (2 + 3) * 4 ** 2 # 80
result = ((2 + 3) * 4) ** 2 # 400

# Complex expression
x = 5
y = 3
z = 2
result = x + y * z ** 2 - (x + y) / z

11. Expressions and Statements


11.1 Understanding Expressions
An expression is a combination of values, variables, operators, and function calls that can
be evaluated to produce a value.

11.1.1 Types of Expressions

Arithmetic Expressions
# Simple arithmetic
result = 5 + 3 * 2

# Complex arithmetic
area = length * width
volume = length * width * height
# Mixed operations
total = price * quantity * (1 + tax_rate)

Boolean Expressions
# Comparison expressions
is_adult = age >= 18

# Compound boolean expressions


is_valid = (age >= 18) and (country == "USA")

# Nested boolean expressions


can_vote = (age >= 18) and (citizenship == "yes") or (special_status
== True)

String Expressions
# String concatenation
full_name = first_name + " " + last_name

# String formatting
greeting = f"Hello, {full_name}!"

# String operations
is_long_name = len(full_name) > 20

11.2 Statements
A statement is a complete line of code that performs an action.

11.2.1 Types of Statements

Assignment Statements
# Simple assignment
x = 5

# Multiple assignment
a, b, c = 1, 2, 3

# Augmented assignment
counter += 1

Conditional Statements
# if statement
if temperature > 30:
print("It's hot!")

# if-else statement
if score >= 60:
print("Pass")
else:
print("Fail")
# if-elif-else statement
if score >= 90:
grade = 'A'
elif score >= 80:
grade = 'B'
elif score >= 70:
grade = 'C'
else:
grade = 'F'

Loop Statements
# for loop
for i in range(5):
print(i)

# while loop
while counter < 10:
counter += 1

Function Definition Statements


def calculate_area(radius):
return 3.14 * radius ** 2

def greet(name, greeting="Hello"):


return f"{greeting}, {name}!"

12. Input and Output Operations


12.1 Input Functions

12.1.1 Basic Input


# Simple input
name = input("Enter your name: ")

# Numeric input
age = int(input("Enter your age: "))
height = float(input("Enter your height in meters: "))

12.1.2 Input Validation


# Input with validation
while True:
try:
age = int(input("Enter your age: "))
if age < 0 or age > 150:
raise ValueError("Invalid age")
break
except ValueError as e:
print(f"Error: {e}. Please enter a valid age.")

12.1.3 Multiple Inputs


# Getting multiple inputs
x, y = map(int, input("Enter two numbers separated by space:
").split())

# Getting a list of numbers


numbers = [int(x) for x in input("Enter numbers separated by space:
").split()]

12.2 Output Functions

12.2.1 Basic Print


# Simple print
print("Hello, World!")

# Print with multiple arguments


print("Name:", name, "Age:", age)

# Print with separator and end parameters


print(1, 2, 3, sep=', ', end='!\n')

12.2.2 Formatted Output


# Using f-strings (Python 3.6+)
name = "Alice"
age = 25
print(f"{name} is {age} years old")

# Using .format()
print("{} is {} years old".format(name, age))

# Using % operator (older style)


print("%s is %d years old" % (name, age))

12.2.3 Advanced Output Formatting


# Number formatting
pi = 3.14159
print(f"Pi to 2 decimal places: {pi:.2f}")

# Width and alignment


for i in range(1, 4):
print(f"{i:2d} {i*i:3d} {i*i*i:4d}")

# Currency formatting
price = 1234.5678
print(f"Price: ${price:,.2f}")
12.3 File Input/Output

12.3.1 Reading from Files


# Reading entire file
with open('file.txt', 'r') as file:
content = file.read()

# Reading line by line


with open('file.txt', 'r') as file:
for line in file:
print(line.strip())

# Reading specific number of bytes


with open('file.txt', 'r') as file:
chunk = file.read(100)

12.3.2 Writing to Files


# Writing strings
with open('output.txt', 'w') as file:
file.write("Hello, World!\n")
file.write("This is a new line")

# Writing multiple lines


lines = ['Line 1', 'Line 2', 'Line 3']
with open('output.txt', 'w') as file:
file.writelines(f"{line}\n" for line in lines)

13. Sequential Programming Approach


13.1 Understanding Sequential Programming
Sequential programming is the simplest and most basic programming paradigm where
instructions are executed one after another in a specified order.

13.2 Basic Principles

13.2.1 Order of Execution


# Instructions execute in sequence
print("Step 1")
print("Step 2")
print("Step 3")

# Variable assignments happen in sequence


x = 5
y = x + 3
z = y * 2
13.2.2 Program Flow
# Basic sequential flow
name = input("Enter your name: ")
age = int(input("Enter your age: "))
year = 2024 - age
print(f"Hello, {name}! You were born in {year}")

13.3 Sequential Program Structure

13.3.1 Input Phase


# Gathering all inputs first
length = float(input("Enter length: "))
width = float(input("Enter width: "))
height = float(input("Enter height: "))

13.3.2 Processing Phase


# Processing the inputs
area = length * width
volume = area * height
cost = volume * price_per_unit

13.3.3 Output Phase


# Displaying results
print(f"Area: {area:.2f} square units")
print(f"Volume: {volume:.2f} cubic units")
print(f"Total Cost: ${cost:.2f}")

13.4 Example Complete Sequential Program


# Complete program following sequential approach
def main():
# Input phase
print("Welcome to Rectangle Calculator")
length = float(input("Enter length: "))
width = float(input("Enter width: "))

# Processing phase
area = length * width
perimeter = 2 * (length + width)
diagonal = (length**2 + width**2) ** 0.5

# Output phase
print("\nResults:")
print(f"Area: {area:.2f} square units")
print(f"Perimeter: {perimeter:.2f} units")
print(f"Diagonal: {diagonal:.2f} units")

# Program execution
if __name__ == "__main__":
main()
13.5 Benefits and Limitations

Benefits:
• Simple to understand and implement
• Easy to debug
• Straightforward flow of control
• Good for simple calculations and processes

Limitations:
• Not suitable for complex problems
• Limited reusability
• Can become difficult to maintain for large programs
• No built-in error handling

13.6 Best Practices for Sequential Programming


17. Clear Structure

– Organize code into distinct sections


– Use meaningful variable names
– Add appropriate comments
18. Input Validation

while True:
try:
number = float(input("Enter a positive number: "))
if number <= 0:
raise ValueError("Number must be positive")
break
except ValueError as e:
print(f"Error: {e}")

19. Modular Design

def get_input():
# Input code here
return value

def process_data(value):
# Processing code here
return result

def display_result(result):
# Output code here

# Main program
value = get_input()
result = process_data(value)
display_result(result)
20. Error Handling

try:
# Main program logic
result = calculate_result(input_value)
except ValueError:
print("Invalid input")
except ZeroDivisionError:
print("Cannot divide by zero")
else:
print("Calculation successful")
finally:
print("Program completed")

You might also like