MODULE 1
1. Define keywords, statements, data types, expressions, variables, precedence, and associativity of operators
with syntax and example.
Keywords
Keywords are special reserved words that have predefined meaning in Python. These words form the vocabulary of Python language and
cannot be used as identifiers for variables, functions, or classes.
Using a keyword as a variable name will cause an error.
Examples of Python keywords are:
if, else, elif, while, for, break, continue, import, def, return, class, pass, True, False, None, etc.
Syntax Example:
Statements
A statement is a unit of code that the Python interpreter can execute.
There are various types of statements:
• Assignment Statement, Print Statement, Control Flow Statements (if, for, while, etc.)
Examples:
Variables
A variable is a named location in memory used to store data temporarily during the execution of a program.
Python variables are created when first assigned a value, and the type is decided dynamically.
Rules for variable naming:
• Must start with a letter (A–Z or a–z) or underscore _ , Cannot start with a number, No special symbols like @, $, %, Case-sensitive
Example:
Data Types
Data types specify the type of value a variable can hold.
Syntax Example:
Expressions
An expression is a combination of variables, operators, and values that yields a result.
Example:
Operators, Precedence and Associativity
Operators are special symbols that perform operations on variables and values.
Types of operators:
• Arithmetic operators: +, -, *, /, %, **, //
• Relational operators: >, <, >=, <=, ==, !=
• Logical operators: and, or, not
• Assignment operators: =, +=, -=, etc.
Operator Precedence
When multiple operators are used in an expression, Python evaluates based on precedence.
Order of Precedence (PEMDAS rule):
1. Parentheses ()
2. Exponentiation **
3. Multiplication *, Division /, Floor Division //, Modulus %
4. Addition +, Subtraction -
Example:
Associativity of Operators
Associativity determines the order when two operators of the same precedence appear:
• Left to right: Most operators
• Right to left: Exponentiation (**)
Example:
2. Explain with syntax and example different types of python data types and type( ) function.
In Python, data types specify the type of data that a variable can hold.
Every value in Python is an object, and every object belongs to a specific class or type.
Data types are very important because they determine what operations can be performed on a given piece of data.
Basic Data Types in Python
Python provides the following standard data types:
Data Type Description
Numbers Integers, Floating point numbers, Complex numbers
Boolean True or False
Strings Sequence of characters
List Ordered collection, mutable
Tuple Ordered collection, immutable
Dictionary Unordered collection of key-value pairs
None Represents absence of a value
1. Numbers
Numbers in Python are of three types:
• int: Integer numbers (e.g., 1, 100, -25)
• float: Floating-point numbers (e.g., 3.14, -0.99)
Example:
print(type(a)) # Output: <class 'int'>
print(type(b)) # Output: <class 'float'>
3. Strings
A string is a sequence of characters enclosed either within
single quotes ' ' or double quotes " ".
Multiline strings are enclosed within triple quotes ''' ''' or """ """.
Example:
5. Tuple
A tuple is similar to a list but is immutable.
Elements are enclosed within parentheses ( ).
Example:
7. None
None is a special data type representing the absence of a value or a null value.
It is often used to initialize variables that are later assigned proper values.
Example:
The type() Function
The type() function in Python is used to determine the type of an object or variable.
Thus, type() is an important built-in function for debugging and understanding data types in Python.
3. Evaluate the following expressions:
a. 4*5%2*3
b. 2**3**2
4. Order of operation in python.
In Python, when an expression contains multiple operators, the order in which these operations are performed is governed by operator
precedence and associativity rules.
Operator precedence and associativity determine how expressions are evaluated to produce a result.
Without these rules, the results could be unpredictable or incorrect.
Thus, understanding the order of operations is critical for writing correct Python programs.
Operator Precedence in Python
The precedence of operators follows a hierarchy similar to the PEMDAS rule (Parentheses, Exponents, Multiplication and Division, Addition
and Subtraction).
The higher precedence operator is evaluated before the lower precedence one.
Here is the standard precedence order in Python from highest to lowest:
Associativity of Operators
When two operators of the same precedence appear in an expression, associativity decides the order of evaluation:
Operator Associativity
** Right to Left
All other operators (+, -, *, /, //, %, etc.) Left to Right
Examples to Illustrate Order of Operations
5. Describe arithmetic operators, assignment operators, comparison operators, relational operators, and logical
operators in detail with example.
1. Arithmetic Operators
Arithmetic operators are used to perform basic mathematical operations like
addition, subtraction, multiplication, division, etc.
3. Comparison Operators (Relational Operators)
Comparison operators are used to compare two values.
They return Boolean values: True or False.
6. Discuss different forms of if control statements with necessary syntax and examples. In Python, control flow
statements allow the execution of specific blocks of code based on certain conditions.
The if statement is one of the most important decision-making structures that enables conditional execution.
There are various forms of if control statements:
1. Simple if Statement
The simplest form of control flow is the if statement.
It tests a condition: if it evaluates to True, the block of code under if is executed.
Syntax:
2. if...else Statement (Two-way decision)
When we want to perform one action if the condition is true and another action if it is false, we use the if...else statement.
Syntax:
3. if...elif...else Statement (Chained Conditionals)
Sometimes, more than two possible conditions are to be checked.
Python provides elif (short for "else if") to check multiple conditions.
4. Nested if Statement
An if statement inside another if statement is called a nested if.
It is used when a condition depends on another condition.
Syntax:
7. Explain in detail, control flow structures in python with examples.
Introduction to Control Flow
In any programming language, control flow structures
determine the order in which instructions are executed.
Python provides several control flow mechanisms that allow:
• Decision making
• Repeating a block of code
• Exiting from loops or conditions
The main control flow structures in Python are:
• Decision Making (if, if-else, if-elif-else)
• Loops (while, for)
• Branching (break, continue, pass)
8. Explain the use of break and continue statements on loops in python with relevant code example.
In Python, break and continue are control flow statements used to alter the normal execution of loops.
They are mainly used inside for and while loops to change the flow based on certain conditions.
The break Statement
• The break statement terminates the loop immediately when it is encountered.
• Control moves to the statement immediately after the loop.
• break is commonly used to exit an infinite loop or to stop iteration when a certain condition is met.
Syntax of break:
The continue Statement
• The continue statement skips the current iteration and jumps to the next iteration of the loop.
• It does not terminate the loop, but only skips the rest of the code inside the loop for the current iteration.
Syntax of continue:
9. With syntax, explain the finite and infinite looping constructs in python.
In Python, looping constructs are used to execute a block of code repeatedly.
Loops can be broadly categorized into two types:
• Finite loops: Execute a known or limited number of times.
• Infinite loops: Execute endlessly unless explicitly broken.
Understanding both types of loops is essential for writing efficient programs.
1. Finite Looping Constructs
A finite loop repeats a specific number of times based on a condition that eventually becomes false.
Python provides two main looping constructs:
a) for Loop (Definite or Finite Loop)
• Executes a block of code for each item in a sequence (like list, tuple, string) or a range.
• The number of iterations is pre-determined.
Syntax:
b) while Loop with Finite Condition
• Repeats as long as the condition is true.
• The loop must eventually make the condition false to avoid infinite execution.
2. Infinite Looping Constructs
An infinite loop is a loop that never terminates naturally because the condition always remains true.
Infinite loops are useful when waiting for an external event (e.g., server running, waiting for user input).
a) Infinite while Loop
• Common way to create infinite loops is using while True: where True is always true.
Syntax:
b) Breaking Infinite Loops Using break
In practice, infinite loops are controlled using the break statement.
Example:
10. What is a function? Mention its types and explain briefly. Write a python program to add two numbers using
function, read input from the user and print the output.
Definition of a Function
A function is a named block of reusable code that performs a specific task when called.
Functions promote modularity, reusability, and better organization of code.
Functions allow us to divide a large program into smaller pieces called modules, making debugging and maintenance easier.
Syntax to Define a Function
• def: Keyword to declare the function.
• function_name: Any valid identifier name.
• parameters: Input values (optional).
• statement(s): Body of the function that performs operations.
Calling a Function
After defining a function, it must be called to execute the
statements inside it.
Types of Functions in Python
Functions can be classified mainly into two categories:
A) Built-in Functions
• These functions are already defined by Python.
• They are always available and can be directly used.
Examples of Built-in Functions:
• print(): Outputs data to the screen.
• input(): Takes user input.
Example:
B) User-defined Functions
• These are functions created by the programmer to
perform specific tasks.
• They allow custom logic to be reused multiple times.
• def keyword is used to define user defined function.
Example:
11. Explain how to define and call user defined function in python.
Defining a User-Defined Function
A function is defined using the def keyword followed by:
• The function name
• Parentheses () containing optional parameters
• A colon :
• An indented block of code called the function body
Syntax to Define a Function
Calling a User-Defined Function
Once a function is defined, it is called to execute its code block.
Function calling is done by writing the function name followed by parentheses.
Syntax to Call a Function
Function with Parameters and Return Value
Functions can take arguments (inputs) and can also return a value using the return statement.
Example: Function with Parameters
12. Describe the for statement with an example.
In Python, the for loop is a control flow statement used for iterating over a sequence such as a list, tuple,
dictionary, string, or range object. It is one of the most commonly used looping constructs in Python because it is
simple, powerful, and readable. The for loop allows a block of code to be executed repeatedly for each item in the
sequence.
Syntax:
Example:
Output:
In the above example, the for loop iterates through each element in the list fruits and prints it.
Another common example uses the range() function to iterate over a sequence of numbers:
Here, range(1,6) generates numbers from 1 to 5, and each number is printed on a new line.
Working:
• The range() function generates a sequence of numbers starting from the start value (inclusive) to the end
value (exclusive).
• Each time through the loop, the variable is assigned the next value from the sequence.
• The block of statements within the loop body is executed.
• After all elements have been exhausted, the control exits the loop.
Features:
• It ensures definite iteration — the number of times the loop will run is known beforehand.
• The for loop can also work with strings, lists, tuples, dictionaries, and sets.
• Nested for loops are possible, where one loop can be placed inside another.
13. Illustrate *args and **kwargs parameters in python programming language with an example.
In Python, functions are extremely flexible. They can accept any number of arguments — not just a fixed number. This is possible through
two special mechanisms:
• *args — Non-keyword variable-length arguments.
• **kwargs — Keyword variable-length arguments.
These mechanisms allow us to define functions that can accept a variable number of input arguments without specifying them individually
in the function definition. This is very useful in real-world applications where the number of inputs might not be known in advance.
14. Explain the types of arguments in python functions with example for each.
In Python, arguments are the values passed to a function when it is called. Python provides several types of arguments that allow flexibility
when designing functions. Understanding different types of arguments helps in writing efficient and reusable functions.
The types of arguments in Python are:
1. Positional Arguments:
• These are the most common type of arguments.
• The order in which arguments are passed matters and should match the order of parameters in the function definition.
Example:
2. Default Arguments:
• In Python, a function can have parameters with default values.
• If no argument is provided for such parameters, their default value is used.
3. Keyword Arguments:
• In keyword arguments, the caller specifies which value goes to which parameter by using the parameter names explicitly.
• The order of arguments does not matter here.
Example:
Keyword arguments improve readability and avoid mistakes with the order.
4. Variable-length Arguments (*args and **kwargs):
Python allows a function to handle more arguments than specified in the function definition using *args ( for positional
arguments) and **kwargs (for keyword arguments).
• *args collects extra positional arguments as a tuple.
• **kwargs collects extra keyword arguments as a dictionary.
Example using *args , **kwargs:
15. Write a Python program to check whether the given year is leap year or not
A leap year is a year that is exactly divisible by 4, except for years that are exactly divisible by 100, unless the year is also exactly divisible by
400. Leap years have 366 days, with an extra day in February (29 days instead of 28).
Leap Year Rules:
1. If the year is divisible by 400, it is a leap year.
2. If the year is divisible by 100 but not divisible by 400, it is not a leap year.
3. If the year is divisible by 4 but not divisible by 100, it is a leap year.
4. Otherwise, it is not a leap year.
OR
16. Write a Python program to print the following pattern
1
12
123
1234