Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
3 views

python unit 1

The document discusses various aspects of Python, including memory management techniques, PEP 8 style guidelines, and the programming cycle. It explains dynamic and strong typing, operator associativity, and provides several Python programs for tasks like printing even-length words, converting numbers, and checking for prime numbers. Additionally, it highlights the importance of debugging tools and the role of Boolean expressions in programming.
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
3 views

python unit 1

The document discusses various aspects of Python, including memory management techniques, PEP 8 style guidelines, and the programming cycle. It explains dynamic and strong typing, operator associativity, and provides several Python programs for tasks like printing even-length words, converting numbers, and checking for prime numbers. Additionally, it highlights the importance of debugging tools and the role of Boolean expressions in programming.
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 19

1. How memory is managed in Python? Explain PEP 8. Write a Python program to print even length words in a string.

Memory Management in Python

Python uses a combination of techniques for memory management, including:

1. Reference Counting: Every object has a reference count that tracks how many references point to it. When the reference
count reaches zero, the memory is deallocated.
2. Garbage Collection: Python has an automatic garbage collector to remove unused objects and free memory.
3. Heap Memory Management: All Python objects and data structures are stored in a private heap.
4. Memory Pools: Python uses memory pools like the PyMalloc allocator for better performance.
5. Dynamic Typing: Variables can hold different data types, and memory is allocated accordingly.

PEP 8 (Python Enhancement Proposal 8)

PEP 8 is the official style guide for Python code. It includes:

• Indentation (4 spaces per level, no tabs)


• Maximum line length (79 characters)
• Blank lines for readability
• Naming conventions (CamelCase for classes, snake_case for functions/variables)
• Consistent spacing and imports

Python Program: Print Even Length Words in a String

python
CopyEdit
def print_even_length_words(sentence):
words = sentence.split()
for word in words:
if len(word) % 2 == 0:
print(word)

# Example usage
sentence = "Hello world this is Python"
print_even_length_words(sentence)

2. Define operator associativity with its type. What are the factors for expression evaluation?

Operator Associativity

Operator associativity determines the direction in which an expression is evaluated when multiple operators of the same precedence
appear. Types:

• Left to Right Associativity (most operators like +, -, *, /)


• Right to Left Associativity (assignment =, exponentiation **)

Factors for Expression Evaluation

1. Operator Precedence – Determines which operator is evaluated first.


2. Associativity – Decides evaluation direction for same-precedence operators.
3. Parentheses – Force specific execution order.
4. Data Type Coercion – Automatic conversion between types.
5. Short-circuiting – Logical operators (and, or) stop evaluating early.

3. Why is Python called a dynamic and strongly typed language?

Dynamic Typing

Python is dynamically typed, meaning:


• You don’t need to declare variable types explicitly.
• The type of a variable is determined at runtime.
• Example:

python
CopyEdit
x = 5 # x is an integer
x = "hello" # Now x is a string

Strongly Typed

Python is strongly typed, meaning:

• Operations between incompatible types are not allowed.


• Example:

python
CopyEdit
print("Age: " + 20) # TypeError: cannot concatenate 'str' and 'int'

• You must explicitly convert types to perform operations:

python
CopyEdit
print("Age: " + str(20)) # Correct

4. Explain the programming cycle for Python.

Python follows the following cycle:

1. Writing the Code


o You write the Python program in an editor like VS Code, PyCharm, or IDLE.
2. Saving the File
o Save the file with a .py extension, e.g., program.py.
3. Compiling and Interpreting
o Python interprets the code line by line (Unlike C, which compiles everything at once).
4. Debugging
o Errors are checked, and the programmer fixes them.
5. Executing the Program
o The final program runs successfully.

5. Can we make multiline comments in Python? Do we need to declare variables with data types?

Multiline Comments

Python does not support explicit multiline comments, but we can use:

• Triple quotes (""" """ or ''' ''') for multiline docstrings:

python
CopyEdit
"""
This is a
multiline comment
"""

Variable Type Declaration

• Python does not require explicit type declaration.


• Example:
python
CopyEdit
x = 10 # No need to write int x = 10
y = "AI" # No need to write string y = "AI"

6. What is Python? How is it interpreted? What tools help find bugs? What are Python decorators?

What is Python?

Python is a high-level, interpreted, dynamically typed, and general-purpose programming language. It is widely used in various
fields such as:

• Web development (Django, Flask)


• Data science and machine learning (NumPy, Pandas, TensorFlow)
• Automation and scripting
• Embedded systems and IoT

Python is popular due to its simplicity, readability, and vast library support, making it beginner-friendly and powerful for
professional use.

How is Python interpreted?

Python is an interpreted language, meaning that it executes code line by line rather than compiling the entire program before
running. The interpretation process follows these steps:

1. Lexical Analysis – The source code is converted into tokens.


2. Parsing – The tokens are analyzed and transformed into an Abstract Syntax Tree (AST).
3. Bytecode Compilation – The AST is converted into Python bytecode (.pyc files).
4. Execution by Python Virtual Machine (PVM) – The PVM interprets and runs the bytecode.

Since Python is interpreted, it enables quick prototyping and easy debugging, but may run slower compared to compiled languages
like C or Java.

What tools help find bugs in Python?

Python provides various tools to detect and debug errors efficiently:

• pdb (Python Debugger) – A built-in module that allows step-by-step debugging.


• PyLint – A static code analysis tool that checks for style violations and potential errors.
• flake8 – A combination of multiple tools to enforce coding standards and detect mistakes.
• PyCharm Debugger – A graphical debugger available in PyCharm IDE.
• pytest & unittest – Frameworks for writing and running test cases to catch bugs early.

These tools help developers write cleaner and error-free Python code.

What are Python decorators?

A decorator in Python is a function that modifies the behavior of another function without changing its actual code. It is used to
dynamically add functionality to functions or methods.

Example of a Simple Decorator:

def my_decorator(func):
def wrapper():
print("Before function execution")
func()
print("After function execution")
return wrapper

@my_decorator # Applying the decorator


def say_hello():
print("Hello!")

say_hello()

Output:

Before function execution


Hello!
After function execution

Decorators are commonly used in logging, authentication, caching, and modifying function behavior dynamically.

7.What happens if you put a semicolon at the end of a Python statement?

In Python, a semicolon (;) at the end of a statement does not cause an error, but it is not required and generally discouraged as
Python uses newlines to separate statements.

Example:

print("Hello, World!");

Output:

Hello, World!

The semicolon has no effect here. However, Python allows multiple statements on a single line if separated by semicolons:

x = 5; y = 10; print(x + y)

Output:

15

Even though this is valid, it reduces readability, which is why using semicolons in Python is not recommended.

Five Benefits of Python

1. Easy to Learn and Readable


o Python has a simple and clean syntax, similar to natural language.
o Indentation-based formatting improves code readability.
2. Extensive Libraries and Frameworks
o Python provides powerful libraries like NumPy, Pandas, TensorFlow, Flask, Django, and OpenCV for various
applications.
3. Platform Independence
o Python is cross-platform, meaning it can run on Windows, macOS, and Linux without modification.
4. Strong Community Support
o Python has a large and active community that contributes to open-source projects, libraries, and provides quick
support for debugging.
5. Versatility and Wide Applications
o Used in web development, data science, AI/ML, automation, embedded systems, and cybersecurity.
o Supports object-oriented, procedural, and functional programming paradigms.

8.What do you mean by Boolean expression?


A Boolean expression is an expression that evaluates to either True or False. It is commonly used in conditional statements and
logical operations.

Example:

x = 10
y = 5
print(x > y) # True
print(x == y) # False

Here, x > y evaluates to True, and x == y evaluates to False.

• Short Notes on Various Topics

1. The Programming Cycle for Python

The Python programming cycle consists of the following steps:

1. Writing the Code – Create a .py file using any text editor or IDE.
2. Saving the File – Save the script with a .py extension.
3. Running the Code – Execute the script using the Python interpreter (python filename.py).
4. Debugging – Identify and fix errors using debugging tools.
5. Testing & Execution – Test different inputs and validate outputs.

2. Elements of Python

The fundamental elements of Python include:

• Variables & Data Types – int, float, string, list, tuple, dict, set, etc.
• Operators – Arithmetic, logical, relational, bitwise, etc.
• Control Structures – if-else, for, while, try-except, etc.
• Functions & Modules – Built-in and user-defined functions, importing modules.
• Classes & Objects – Supports object-oriented programming (OOP).

3. Type Conversion in Python

Python allows conversion of data from one type to another using explicit and implicit conversion.

• Implicit Conversion (Automatic)


Python automatically converts smaller data types to larger ones.
• a = 5 # int
• b = 2.5 # float
• c = a + b
• print(c, type(c)) # Output: 7.5 <class 'float'>
• Explicit Conversion (Manual)
The int(), float(), str(), etc., functions can be used to convert types manually.
• x = "100"
• y = int(x) # Converts string to integer
• print(y, type(y)) # Output: 100 <class 'int'>

4. Operator Precedence in Python

Operator precedence determines the order in which operations are performed in an expression.

Precedence Order (Highest to Lowest):


1. Parentheses ()
2. Exponentiation **
3. Multiplication, Division, Modulus *, /, %, //
4. Addition & Subtraction +, -
5. Relational Operators <, >, ==, !=, <=, >=
6. Logical Operators and, or, not

Example:

result = 10 + 2 * 3 ** 2
print(result) # Output: 28

Here, 3 ** 2 is evaluated first, then 2 * 9, and finally 10 + 18.

5. Boolean Expression

A Boolean expression is an expression that returns either True or False based on logical conditions.

Example:

x = 10
y = 20
print(x < y) # True
print(x == y) # False

Boolean expressions are used in if-else statements, loops, and logical operations.

10.Write a simple program in Python to convert a decimal number into binary, octal, and hexadecimal number system.

Python Program:

# Take decimal input from the user


decimal_number = int(input("Enter a decimal number: "))

# Convert to binary, octal, and hexadecimal


binary = bin(decimal_number) # Convert to binary
octal = oct(decimal_number) # Convert to octal
hexadecimal = hex(decimal_number) # Convert to hexadecimal

# Display the results


print(f"Binary: {binary}")
print(f"Octal: {octal}")
print(f"Hexadecimal: {hexadecimal}")

Example Output:

Enter a decimal number: 20


Binary: 0b10100
Octal: 0o24
Hexadecimal: 0x14

This program uses bin(), oct(), and hex() functions to convert a decimal number into its respective number systems.

11.When evaluating a complicated expression, what is the role of associativity? Why is it important?

Role of Associativity in Expression Evaluation


Associativity determines the order of execution for operators of the same precedence in an expression. If two operators have the
same precedence, associativity decides whether the expression is evaluated left to right or right to left.

Types of Associativity:

1. Left-to-Right Associativity (Most operators)


o Operators like +, -, *, /, //, %, &, |, ^ follow left-to-right associativity.
o Example:
o result = 10 - 4 + 2
o print(result) # Output: 8

Explanation:
(10 - 4) + 2 → 6 + 2 → 8

2. Right-to-Left Associativity (Few operators)


o Operators like = (assignment) and **** (exponentiation) follow right-to-left associativity.
o Example:
o result = 2 ** 3 ** 2
o print(result) # Output: 512

Explanation:
2 ** (3 ** 2) → 2 ** 9 → 512

Why is Associativity Important?

1. Avoids ambiguity – Helps in deciding the correct order of execution.


2. Ensures correct results – Prevents misinterpretation of operations.
3. Optimizes performance – Determines how expressions should be grouped for evaluation.

Thus, associativity plays a crucial role in ensuring that expressions are evaluated correctly and consistently.

12.Write a program in Python to find whether a number is prime or not

Python Program:

def is_prime(n):
if n < 2:
return False # Numbers less than 2 are not prime
for i in range(2, int(n**0.5) + 1): # Check divisibility up to sqrt(n)
if n % i == 0:
return False
return True

# Take input from the user


num = int(input("Enter a number: "))

# Check if the number is prime


if is_prime(num):
print(f"{num} is a Prime Number")
else:
print(f"{num} is Not a Prime Number")

Example Output:

Enter a number: 17
17 is a Prime Number
Enter a number: 20
20 is Not a Prime Number

Explanation:

• The function is_prime(n) checks if n is prime.


• If n < 2, it's not prime.
• The loop runs from 2 to √n, checking divisibility.
• If n is divisible by any number in this range, it's not prime.

This approach optimizes the checking process using the square root method, making it more efficient.

13.How would you convert a long integer to a regular int in Python if needed? What precautions should be taken when doing
this conversion?

Converting a Long Integer to a Regular int in Python

In Python versions 2.x, there was a distinction between int (fixed-size integer) and long (arbitrarily large integer). To convert a
long integer to a regular int, you could use:

num_long = 12345678901234567890L # Python 2 long integer


num_int = int(num_long) # Convert to regular int
print(num_int)

However, in Python 3.x, the long type was merged with int, meaning all integers are now of unlimited precision. So, explicit
conversion is not required, as Python automatically handles large integers.

Precautions When Converting a Large Integer to int

If you need to convert a large number to a fixed-size integer (for example, when interacting with external systems like databases or
programming languages with fixed integer sizes), keep in mind:

1. Loss of Precision
o Some languages (like C or Java) have fixed integer limits (e.g., int32 or int64).
o Converting a large Python integer to a smaller integer type may result in overflow or truncation.
2. Memory Considerations
o Python’s int dynamically allocates memory.
o Converting to a fixed-size integer may reduce memory usage, but may also lead to data loss if the number is too
large.
3. Use sys.maxsize for Limits
o Before conversion, check the maximum supported integer size in your system:
4. import sys
5. print(sys.maxsize) # Typically 2^63 - 1 on 64-bit systems

Example: Handling Large Integer Conversion with Precautions

import sys

num = 98765432109876543210 # Large integer

# Check if it fits within system maxsize


if num > sys.maxsize:
print("Warning: Number exceeds typical int size and may lose precision in some
systems!")

num_int = int(num) # Convert to int (Python handles it dynamically)


print(num_int)

Conclusion

• In Python 3.x, there is no need to convert long to int, as int supports arbitrary precision.
• When converting large numbers for use in external systems (C, Java, databases), be mindful of integer limits to avoid
overflow or data loss.

14.Concept of "Automatic Conversion" in Python When Dealing with Arithmetic Operations Involving int and long Values

What is Automatic Conversion?

Automatic conversion, also known as implicit type conversion, is when Python automatically converts one data type into another
without explicit intervention by the programmer.

In Python 2.x, there was a distinction between:

• int (fixed-precision, 32-bit or 64-bit)


• long (arbitrary-precision for very large numbers, denoted with an L)

When performing arithmetic operations that exceeded the storage limit of int, Python automatically converted the result to long
to prevent overflow.

Example in Python 2.x:

x = 2**31 # Large integer


y = x * x # Automatic conversion to long
print(type(y)) # Output: <type 'long'>

How Does Python Handle This Conversion in Python 3.x?

In Python 3.x, the long type was removed, and all integers are now of unlimited precision. This means that Python no longer
needs to automatically convert between int and long, as int can handle arbitrarily large numbers.

Example in Python 3.x:

x = 2**100 # Very large integer


y = x * x # No need for conversion, Python handles it automatically
print(type(y)) # Output: <class 'int'>

Here, Python dynamically allocates memory to accommodate large integers, so there is no risk of overflow.

Key Takeaways:

1. In Python 2.x, when an int exceeded its limit, Python automatically converted it to long.
2. In Python 3.x, int has unlimited precision, so no explicit conversion is needed between int and long.
3. Python dynamically manages memory to handle large integers efficiently.

This behavior makes Python more robust for handling large numbers compared to languages like C or Java, which impose strict
integer size limits.

15.What is the difference between mutable and immutable data types in Python? Provide examples of each and discuss why
immutability is important in certain contexts.

Difference Between Mutable and Immutable Data Types

In Python, data types are classified as mutable or immutable based on whether their values can be modified after creation.
1. Mutable Data Types

Mutable objects can be changed after creation. Any modification happens in place, meaning the object's memory address remains
the same.

Examples of Mutable Data Types:

1. Lists (list)
2. my_list = [1, 2, 3]
3. print(id(my_list)) # Memory address before modification
4.
5. my_list.append(4) # Modifying the list
6. print(my_list) # Output: [1, 2, 3, 4]
7.
8. print(id(my_list)) # Same memory address (modified in place)
9. Dictionaries (dict)
10. my_dict = {"a": 1, "b": 2}
11. my_dict["c"] = 3 # Adding a new key-value pair
12. print(my_dict) # Output: {'a': 1, 'b': 2, 'c': 3}
13. Sets (set)
14. my_set = {1, 2, 3}
15. my_set.add(4) # Modifying the set
16. print(my_set) # Output: {1, 2, 3, 4}

2. Immutable Data Types

Immutable objects cannot be changed after creation. Any modification creates a new object in memory, rather than modifying the
existing one.

Examples of Immutable Data Types:

1. Integers (int)
2. x = 10
3. print(id(x)) # Memory address before modification
4.
5. x = x + 5 # Creates a new object
6. print(x) # Output: 15
7.
8. print(id(x)) # New memory address (new object created)
9. Strings (str)
10. s = "Hello"
11. print(id(s)) # Memory address before modification
12.
13. s = s + " World" # Creates a new string
14. print(s) # Output: Hello World
15.
16. print(id(s)) # New memory address (new object created)
17. Tuples (tuple)
18. my_tuple = (1, 2, 3)
19. # my_tuple[0] = 10 # TypeError: 'tuple' object does not support item
assignment
20. Booleans (bool)
21. x = True
22. x = False # A new Boolean object is created
23. Floating Points (float)
24. y = 3.14
25. y = y + 1.0 # A new float object is created

Why is Immutability Important?

1. Memory Efficiency & Performance


o Python reuses immutable objects instead of creating duplicates, optimizing memory usage.
2. a = "hello"
3. b = "hello"
4. print(a is b) # Output: True (Same memory reference)
5. Hashability & Dictionary Keys
o Immutable objects can be used as dictionary keys, while mutable ones cannot.
6. my_dict = {(1, 2, 3): "Tuple as key"} # Tuples (immutable) can be used
7. # my_dict = {[1, 2, 3]: "List as key"} # TypeError: unhashable type: 'list'
8. Thread Safety
o Immutable objects prevent unintended side effects in multi-threaded programs.
o Example: Strings are immutable, making them safe to share across threads.
9. Avoiding Unexpected Changes
o Mutable objects can change unexpectedly, leading to bugs.
10. def add_item(my_list, item):
11. my_list.append(item) # Modifies original list
12.
13. l = [1, 2, 3]
14. add_item(l, 4)
15. print(l) # Output: [1, 2, 3, 4] (Original list changed)

Summary Table

Feature Mutable (list, dict, set) Immutable (int, str, tuple)


Can be changed? Yes No
Memory efficient? No (Modifies in place) Yes (Reuses objects)
Hashable? No Yes (Used as dictionary keys)
Thread safe? No Yes

Conclusion

• Use mutable types when you need modifiable data structures (e.g., lists, dictionaries).
• Use immutable types for safety, memory efficiency, and reliability (e.g., tuples, strings).

16.What are the advantages and disadvantages of using dynamic typing in Python? How does it compare to static typing in
other programming languages?

Dynamic Typing in Python

Python uses dynamic typing, meaning variables do not have fixed types. Instead, the type is determined at runtime, and the same
variable can hold different data types at different points in the program.

Example of Dynamic Typing in Python:

x = 10 # x is an integer
x = "Hello" # x is now a string
x = 3.14 # x is now a float
print(x)

Here, x changes type multiple times without explicit declaration.

Advantages of Dynamic Typing in Python

1. Flexibility and Ease of Use


o No need to declare variable types explicitly.
o Makes Python code shorter and easier to write.
2. Faster Development
o Suitable for rapid prototyping, scripting, and data analysis.
o Less boilerplate code compared to statically typed languages.
3. More Expressive Code
o Functions can handle multiple data types without modification.
4. def add(a, b):
5. return a + b # Works for integers, floats, and even strings
6. print(add(5, 3)) # Output: 8
7. print(add("Hi ", "there")) # Output: Hi there
8. Interpreted Language Benefit
o Python does not require a compilation step, making it easier to test and debug.

Disadvantages of Dynamic Typing in Python

1. Increased Risk of Runtime Errors


o Type errors are detected only at runtime, leading to potential crashes.
2. x = "10" + 5 # TypeError: can only concatenate str (not "int") to str
3. Performance Overhead
o Type checking is done at runtime, making Python slower than statically typed languages like C or Java.
4. Debugging Challenges
o Harder to track down type-related bugs in large codebases.
5. Lack of Type Safety
o Variables can be unintentionally changed to an incorrect type, leading to unexpected behavior.
6. x = 100 # Intended as an integer
7. x = "100" # Changed to string by mistake
8. print(x + 50) # TypeError: can only concatenate str (not "int") to str

Comparison: Dynamic Typing (Python) vs. Static Typing (C, Java, etc.)

Feature Dynamic Typing (Python, JavaScript) Static Typing (C, Java, C++)
Type Declaration No need to declare types explicitly Must declare variable types (int, float, string)
Flexibility Highly flexible, variables can change types Strict, variable type cannot change
Performance Slower due to runtime type checking Faster due to compile-time type checking
Error Detection Errors occur at runtime Errors detected at compile time
Debugging Harder to debug large codebases Easier debugging due to early error detection
Best For Scripting, prototyping, rapid development Large-scale applications, high-performance computing

Conclusion

• Dynamic Typing makes Python easier to write and flexible, but it increases the risk of runtime errors and performance
issues.
• Static Typing (used in C, Java, etc.) helps with error prevention, optimization, and performance, but requires more code.

Python partially solves this with type hints (typing module) in Python 3.6+, allowing optional type checking:

def add(a: int, b: int) -> int:


return a + b

However, Python remains dynamically typed at runtime.

17.Explain the concept of data type coercion in Python. How does Python handle operations between different data types, and
what rules govern these conversions?

What is Data Type Coercion?

Data type coercion in Python is the automatic conversion of one data type into another when performing operations involving
different types. Python implicitly converts the data type to avoid errors and ensure smooth execution of expressions.

How Python Handles Operations Between Different Data Types


Python follows specific rules when performing operations between different types. If an operation involves two different types,
Python converts one type to match the other using implicit or explicit conversion.

1. Implicit Type Conversion (Automatic Coercion)

• Python automatically converts smaller data types to larger ones to prevent data loss.

Example: Integer to Float Conversion

x = 10 # int
y = 2.5 # float
result = x + y # int is converted to float automatically
print(result) # Output: 12.5
print(type(result)) # Output: <class 'float'>

Here, x (integer) is implicitly converted to a float to match y, ensuring a consistent data type.

2. Explicit Type Conversion (Type Casting)

• When implicit conversion is not possible, Python allows explicit conversion using functions like int(), float(),
str(), etc.

Example: String to Integer Conversion

num_str = "100"
num_int = int(num_str) # Explicit conversion
print(num_int + 50) # Output: 150

Example: Float to Integer Conversion (Loss of Precision)

pi = 3.14
integer_value = int(pi) # Converts to 3 (decimal part is lost)
print(integer_value) # Output: 3

Rules Governing Data Type Conversions in Python

Python follows a hierarchy when converting data types:

1. Lower precision → Higher precision (Implicit conversion)


o int → float → complex
2. x = 5 # int
3. y = 2.5 # float
4. print(x + y) # Output: 7.5 (int is converted to float)
5. Higher precision → Lower precision (Requires explicit conversion, may lose data)
o float → int (Decimal part is lost)
o complex → int/float (Not allowed, will raise an error)
6. Operations with str require explicit conversion
7. age = 25
8. print("I am " + str(age) + " years old.") # Output: I am 25 years old.
9. Boolean (True/False) in Numeric Operations
o True is treated as 1, False as 0 in arithmetic operations.
10. print(True + 5) # Output: 6
11. print(False + 10) # Output: 10

Key Takeaways

Implicit conversion (automatic coercion) happens when Python safely converts smaller types to larger types (e.g., int →
float).
Explicit conversion (type casting) is needed when converting between incompatible types (e.g., str → int).
Data loss can occur when converting from higher to lower precision (e.g., float → int).
Boolean values (True = 1, False = 0) can be used in numeric operations.

18.Explain the role of the is and == operators in Python when comparing objects. How do they differ, and when should you
use one over the other?

1. Role of is and == Operators in Python

Both is and == are used for comparison, but they serve different purposes:

• == (Equality Operator): Compares the values of two objects.


• is (Identity Operator): Compares the memory addresses (object identity) of two objects.

2. Difference Between is and ==

== (Equality Operator) - Compares Values

• Checks if two objects have the same value, even if they are stored at different memory locations.

Example:

a = [1, 2, 3]
b = [1, 2, 3]
print(a == b) # True, because their values are the same
print(a is b) # False, because they are different objects in memory

Here, a and b are two separate list objects, but they contain the same values, so a == b is True.

is (Identity Operator) - Compares Memory Addresses

• Checks if two variables point to the same memory location (i.e., they are the same object).

Example:

x = [10, 20, 30]


y = x # y now points to the same object as x

print(x == y) # True (same values)


print(x is y) # True (same memory reference)

Here, y is assigned to x, so they refer to the same object in memory.

Example Where is is False:

a = [1, 2, 3]
b = [1, 2, 3] # A new list with the same values

print(a is b) # False, because they are different objects

Even though a and b have the same values, they are stored at different memory locations, so a is b is False.

3. When to Use is vs. ==?


Scenario Use == (Equality) Use is (Identity)
Checking if two variables have the same value Yes No
Checking if two variables refer to the same object in memory No Yes
Comparing primitive types (int, float, str) Yes Only for small values (interning)
Comparing mutable objects (list, dict, set) Yes If checking object identity
Checking if a variable is None No if x is None:

4. Special Case: Immutable Objects & Interning

For small integers (-5 to 256) and short strings, Python caches objects to optimize memory usage. This means is might return
True for numbers and strings with the same value.

a = 100
b = 100
print(a is b) # True (Python caches small integers)

x = "hello"
y = "hello"
print(x is y) # True (Python caches short strings)

However, for large numbers and dynamically created strings, is may return False:

a = 5000
b = 5000
print(a is b) # False (Different objects in memory)

x = "hello world!"
y = "hello world!".replace("!", "")
print(x is y) # False (Different memory locations)

5. When Should You Use is?

• Checking if a variable is None (recommended approach):


• if x is None: # Correct
• print("x is None")

Using x == None is discouraged because it can be overridden in custom classes.

• Checking if two variables refer to the same object in memory (useful for performance optimizations).

Conclusion

• Use == when comparing values (recommended for most cases).


• Use is when checking object identity (especially for None or ensuring two variables point to the same object).
• Be cautious with immutable types (int, str), as Python may cache small values, leading to unexpected results with is.

19.Explain the difference between local and global variables in Python. When and why might you choose to use one over the
other?

1. Difference Between Local and Global Variables


Feature Local Variable Global Variable
Defined inside a function (accessible only within Defined outside functions (accessible throughout
Scope
that function) the program)
Lifetime Exists only while the function is executing Exists as long as the program runs
Accessible only within the function where it is Can be accessed inside functions using the
Access inside functions
defined global keyword
Modification inside Cannot modify a global variable without using
Can be modified inside functions using global
functions global
Memory Usage Stored in function’s local memory (stack) Stored in global memory (heap)

2. Example of Local and Global Variables

Example: Local Variable (Only Available Inside Function)

def example_function():
local_var = 10 # Local variable
print("Inside function:", local_var)

example_function()
# print(local_var) # Error: local_var is not defined outside the function

Output:

Inside function: 10

Here, local_var is defined inside the function and cannot be accessed outside.

Example: Global Variable (Accessible Everywhere)

global_var = 20 # Global variable

def example_function():
print("Inside function:", global_var)

example_function()
print("Outside function:", global_var) # Accessible globally

Output:

Inside function: 20
Outside function: 20

Here, global_var is defined outside the function and accessible both inside and outside.

3. Modifying Global Variables Inside Functions

By default, modifying a global variable inside a function creates a new local variable. To modify a global variable, use the global
keyword.

Example: Without global Keyword (Creates Local Variable)

x = 5 # Global variable

def change_x():
x = 10 # This creates a new local variable, doesn't modify global x
print("Inside function:", x)
change_x()
print("Outside function:", x) # Original global variable remains unchanged

Output:

Inside function: 10
Outside function: 5

Here, Python creates a local variable x inside change_x(), leaving the global x unchanged.

Example: Using global Keyword (Modifies Global Variable)

x = 5 # Global variable

def change_x():
global x # Declaring x as global
x = 10 # Now modifies the global x
print("Inside function:", x)

change_x()
print("Outside function:", x) # Now x is modified globally

Output:

Inside function: 10
Outside function: 10

By using global x, we modified the global variable instead of creating a new local one.

4. When and Why to Use Local vs. Global Variables?

Use Local Variables When:

✔ The variable is needed only within a function.


✔ You want to avoid unintentional changes to global values.
✔ You want to save memory (local variables are deleted once the function exits).

Use Global Variables When:

✔ The variable needs to be accessed across multiple functions.


✔ You need a constant value (e.g., configuration settings).
✔ You want to maintain state information across function calls.

5. Best Practices

Prefer local variables whenever possible to avoid accidental modifications.


Use global variables sparingly to keep code modular and easy to debug.
If needed, use global keyword carefully to modify global variables inside functions.

20.Explain the concept of reserved words (keywords) in Python. Why are they important, and how should you avoid naming
conflicts with keywords?

1. What Are Reserved Words (Keywords) in Python?


Reserved words, also known as keywords, are predefined words in Python that have special meanings and cannot be used as
variable, function, or class names.

Example of Keywords:

Some commonly used Python keywords are:

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

2. Why Are Keywords Important?

They Define the Core Syntax of Python

• Keywords are essential for writing control flow (if, else, while, for), functions (def, return), and exception
handling (try, except).

They Ensure Code Readability & Structure

• Reserved words make Python easy to read and understand.

They Prevent Naming Conflicts

• Python reserves these words to prevent conflicts in syntax interpretation.

3. List of All Python Keywords

To check the complete list of Python keywords, use:

import keyword
print(keyword.kwlist)

Output (Python 3.11+):

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

4. How to Avoid Naming Conflicts with Keywords?

Incorrect (Using a Keyword as a Variable Name)

def = 10 # SyntaxError: invalid syntax

Solution: Use a Different Name

my_def = 10 # No conflict

Solution: Use an Underscore (_)

class_ = "ECE Student" # Valid (Avoids conflict with 'class' keyword)

Solution: Use Meaningful Names


my_variable = 100 # Instead of 'def' or 'class'

5. Summary

Feature Reserved Words (Keywords)


Purpose Define Python’s syntax and structure
Usage Cannot be used as variable, function, or class names
Examples if, else, for, while, def, return, class
How to Avoid Conflicts? Use _ (e.g., class_), rename variables (e.g., my_def)

Using keywords correctly ensures clean, readable, and error-free Python code. Let me know if you need more examples!

You might also like