0% found this document useful (0 votes)
2 views34 pages

DataAnalytics UsingPython Module1 (1) 11

The document covers the basics of Python programming, including keywords, statements, expressions, variables, and operators. It explains the significance of Python keywords, the difference between statements and expressions, and provides examples of various types of operators. Additionally, it highlights the dynamic typing of variables and the rules for naming them.

Uploaded by

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

DataAnalytics UsingPython Module1 (1) 11

The document covers the basics of Python programming, including keywords, statements, expressions, variables, and operators. It explains the significance of Python keywords, the difference between statements and expressions, and provides examples of various types of operators. Additionally, it highlights the dynamic typing of variables and the rules for naming them.

Uploaded by

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

Module-1

Python Basic Concepts and Programming


Keywords, Statements and Expressions, Variables, Operators, Precedence and Associativity,
Data Types, Indentation, Comments, Reading Input, Print Output, Type Conversions, The
type( ) Function and Is Operator, Control Flow Statements, The if Decision Control Flow
Statement, The if…else Decision Control Flow Statement, The if…elif…else Decision
Control Statement, Nested if Statement, The while Loop, The for Loop, The continue and
break Statements, Built-In Functions, Commonly Used Modules, Function Definition and
Calling the Function, The return Statement and void Function, Scope and Lifetime of
Variables, Default Parameters, Keyword Arguments, *args and **kwargs, Command Line
Arguments.

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.

2.1. Statements in Python


A statement in Python is an instruction that the Python interpreter can execute. A statement
does something, such as assigning a value to a variable, controlling the flow of execution
(e.g., if, while, for), or defining a function.
Types of Statements:
 Expression Statement: An expression followed by a newline (or a semicolon). For
example:
x + 2 # Expression statement
 Assignment Statement: Used to assign a value to a variable. The most common
form:
x = 10
 Conditional Statements: Used to make decisions, like if, elif, and else:
if x > 10:
print("x is greater than 10")
else:
print("x is less than or equal to 10")
 Loop Statements: Used for repeated execution, such as for and while:
for i in range(5):
print(i)
 Function Definition Statements: Used to define functions:
def my_function(x):
return x * 2
 Class Definition Statements: Used to define classes:
class MyClass:
def __init__(self, x):
self.x = x
 Return Statements: Used to return a value from a function:
def add(x, y):
return x + y
 Import Statements: Used to import modules and functions:
import math
from math import pi
 Pass Statement: A placeholder used when a statement is required syntactically but no
action is needed:
def placeholder_function():
pass # No operation
Key Points:
 A statement in Python doesn’t return a value, but it might change the state of the
program (e.g., through assignments, loops).
 Python doesn't require semicolons to end statements, though they can be used to
separate multiple statements on a single line.

2.2. Expressions in Python


An expression is any valid combination of literals, operators, and variables that results in a
value. In other words, an expression evaluates to a value.
Types of Expressions:
 Literal Expressions: A literal is a fixed value written directly in the code.
42 # Integer literal
3.14 # Floating-point literal
"Hello" # String literal
 Arithmetic Expressions: Expressions involving mathematical operations.
2 + 3 # Addition expression
10 - 4 # Subtraction expression
5 * 2 # Multiplication expression
10 / 2 # Division expression
 Relational Expressions: Expressions that compare values.
5 > 2 # Greater-than comparison (True)
3 == 3 # Equality comparison (True)
4 != 5 # Not equal comparison (True)
 Logical Expressions: Expressions involving logical operators (and, or, not).
True and False # Logical AND
True or False # Logical OR
not True # Logical NOT
 List, Set, and Dictionary Expressions:
o List Expressions:
o [x * 2 for x in range(5)] # List comprehension
o Set Expressions:
o {x for x in range(5)} # Set comprehension
o Dictionary Expressions:
o {x: x * 2 for x in range(5)} # Dictionary comprehension
 Lambda Expressions: Anonymous functions defined using lambda.
square = lambda x: x * x
Expression Evaluation:
 An expression is evaluated based on operator precedence and associativity.
 Expressions can consist of one or more operands (e.g., variables, literals, etc.) and
operators (e.g., +, -, *, etc.).
Key Points:
 An expression always results in a value.
 Python expressions can be simple (like a number or string) or complex (like a
function call or list comprehension).
 In Python, even assignments like x = 10 are technically expressions because they
return the value assigned (x in this case).

2.3. Difference Between Statements and Expressions


Aspect Statement Expression
Definition A statement is an An expression is a combination of
instruction to the Python values, variables, operators, and
interpreter to perform an function calls that evaluates to a value.
action.
Result Statements do not return Expressions always evaluate to a
values (except for return value.
statements).
Examples x = 5, if, for, while, def x + 2, 3 * 5, y == 10, print("Hi")
Can it be used No, statements can't be part Yes, expressions can be part of
in an expression? of an expression. statements.
Example: Combining Statements and Expressions
x = 10 # Statement: Assignment
print(x + 5) # Statement: Function call (expression inside)
Here:
 x = 10 is a statement that assigns a value.
 x + 5 is an expression that evaluates to 15.
 print(x + 5) is a statement that calls the print() function with an expression inside.

2.4. Expression vs. Statement Evaluation


 Expression Evaluation: The process of calculating the value of an expression.
o Example:
o x = 3 + 4 # '3 + 4' is an expression that evaluates to 7
 Statement Execution: The process of carrying out the instruction in a statement.
o Example:
o x = 3 + 4 # This is a statement where an expression is executed, resulting in
assignment

2.5. Expression as a Statement


In Python, it's possible to use an expression as a statement:
x = (y + 2) * 3 # This is an expression within a statement (assignment).
Even though x = (y + 2) * 3 contains an expression, it's part of an assignment statement.

2.6. Evaluating Expressions in Context


Expressions can be used in various contexts within statements:
 In Conditional Statements:
 if x > 10: # Expression 'x > 10'
 print("x is greater than 10")
 In Loops:
 for i in range(5): # Expression 'range(5)'
 print(i)
 In Function Calls:
 print(2 + 3) # Expression '2 + 3' passed as an argument to the function

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)

4. Precedence and Associativity


Operator precedence defines the order in which operators are evaluated in an expression, and
associativity determines the direction in which operators of the same precedence are
evaluated.
Operator Precedence
Operators with higher precedence are evaluated before operators with lower precedence.
Operator precedence (from highest to lowest):
1. Parentheses () (highest precedence)
2. Exponentiation **
3. Unary plus, minus, and bitwise NOT +x, -x, ~x
4. Multiplication, Division, Floor Division, Modulus *, /, //, %
5. Addition and Subtraction +, -
6. Bitwise shifts <<, >>
7. Bitwise AND &
8. Bitwise XOR ^
9. Bitwise OR |
10. Comparison Operators ==, !=, <, >, <=, >=
11. Logical NOT not
12. Logical AND and
13. Logical OR or (lowest precedence)
Associativity
 Most operators in Python have left-to-right associativity, meaning they are evaluated
from left to right.
 The exponentiation operator ** has right-to-left associativity, meaning 2 ** 3 ** 2 is
evaluated as 2 ** (3 ** 2).
Example:
2 + 3 * 5 # Result is 17, because * has higher precedence than +

5. Data Types in Python


Python has several built-in data types, which can be categorized into:
A. Numeric Types
 int: Integer type. Example: a = 10 1.b 2023
 float: Floating-point number type. Example: b = 10.5
 complex: Complex number type. Example: c = 2 + 3j
B. Sequence Types
 str: String type. Example: name = "Alice"
 list: List (mutable ordered collection). Example: my_list = [1, 2, 3]
 tuple: Tuple (immutable ordered collection). Example: my_tuple = (1, 2, 3)
C. Set Types
 set: Set (unordered collection of unique elements). Example: my_set = {1, 2, 3}
 frozenset: Immutable set. Example: frozen_set = frozenset([1, 2, 3])
D. Mapping Type
 dict: Dictionary (unordered collection of key-value pairs). Example: my_dict =
{"name": "Alice", "age": 30}
E. Boolean Type
 bool: Boolean type representing True or False.
F. Binary Types
 bytes: Immutable sequence of bytes. Example: b = b"hello"
 bytearray: Mutable sequence of bytes. Example: b_arr = bytearray([65, 66, 67])
 memoryview: Memory view of a byte array. Example: mv =
memoryview(bytearray([65, 66, 67]))
Type Conversion
Python allows conversion between different data types using functions like int(), float(), str(),
etc.
x = 10.5
y = int(x) # y = 10

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.

9. Printing Output in Python


Python uses the print() function to display output to the console.
Syntax:
print(value, ..., sep=' ', end='\n', file=[Link], flush=False)
 value: Values to be printed (can be any type: string, number, list, etc.).
 sep: (optional) Specifies the separator between multiple values (default is space ' ').
 end: (optional) Specifies what to append at the end of the output (default is a newline
\n).
 file: (optional) Specifies the file where the output is printed (default is [Link], i.e.,
the console).
 flush: (optional) If set to True, forces the output to be flushed to the file.
Examples:
1. Basic Output:
print("Hello, world!") # Output: Hello, world!
2. Multiple Arguments:
name = "John"
age = 25
print("Name:", name, "Age:", age) # Output: Name: John Age: 25
3. Changing Separator:
print("apple", "banana", "cherry", sep=', ') # Output: apple, banana, cherry
4. Custom End:
print("Hello", end=" ")
print("World!") # Output: Hello World! (with no newline between the prints)
5. Formatted Strings (f-strings): F-strings (formatted string literals) allow embedding
expressions inside string literals, using curly braces {}. This is available in Python 3.6
and later.
name = "Alice"
age = 30
print(f"Name: {name}, Age: {age}") # Output: Name: Alice, Age: 30
6. Printing to a File:
with open("[Link]", "w") as f:
print("This is written to the file.", file=f)
7. Printing Lists and Dictionaries:
my_list = [1, 2, 3, 4]
print(my_list) # Output: [1, 2, 3, 4]
my_dict = {"name": "John", "age": 25}
print(my_dict) # Output: {'name': 'John', 'age': 25}

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

result = x + y # Implicit conversion of x (int) to float


print(result) # Output: 7.5 (float)
In this case, Python automatically converts the integer x to a float before performing the
addition.
2. The type() Function
The type() function is used to determine the type of an object or variable in Python.
 Syntax:
 type(object)
The type() function returns the type of the object as a class type.
Examples:
1. Getting the Type of an Integer:
2. num = 10
3. print(type(num)) # Output: <class 'int'>
4. Getting the Type of a String:
5. name = "Python"
6. print(type(name)) # Output: <class 'str'>
7. Getting the Type of a List:
8. numbers = [1, 2, 3]
9. print(type(numbers)) # Output: <class 'list'>
10. Checking the Type of a Float:
11. pi = 3.14
12. print(type(pi)) # Output: <class '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.

2. The if...else Statement


The else block is executed when the condition in the if statement is False. It provides an
alternative action.
Syntax:
if condition:
# Code to execute if condition is True
else:
# Code to execute if condition is False
Example:
age = 16
if age >= 18:
print("You are an adult.")
else:
print("You are a minor.")
In this case, since age >= 18 is False, the program prints "You are a minor.".

3. The if...elif...else Statement


When you have multiple conditions to check, you can use elif (short for "else if") to check
additional conditions. If none of the conditions are True, the else block is executed.
Syntax:
if condition1:
# Code to execute if condition1 is True
elif condition2:
# Code to execute if condition2 is True
elif condition3:
# Code to execute if condition3 is True
else:
# Code to execute if all conditions are False
Example:
age = 70
if age < 18:
print("You are a minor.")
elif age >= 18 and age <= 65:
print("You are an adult.")
else:
print("You are a senior citizen.")
Output:
You are a senior citizen.
In this example, since age is 70, the third condition in the elif block is True, so it prints "You
are a senior citizen.".

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

if age >= 18:


if has_permission:
print("You are allowed to access the content.")
else:
print("You do not have permission to access the content.")
else:
print("You are not allowed to access the content.")
Output:
You are allowed to access the content.
In this example, since the outer if condition (age >= 18) is True, the inner if statement checks
whether has_permission is True to decide the output.

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.

12. Python Looping Mechanisms:


In Python, loops allow you to execute a block of code repeatedly based on a condition. There
are two primary types of loops: while loops and for loops. In addition, the continue and break
statements are used to control the flow of loops. Let's dive into the details.

1. The while Loop:


A while loop repeats a block of code as long as the given condition is True.
Syntax:
while condition:
# Code to execute repeatedly
 condition: This is an expression that evaluates to a boolean value (True or False). If
the condition is True, the block of code inside the loop will run. If it's False, the loop
ends.
 The loop continues to run until the condition evaluates to False.
Example:
count = 0
while count < 5:
print("Count is:", count)
count += 1 # increment count
Output:
Count is: 0
Count is: 1
Count is: 2
Count is: 3
Count is: 4
 In this example, the loop runs as long as count < 5. The count is incremented in each
iteration, and once it reaches 5, the loop terminates.
Key Points:
 Ensure the condition eventually becomes False to avoid an infinite loop (e.g., a
condition that is always True).
 If the condition is initially False, the code inside the loop will not execute.

2. The for Loop:


The for loop in Python is typically used for iterating over a sequence (like a list, tuple,
dictionary, or string) or any other iterable object.
Syntax:
for item in iterable:
# Code to execute for each item
 iterable: This is the sequence or collection that you want to iterate over.
 item: Represents the current value in the iteration (each element of the iterable).
Example 1: Looping Over a List:
fruits = ["apple", "banana", "cherry"]
for fruit in fruits:
print(fruit)
Output:
apple
banana
cherry
Example 2: Using range() with for Loop:
You can use the range() function to create a sequence of numbers and iterate over them.
for i in range(1, 6): # range(start, stop)
print(i)
Output:
1
2
3
4
5
 The range() function generates numbers starting from 1 up to (but not including) 6.
Key Points:
 The for loop is used when the number of iterations is known, or when iterating over a
collection.
 You can iterate over strings, lists, tuples, dictionaries, and other iterables.

3. The continue Statement:


The continue statement is used to skip the rest of the code inside a loop for the current
iteration and proceed with the next iteration of the loop.
Syntax:
continue
 When the continue statement is encountered, the current iteration is immediately
stopped, and the loop proceeds with the next iteration.
Example 1: Skipping Even Numbers:
for i in range(1, 6):
if i % 2 == 0:
continue # skip even numbers 2.a.2 2023
print(i)
Output:
1
3
5
 The continue statement causes the loop to skip the even numbers (2 and 4 in this
case).
Key Points:
 The continue statement only affects the current iteration of the loop and moves to
the next iteration.
 It is useful when you want to skip over certain conditions without terminating the
entire loop.

4. The break Statement:


The break statement is used to exit the loop prematurely, regardless of the condition. Once
the break statement is encountered, the loop terminates, and the program continues executing
from the next statement after the loop.
Syntax:
break
Example 1: Breaking After 3 Iterations:
for i in range(1, 6):
if i == 4:
break # exit loop when i equals 4
print(i)
Output:
1
2
3
 When i reaches 4, the break statement is triggered, and the loop exits.
Example 2: Breaking in a while loop:
count = 0
while True:
if count == 3:
break
print(count)
count += 1
Output:
0
1
2
 This is an example of an infinite while loop that is broken when count reaches 3.
Key Points:
 The break statement is useful when you want to exit the loop based on some condition
before the loop naturally ends.
 It terminates the loop entirely, and the program continues after the loop block.

Loop Control Flow Summary:


Statement Purpose Example Usage
Repeats a block of code as long as the condition While loop to perform actions
while
is True. repeatedly.
Loop through a list, string, or
for Iterates over each item in a sequence or a range.
range.
Skips the current iteration of the loop and moves Skip specific iterations based
continue
to the next iteration. on conditions.
Exits the loop prematurely, regardless of the Exit a loop based on a
break
loop condition. condition.

Important Points to Remember:


1. Infinite Loops: Always ensure that the condition in a while loop is eventually False.
Otherwise, you might end up with an infinite loop.
2. Loop Termination: You can terminate a loop early using break, and skip an iteration
using continue.
3. Nested Loops: You can have loops within loops (nested loops). In such cases, break
will only break out of the innermost loop, and continue will only affect the current
iteration of the innermost loop.
Example of Nested Loops:
for i in range(3):
for j in range(3):
if j == 1:
continue # Skip the second iteration
print(f"i: {i}, j: {j}")
Output:
i: 0, j: 0
i: 0, j: 2
i: 1, j: 0
i: 1, j: 2
i: 2, j: 0
i: 2, j: 2
 In this nested loop, the continue skips the second iteration of the inner loop (where j
== 1).

These looping techniques are the backbone of many algorithms and programs, so it's
important to practice using them in different scenarios.

13.1. Built-In Functions


Python provides many built-in functions that perform a wide range of operations without
needing to import any libraries. Below are some of the commonly used built-in functions:
a) Type-Related Functions:
 type(object)
Returns the type of an object.
 print(type(5)) # <class 'int'>
 print(type("Hello")) # <class 'str'>
 isinstance(object, classinfo)
Checks if an object is an instance or subclass of a class or a tuple of classes.
 isinstance(5, int) # True
 isinstance("Hello", str) # True
b) Mathematical Functions:
 abs(x)
Returns the absolute value of a number.
 abs(-5) # 5
 pow(x, y)
Returns x raised to the power y (i.e., xyx^y).
 pow(2, 3) # 8
 min(iterable)
Returns the smallest item in an iterable.
 min([5, 2, 8, 1]) # 1
 max(iterable)
Returns the largest item in an iterable.
 max([5, 2, 8, 1]) # 8
c) String Functions:
 len(s)
Returns the length of a string, list, or any iterable.
 len("Hello") # 5
 str(object)
Converts an object to a string.
 str(123) # '123'
 input(prompt)
Accepts user input as a string.
 name = input("Enter your name: ") # User types 'Alice'
d) Iterable-Related Functions:
 list(iterable)
Converts an iterable (e.g., tuple, string) to a list.
 list((1, 2, 3)) # [1, 2, 3]
 tuple(iterable)
Converts an iterable to a tuple.
 tuple([1, 2, 3]) # (1, 2, 3)
 set(iterable)
Converts an iterable to a set (removes duplicates).
 set([1, 2, 2, 3]) # {1, 2, 3}
 sorted(iterable)
Returns a sorted list from the elements of any iterable.
 sorted([3, 1, 4, 2]) # [1, 2, 3, 4]
e) Other Useful Built-In Functions:
 sum(iterable)
Returns the sum of an iterable (e.g., list of numbers).
 sum([1, 2, 3, 4]) # 10
 open(file,mode)
Opens a file and returns a file object.
 file = open('[Link]', 'r')
 help(object)
Provides a helpful description of the object (e.g., module, function).
 help(str) # Shows documentation for the str class

2. Commonly Used Modules


Python includes several modules that offer various functionalities. Some of the most
commonly used modules include:
a) math
Provides mathematical functions and constants.
 [Link](x) - Returns the square root of x.
 import math
 print([Link](16)) # 4.0
 [Link] - The mathematical constant pi.
 print([Link]) # 3.141592653589793
b) random
Generates random numbers and selects random items.
 [Link](a, b) - Returns a random integer between a and b.
 import random
 print([Link](1, 10)) # Random integer between 1 and 10
 [Link](sequence) - Returns a random item from a sequence.
 print([Link]([1, 2, 3, 4, 5])) # Random choice from the list
c) datetime
Deals with date and time objects.
 [Link]() - Returns the current date and time.
 import datetime
 print([Link]()) # Current date and time
 [Link](date_string, format) - Converts a string into a datetime
object.
 date_string = '2025-01-08'
 date_obj = [Link](date_string, '%Y-%m-%d')
 print(date_obj) # 2025-01-08 00:00:00
d) os
Interacts with the operating system.
 [Link]() - Returns the current working directory.
 import os
 print([Link]()) # e.g., '/home/user'
 [Link](path) - Lists files and directories in the specified path.
 print([Link]('.')) # Lists files in the current directory

3. Function Definition and Calling the Function


a) Defining a Function
In Python, functions are defined using the def keyword. A function can take parameters,
execute a block of code, and return a result.
Syntax:
def function_name(parameters):
# Function body
# Operations
return value 2.b 2023
Example:
def greet(name):
return f"Hello, {name}!"

print(greet("Alice")) # Output: Hello, Alice!


b) Calling a Function
Once a function is defined, it can be called by its name, followed by parentheses. If the
function requires parameters, those are passed inside the parentheses.
Example:
def add(a, b):
return a + b

result = add(3, 4)
print(result) # Output: 7

4. The return Statement and Void Function


a) The return Statement
The return statement is used to exit a function and return a value to the caller. Once a
function encounters a return statement, it stops execution and returns the value specified.
Syntax:
def function_name(parameters):
# Some logic
return value
Example:
def multiply(x, y):
return x * y

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}!")

greet_user("Alice") # Output: Hello, Alice!


In this example, the function does not return any value; it only prints the greeting. Thus, it is
a void function.

Summary of Key Points:


1. Built-In Functions: Python has many useful built-in functions, such as type(), len(),
min(), sum(), etc.
2. Common Modules: Modules like math, random, datetime, and os provide essential
functionality for mathematical operations, randomization, date-time manipulation, and
interacting with the operating system.
3. Function Definition and Calling: Functions in Python are defined using the def
keyword. They are called by their name with appropriate arguments inside
parentheses.
4. The return Statement and Void Functions: A function can return a value using
return, or it can be a void function that performs an operation without returning
anything.

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.

1. Scope and Lifetime of Variables


Scope
The scope of a variable refers to the region of the code where that variable can be accessed or
modified. Python defines different scopes based on where a variable is declared:
 Local Scope: Variables declared inside a function or block are local to that
function/block. These variables can only be accessed within that function/block.
 Enclosing Scope: This refers to the scope of any enclosing functions, like in nested
functions. If a variable is not found in the local scope, Python looks for it in the
enclosing scope.
 Global Scope: Variables declared at the top level of a script or module are in the
global scope. They can be accessed anywhere in the module but must be explicitly
marked as global if they are to be modified inside a function.
 Built-in Scope: The built-in scope contains names that are available by default in all
Python programs, like print(), len(), and range().
LEGB Rule:
The order in which Python looks for a variable is determined by the LEGB rule (Local,
Enclosing, Global, Built-in).
Lifetime
The lifetime of a variable refers to the period during which it exists in memory. It starts when
the variable is created and ends when it is destroyed. The lifetime depends on the scope of the
variable.
 Local variables have a lifetime limited to the execution of the function they are
defined in.
 Global variables remain in memory as long as the program is running.
Example:
def func():
x = 10 # 'x' exists during the execution of func

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

print(append_to_list(1)) # Output: [1]


print(append_to_list(2)) # Output: [1, 2] (unexpected)
To avoid this, use None as the default value and create a new list inside the function if
necessary:
def append_to_list(value, list=None):
if list is None:
list = []
[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

# Using keyword arguments


result = func(arg1=5, arg3=10, arg2=15)
print(result) # Output: 30
Key Points:
 The order of keyword arguments does not matter.
 A function can accept arbitrary keyword arguments using **kwargs.

4. *args and **kwargs


*args (Non-keyword Variable-Length Arguments):
 *args allows a function to accept an arbitrary number of positional arguments.
 These arguments are passed as a tuple.
Example:
def func(*args):
for arg in args:
2.a.1 2022
print(arg)

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}')

func(1, 2, 3, kwarg1="Test", extra="Extra")


# Output:
# arg1: 1
# args: (2, 3)
# kwarg1: Test
# kwargs: {'extra': 'Extra'}

5. Command Line Arguments


Python allows you to pass arguments to a script via the command line. These arguments are
accessible using the [Link] list from the sys module.
[Link]:
 [Link] is a list where the first element is the script name, and the remaining
elements are the command line arguments passed to the script.
Example:
# Save this as [Link]
import sys

print("Script name:", [Link][0])


print("Arguments:", [Link][1:])
To run the script from the command line:
python [Link] arg1 arg2 arg3
The output will be:
Script name: [Link]
Arguments: ['arg1', 'arg2', 'arg3']
Parsing Command Line Arguments with argparse:
argparse is a module in Python for parsing command line arguments. It provides more
flexibility and is often used for more complex argument parsing.
import argparse

# Create an argument parser


parser = [Link](description="This is a sample script")

# Add arguments
parser.add_argument('--name', type=str, help="Your name")
parser.add_argument('--age', type=int, help="Your age")

# Parse the arguments


args = parser.parse_args()

print(f"Hello, {[Link]}. You are {[Link]} years old.")


To run the script:
python [Link] --name Alice --age 30
Output:
Hello, Alice. You are 30 years old.

Summary of Key Concepts:


 Scope: Refers to the visibility and accessibility of variables. The LEGB rule defines
the order in which Python searches for variables.
 Lifetime: Refers to how long a variable exists in memory.
 Default Parameters: Function parameters that have default values.
 Keyword Arguments: Allows you to specify arguments by name when calling a
function.
 *args: Allows a function to accept any number of positional arguments.
 **kwargs: Allows a function to accept any number of keyword arguments.
 Command Line Arguments: Use [Link] or argparse to handle command-line input.

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

1. Keywords (Level 1: Remembering)

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.

2. Statements and Expressions (Level 2: Understanding)

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:

 x = 10 is a statement because it assigns a value to a variable.

An expression is a combination of values, variables, operators, and functions that the


interpreter can evaluate to produce a value. For example:

 3 + 5 is an expression because it can be evaluated to produce the value 8.

Key difference:

 Statement = Action
 Expression = Produces a value

3. Variables (Level 3: Applying)

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).

4. Operators (Level 3: Applying)

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.

5. Precedence and Associativity (Level 4: Analyzing)

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

1. First, 2 ** 2 is evaluated (exponentiation has the highest precedence).


2. Then, 4 * 4 is evaluated.
3. Finally, 3 + 16 is evaluated, resulting in 19.

6. Data Types (Level 2: Understanding)

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.

7. Indentation (Level 2: Understanding)


Question:Why is indentation important in Python, and how does it affect the structure
of the program?
Answer:In Python, indentation is used to define the structure and scope of code blocks
instead of curly braces {} (as in many other programming languages). Indentation signifies
which statements belong to a certain control structure (like loops or functions).

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.

8. Comments (Level 1: Remembering)

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:

1. Single-line comments: Begin with the # symbol. Example:


2. # This is a single-line comment
3. x = 10
4. Multi-line comments: Can be created by using triple quotes ''' or """. Example:
5. """
6. This is a multi-line comment.
7. It spans multiple lines.
8. """

Comments are helpful for documenting the purpose of the code, explaining complex logic, or
leaving reminders.

9. Reading Input (Level 3: Applying)

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:

name = input("Enter your name: ")


age = input("Enter your age: ")
print("Hello, " + name + "!")

If you need to convert the input to a different data type, you can cast it. For example:

age = int(input("Enter your age: ")) # Converts input to an

integer

---

### 10. **Print Output (Level 3: Applying)**

#### 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!")

You can also format output using:

1. f-strings (formatted string literals, Python 3.6+):


2. name = "Alice"
3. print(f"Hello, {name}!")
4. The format() method:
5. name = "Alice"
6. print("Hello, {}!".format(name))
7. Old-style string formatting:
8. name = "Alice"
9. print("Hello, %s!" % name)

Each of these methods allows you to format strings and output dynamic values in a structured
manner.

You might also like