DataAnalytics UsingPython Module1 (1) 11
DataAnalytics UsingPython Module1 (1) 11
1. Python Keywords
repeated
Python keywords are reserved words that have special meaning in the language. They cannot
be used as identifiers (names for variables, functions, classes, etc.). Keywords are predefined
and dictate the syntax and structure of the Python language. These words are integral to the
language's grammar.
List of Python Keywords
As of Python 3.10 (the most recent stable version at my knowledge cutoff),
Python has 35 keywords:
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.
Description of Each Keyword
False
Boolean value representing "false."
Example: x = False
None
Represents the absence of a value or a null [Link]: x = None
True
Boolean value representing "true."Example: y = True
and
Logical operator that returns True if both operands are [Link]: x = True and
False (Result: False)
as
Used to create an alias while importing a module or when handling
[Link]:
import numpy as np
Or for exception handling:
try:
# code
except SomeError as e:
print(e)
assert
Used for debugging purposes; checks if a condition is True, and raises an AssertionError if
it’s [Link]:
assert x > 0, "x must be positive"
async
Marks a function as asynchronous. It is used in conjunction with [Link]:
async def my_async_func():
await some_async_operation()
await
Used to pause the execution of an asynchronous function until a task [Link]:
result = await some_async_func()
break
Exits the nearest enclosing loop, whether for or [Link]:
for i in range(10):
if i == 5:
break
class
Used to define a [Link]:
class Dog:
def __init__(self, name):
[Link] = name
continue
Skips the current iteration of a loop and proceeds to the next [Link]:
for i in range(10):
if i % 2 == 0:
continue
print(i)
def
Used to define a [Link]:
def add(a, b):
return a + b
del
Deletes an object or [Link]:
del my_variable
elif
Short for "else if," used to check multiple conditions in an if [Link]:
if x > 10:
print("x is greater than 10")
elif x == 10:
print("x is equal to 10")
else
Used in conditional statements, executed when the if condition is not [Link]:
if x > 10:
print("x is greater than 10")
else:
print("x is 10 or less")
except
Used in try-except blocks to catch and handle [Link]:
try:
x=1/0
except ZeroDivisionError:
print("Cannot divide by zero")
finally
Block of code that always executes, regardless of whether an exception [Link]:
try:
# code
except Exception:
# handle exception
finally:
print("This will always run")
for
Used to loop over a sequence (like a list, tuple, or string).Example:
for i in range(5):
print(i)
from
Used to import specific parts of a [Link]:
from math import sqrt
global
Declares a variable as global, allowing it to be modified inside a [Link]:
x = 10
def change_x():
global x
x = 20
if
Used for conditional [Link]:
if x > 10:
print("x is greater than 10")
import
Used to import a module into the current [Link]:
import math
in
Tests if a value exists in a sequence (like a list, tuple, or string).Example:
if 3 in [1, 2, 3]:
print("Found!")
is
Tests if two variables point to the same [Link]:
if x is y:
print("x and y are the same object")
lambda
Used to create small anonymous functions (i.e., functions without a name).Example:
square = lambda x: x ** 2
nonlocal
Refers to variables in the nearest enclosing scope (excluding globals).Example:
def outer():
x = 10
def inner():
nonlocal x
x = 20
inner()
print(x)
not
Logical negation operator, inverts a boolean [Link]:
if not x:
print("x is False")
or
Logical operator that returns True if at least one operand is true.
Example:
if x == 1 or y == 2:
print("Condition met")
pass
A null operation; used as a placeholder where code is syntactically required but nothing is
needed.
Example:
if x > 10:
pass # Do nothing
raise
Used to raise an exception.
Example:
raise ValueError("An error occurred")
return
Used to return a value from a function.
Example:
def add(a, b):
return a + b
try
Used to wrap code that may raise an exception for handling.
Example:
try:
x=1/0
except ZeroDivisionError:
print("Division by zero!")
while
Used to create a loop that continues as long as a condition is true.
Example:
while x < 10:
x += 1
with
Used to wrap the execution of a block of code within a context manager (commonly used for
file handling).
Example:
with open('[Link]', 'r') as file:
contents = [Link]()
yield
Used to produce a generator. It allows a function to return an iterator.
Example:
def my_generator():
yield 1
yield 2
Conclusion
Python keywords are critical to the structure of the language and determine how code is
interpreted and executed.
It’s essential to avoid using these keywords as variable names to prevent syntax errors.
These keywords are part of the core syntax of Python, and understanding their purpose and
usage will significantly help you write Python code more effectively.
2. Python Statements and Expressions
Python programs are made up of statements and expressions, both of which are fundamental
building blocks of the language. Below is a detailed breakdown of each concept.
Conclusion:
Statements are instructions that change the state of the program or control its flow.
Expressions evaluate to a value and can be part of statements.
3. Variables in Python
Variables in Python are used to store data that can be referenced and manipulated later. A
variable in Python is essentially a name associated with a value, and Python is dynamically
typed, meaning that the type of the variable is inferred from the value assigned to it, and it
can change during the program execution.
Declaring Variables
In Python, variables are declared by simply assigning a value to a name:
x = 10
name = "Alice"
pi = 3.14159
Python does not require specifying the data type when declaring variables, as it is
inferred automatically.
Variable Naming Rules
Variable names must start with a letter (a-z, A-Z) or an underscore (_).
Subsequent characters can be letters, numbers (0-9), or underscores.
Variable names are case-sensitive (name and Name are different).
Reserved keywords (like if, while, def, etc.) cannot be used as variable names.
Dynamic Typing
Python is dynamically typed, meaning the type of a variable is determined at runtime based
on its assigned value:
x = 10 # x is an integer
x = "hello" # x is now a string
Multiple Assignments
Python allows multiple assignments in a single line:
x, y, z = 5, 10, 15
2. Operators in Python
Operators in Python are symbols that perform operations on variables and values. Python
supports several types of operators:
A. Arithmetic Operators
These are used to perform mathematical operations:
+ : Addition
- : Subtraction
* : Multiplication
/ : Division (returns a float)
// : Floor Division (returns the largest integer less than or equal to the result)
% : Modulus (returns the remainder)
** : Exponentiation (raises the first number to the power of the second number)
Examples:
a = 10
b=3
a + b # 13
a-b #7
a * b # 30
a / b # 3.333...
a // b # 3
a%b #1
a ** b # 1000
B. Comparison Operators
These operators compare two values and return a boolean (True or False):
== : Equal to
!= : Not equal to
> : Greater than
< : Less than
>= : Greater than or equal to
<= : Less than or equal to
Examples:
a=5
b=3
a == b # False
a != b # True
a > b # True
a < b # False
C. Logical Operators
These are used to combine conditional statements:
and : Returns True if both statements are true
or : Returns True if at least one statement is true
not : Reverses the logical state of its operand
Examples:
x=5
y = 10
(x > 3 and y < 15) # True
(x > 3 or y > 15) # True
not (x > 3) # False
D. Assignment Operators
Used to assign values to variables:
= : Simple assignment
+= : Add and assign
-= : Subtract and assign
*= : Multiply and assign
/= : Divide and assign
//=: Floor divide and assign
%= : Modulus and assign
**=: Exponentiate and assign
Examples:
x = 10
x += 5 # x = x + 5 -> x = 15
x *= 2 # x = x * 2 -> x = 30
E. Bitwise Operators
Operate on binary representations of numbers:
& : AND
| : OR
^ : XOR
~ : NOT (inverts all the bits)
<< : Left shift
>> : Right shift
Examples:
a = 5 # 0101
b = 3 # 0011
a & b # 0001 -> 1
a | b # 0111 -> 7
a ^ b # 0110 -> 6
F. Membership Operators
Check if a value is present in a sequence (e.g., list, string):
in : Returns True if the value is found in the sequence
not in : Returns True if the value is not found in the sequence
Examples:
my_list = [1, 2, 3]
2 in my_list # True
4 not in my_list # True
G. Identity Operators
Used to compare the memory locations of two objects:
is : Returns True if two variables point to the same object
is not : Returns True if two variables point to different objects
Examples:
a = [1, 2, 3]
b=a
c = [1, 2, 3]
a is b # True (same reference)
a is not c # True (different reference)
s = "123"
num = int(s) # num = 123
Conclusion
Variables: No explicit type declaration, dynamically typed, and case-sensitive.
Operators: Several types (arithmetic, comparison, logical, etc.) with distinct
behaviors and precedence.
Precedence and Associativity: Operators are evaluated based on precedence, and
most are left-to-right associative, except ** which is right-to-left.
Data Types: Includes basic types like integers, floats, and strings, along with more
advanced types like sets, dictionaries, and binary data.
6. Python Indentation
Indentation is one of the most important aspects of Python syntax. It is used to define the
structure of the code. Unlike many other programming languages, which use braces {} to
group statements, Python relies on indentation to define the beginning and end of blocks of
code (like loops, conditionals, functions, classes, etc.).
Key Points:
Whitespace Sensitivity: Python does not use curly braces ({}) to denote code blocks;
instead, it uses indentation.
Consistency: Indentation should be consistent. Mixing tabs and spaces for indentation
in the same block can cause errors.
Standard Convention: The Python style guide (PEP 8) recommends using 4 spaces
per indentation level, though tabs are also technically allowed (but spaces are
preferred).
Examples:
# Correct Indentation
if x > 10:
print("x is greater than 10")
y=x*2
if y > 50:
print("y is greater than 50")
else:
print("y is 50 or less")
In the above code, each block of code inside the if and else statements is indented.
An indentation error will occur if you mix spaces and tabs or forget to indent a line
properly.
Common Errors:
IndentationError: This occurs when the indentation is not consistent or the expected
level of indentation is not present.
o Example:
o if x > 10:
o print("x is greater than 10") # IndentationError
7. Python Comments
Comments in Python are used to explain the code and make it more readable. They are
ignored by the interpreter during execution.
Types of Comments:
a) Single-line Comments: Used for comments that fit on a single line.
o Syntax: # comment text
o Example:
o # This is a single-line comment
o x = 5 # This is an inline comment
b) Multi-line Comments (Docstrings): Python does not have a specific syntax for block
comments, but you can use triple quotes """ or ''' to comment out multiple lines.
o Syntax:
o """
o This is a multi-line comment
o or a docstring.
o """
o Example:
o """
o This function takes two parameters, adds them,
o and returns the result.
o """
o def add(a, b):
o return a + b
o Docstrings are special types of multi-line comments used to document
functions, classes, or modules. They are accessible through the help() function
and are stored in the __doc__ attribute.
Example with Docstrings:
def greet(name):
"""
This function greets the user with the provided name.
:param name: Name of the person to greet
:return: None
"""
print(f"Hello, {name}!")
8. Reading Input in Python
Python provides built-in functions to read input from the user.
Key Functions:
1. input():
o Used to take input from the user as a string.
o Syntax: input(prompt)
o prompt is an optional string that is displayed to the user before taking the
input.
o The return value is always of type str.
Example:
# Basic input example
name = input("Enter your name: ")
print(f"Hello, {name}!")
If the user types "John", the output will be: Hello, John!
2. Converting Input Types: Since input() returns a string, if you need an integer, float,
or other types, you need to explicitly convert it using type casting functions like int()
or float().
Example:
age = int(input("Enter your age: ")) # Converts input to integer
print(f"You are {age} years old.")
Note: If the user enters non-numeric input when expecting an integer, it will raise a
ValueError. You can handle this using a try and except block.
Summary
Indentation: Python uses indentation (usually 4 spaces) to define code blocks.
Comments: Use # for single-line comments and triple quotes """ or ''' for multi-line
comments or docstrings.
Reading Input: Use input() to take user input, which returns a string. Convert it to
other types as needed.
Printing Output: Use print() for displaying output. Customize the output with sep,
end, and formatted strings (f-strings).
10. Python Study Notes on Type Conversions, the type() Function, and the is
Operator
1. Type Conversions
In Python, type conversion refers to converting one data type into another. There are two
types of type conversions:
Implicit Type Conversion (Type Coercion): This happens automatically when
Python converts one data type to another. It usually happens when the conversion is
safe, and there is no loss of data. Python does this behind the scenes.
Explicit Type Conversion (Type Casting): This is done manually by the
programmer using built-in functions.
Common Type Conversion Functions
1. int(): Converts a value to an integer.
o If the value is a string containing a valid integer, it will convert it.
o Example:
o num = int("10") # Converts string "10" to integer 10
o print(num) # Output: 10
2. float(): Converts a value to a float.
o Example:
o num = float("3.14") # Converts string "3.14" to float
o print(num) # Output: 3.14
3. str(): Converts a value to a string.
o Example:
o num = str(100) # Converts integer 100 to string "100"
o print(num) # Output: "100"
4. bool(): Converts a value to a boolean (True or False).
o Example:
o value = bool(1) # Converts integer 1 to True
o print(value) # Output: True
5. list(): Converts a sequence like a string or a tuple into a list.
o Example:
o seq = list("hello") # Converts string to list of characters
o print(seq) # Output: ['h', 'e', 'l', 'l', 'o']
6. tuple(): Converts a sequence into a tuple.
o Example:
o seq = tuple([1, 2, 3]) # Converts list to tuple
o print(seq) # Output: (1, 2, 3)
7. set(): Converts a sequence into a set (removes duplicates).
o Example:
o seq = set([1, 2, 2, 3, 4]) # Converts list to set, removing duplicates
o print(seq) # Output: {1, 2, 3, 4}
Example of Implicit Type Conversion:
x=5 # Integer
y = 2.5 # Float
3. The is Operator
The is operator in Python checks if two variables point to the same object in memory. It
compares the identity of objects, not their values.
Syntax:
a is b
It returns True if a and b refer to the same object in memory, otherwise False.
Example 1: Basic Comparison
a = [1, 2, 3]
b=a
print(a is b) # Output: True (both variables point to the same list in memory)
Example 2: Checking for Identity
x = 10
y = 10
print(x is y) # Output: True (since small integers are cached in Python)
Example 3: When is Returns False
x = [1, 2, 3]
y = [1, 2, 3]
print(x is y) # Output: False (different objects in memory, even though they have the same
values)
is vs ==
The == operator checks for equality of values, whereas the is operator checks for
identity (whether two variables point to the same object).
Example:
x = [1, 2, 3]
y = [1, 2, 3]
print(x == y) # Output: True (values are equal)
print(x is y) # Output: False (different objects in memory)
Summary of Concepts:
1. Type Conversion:
o Implicit and explicit conversion between data types.
o Common functions: int(), float(), str(), list(), tuple(), set(), bool().
2. type() Function:
o Used to check the type of a variable or object in Python.
o Returns the type of an object as a class.
3. is Operator:
o Compares the identity of two objects (whether they point to the same object in
memory).
o Use == for value comparison and is for identity comparison.
11. Python Control Flow Statements
Control flow statements allow us to control the flow of execution in a Python program. They
enable the program to make decisions, repeat actions, and branch to different paths based on
conditions.
Here are the key control flow statements in Python:
1. The if Statement
2. The if...else Statement
3. The if...elif...else Statement 2.a 2023
4. Nested if Statement
1. The if Statement
The simplest form of decision-making in Python. It evaluates a condition and executes a
block of code if the condition is True.
Syntax:
if condition:
# Code to execute if condition is True
Example:
age = 18
if age >= 18:
print("You are an adult.")
In this example, since age >= 18 evaluates to True, the message "You are an adult." will be
printed.
4. Nested if Statements
You can place an if statement inside another if statement to make more complex decisions.
This is known as a "nested" if statement.
Syntax:
if condition1:
if condition2:
# Code to execute if condition1 and condition2 are True
else:
# Code to execute if condition1 is True and condition2 is False
else:
# Code to execute if condition1 is False
Example:
age = 20
has_permission = True
Key Points:
if statement: Executes code if a condition is True.
if...else statement: Provides an alternative code block for when the condition is False.
if...elif...else statement: Allows for multiple conditions to be checked in sequence.
Nested if statements: Placing if statements within other if statements to handle more
complex logic.
These control flow statements are essential for building logic in Python programs and allow
you to make dynamic decisions based on various conditions.
These looping techniques are the backbone of many algorithms and programs, so it's
important to practice using them in different scenarios.
result = add(3, 4)
print(result) # Output: 7
result = multiply(4, 5)
print(result) # Output: 20
If no return statement is provided, Python will return None by default.
def no_return_function():
print("This function does not return anything")
result = no_return_function()
print(result) # Output: None
b) Void Function
A void function in Python is a function that does not return any value. The function performs
an operation but does not send a result back to the caller.
A function without a return statement is often considered a void function.
In Python, even a function that does not explicitly return a value still returns None
implicitly.
Example of a Void Function:
def greet_user(name):
print(f"Hello, {name}!")
Certainly! Below are detailed Python study notes covering the key concepts you've
mentioned: **Scope and Lifetime of Variables, Default Parameters, Keyword Arguments,
*args and kwargs, and Command Line Arguments.
func()
# 'x' is destroyed after func finishes execution
2. Default Parameters
In Python, you can assign default values to function parameters. These default values are
used if no argument is provided when the function is called.
Default arguments must come after non-default arguments.
If a default argument is mutable (like a list or dictionary), its value can be modified
within the function. This can lead to unexpected behavior.
Syntax:
def func(arg1, arg2=10): # arg2 has a default value
return arg1 + arg2
print(func(5)) # Output: 15
print(func(5, 20)) # Output: 25
Mutable Default Argument Pitfall:
def append_to_list(value, list=[]): # list has a default mutable value
[Link](value)
return list
3. Keyword Arguments
Keyword arguments allow you to pass arguments to a function by explicitly specifying the
parameter name. This makes the function call more readable and eliminates the need to
follow the order of parameters.
Syntax:
def func(arg1, arg2, arg3):
return arg1 + arg2 + arg3
func(1, 2, 3) # Output: 1 2 3
**kwargs (Keyword Variable-Length Arguments):
**kwargs allows a function to accept an arbitrary number of keyword arguments.
These arguments are passed as a dictionary, where the keys are argument names, and
the values are argument values.
Example:
def func(**kwargs):
for key, value in [Link]():
print(f'{key}: {value}')
func(name="Alice", age=25)
# Output:
# name: Alice
# age: 25
Combining *args and **kwargs:
You can combine *args and **kwargs in a function, but *args must come before **kwargs.
def func(arg1, *args, kwarg1=None, **kwargs):
print(f'arg1: {arg1}')
print(f'args: {args}')
print(f'kwarg1: {kwarg1}')
print(f'kwargs: {kwargs}')
# Add arguments
parser.add_argument('--name', type=str, help="Your name")
parser.add_argument('--age', type=int, help="Your age")
These concepts are essential for writing flexible and maintainable Python code, allowing you
to handle variable numbers of inputs and manage variable visibility and lifespan effectively.
Questions and Answers
Question: What are Python keywords, and why are they important in Python
programming?
Answer: Keywords in Python are reserved words that the Python interpreter recognizes
as having a specific meaning. These words cannot be used as identifiers (names for
variables, functions, etc.). Examples of keywords in Python include if, else, def, return,
class, import, etc. Keywords are fundamental to Python's syntax because they define the
structure of the language and its core functionality. For example, if is used for conditional
statements, and def is used to define a function.
Question: Explain the difference between a statement and an expression in Python with
examples.
Answer: A statement in Python is an instruction that the Python interpreter executes. It
performs an action but doesn't produce a value. For example:
Key difference:
Statement = Action
Expression = Produces a value
Question: How would you define and use variables in Python, and what are the rules
for naming them?
Answer: In Python, a variable is a name that holds a reference to a value in memory. To
define a variable, you simply assign a value to it using the assignment operator =. For
example:
age = 25
name = "Alice"
Python variables are dynamically typed, meaning their type is determined at runtime based
on the assigned value. There are several rules for naming variables:
The name must start with a letter (a-z, A-Z) or an underscore (_).
The rest of the name can include letters, numbers (0-9), and underscores.
Variable names are case-sensitive (e.g., age and Age are different).
Keywords cannot be used as variable names (e.g., if, for).
Question: What are operators in Python, and how do they differ based on their
categories? Provide examples.
Answer: Operators in Python are symbols used to perform operations on variables or
values. They can be categorized into several types:
1. Arithmetic operators:
o + (addition), - (subtraction), * (multiplication), / (division), // (floor division),
% (modulo), ** (exponentiation).
o Example: 5 + 3 results in 8.
2. Comparison operators:
o ==, !=, <, >, <=, >= (used to compare values).
o Example: 5 > 3 results in True.
3. Logical operators:
o and, or, not.
o Example: (5 > 3) and (2 < 4) results in True.
4. Assignment operators:
o =, +=, -=, *=, /=.
o Example: x += 5 is equivalent to x = x + 5.
5. Bitwise operators:
o &, |, ^, <<, >>, ~.
o Example: 5 & 3 results in 1.
6. Membership and Identity operators:
o in, not in, is, is not.
o Example: 'a' in 'apple' results in True.
Question: How does operator precedence and associativity affect the evaluation of
expressions in Python? Illustrate with an example.
Answer: Operator precedence determines the order in which operators are evaluated in
an expression. For example, multiplication has higher precedence than addition, so in an
expression like 3 + 4 * 2, the multiplication 4 * 2 is evaluated first, resulting in 3 + 8 = 11.
Associativity refers to the direction in which operators are evaluated when they have the
same precedence. Most operators in Python have left-to-right associativity (evaluated from
left to right), but the exponentiation operator (**) has right-to-left associativity.
Example:
result = 3 + 4 * 2 ** 2
Question: What are the different data types in Python, and how do they differ from each
other?
Answer: Python has several built-in data types:
1. Numeric types:
o int: Integer values, e.g., 5, -100.
o float: Decimal numbers, e.g., 3.14, -0.5.
o complex: Complex numbers, e.g., 3 + 5j.
2. Sequence types:
o list: Ordered, mutable collections, e.g., [1, 2, 3].
o tuple: Ordered, immutable collections, e.g., (1, 2, 3).
o range: Immutable sequence of numbers, e.g., range(0, 5).
3. Text type:
o str: String (text), e.g., "hello", "123".
4. Set types:
o set: Unordered, mutable collections with unique elements, e.g., {1, 2, 3}.
o frozenset: Unordered, immutable collections with unique elements.
5. Mapping type:
o dict: Unordered collection of key-value pairs, e.g., {"name": "Alice", "age":
25}.
6. Boolean type:
o bool: Represents True or False.
7. Binary types:
o bytes, bytearray, memoryview: Deal with binary data.
Each data type has its own set of operations and methods that can be performed on it.
For example:
if x > 5:
print("x is greater than 5")
Here, the statement print("x is greater than 5") is indented, which means it is part of the if
block. If the indentation is incorrect (e.g., mixing spaces and tabs or misaligned blocks),
Python will raise an IndentationError.
Question: What are comments in Python, and how are they used?
Answer: Comments in Python are used to explain and annotate the code. They are not
executed by the Python interpreter. Python supports two types of comments:
Comments are helpful for documenting the purpose of the code, explaining complex logic, or
leaving reminders.
Question: How do you read input from the user in Python, and what is the data type of
the input?
Answer: In Python, you can read input from the user using the input() function. The
input() function always returns the data as a string.
Example:
If you need to convert the input to a different data type, you can cast it. For example:
integer
---
#### Question:
How do you display output to the user in Python, and what are some common options for
formatting the output?
#### Answer:
To display output to the user, you use the `print()` function. This function can accept multiple
arguments, and it automatically converts them to strings and prints them.
Example:
```python
print("Hello, world!")
Each of these methods allows you to format strings and output dynamic values in a structured
manner.