0% found this document useful (0 votes)
4 views60 pages

DAP_1_module

This document provides an introduction to Python programming, covering its design philosophy, execution model, and fundamental concepts such as flow control, data types, and operators. It explains the differences between interpreters and compilers, the structure of Python programs, and the importance of indentation and comments. Additionally, it outlines key programming constructs like variables, functions, and control structures essential for building Python applications.

Uploaded by

sharadhi080808
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)
4 views60 pages

DAP_1_module

This document provides an introduction to Python programming, covering its design philosophy, execution model, and fundamental concepts such as flow control, data types, and operators. It explains the differences between interpreters and compilers, the structure of Python programs, and the importance of indentation and comments. Additionally, it outlines key programming constructs like variables, functions, and control structures essential for building Python applications.

Uploaded by

sharadhi080808
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
You are on page 1/ 60

MODULE – 1

Introduction to Python Programming Language


Python is a high-level, interpreted, general-purpose programming language that is
widely used across various domains like web development, data science, artificial
intelligence, automation, and more.

Python's main design philosophy emphasizes code readability and simplicity, allowing
programmers to express concepts in fewer lines of code compared to languages like C++ or
Java.

Conversing with Python (Running Python Code)

To write and execute Python programs, one must first install Python and set up an
environment.

3. Command Line Execution

• Python programs can also be written in any text editor and run from the command
line:

python myprogram.py

Programming Languages and Translation


A computer only understands machine language, which is made up of binary digits (0s
and 1s). But writing programs directly in machine language is very difficult and error-prone.

To make programming easier, high-level languages like Python, C, Java, etc., were
developed. These languages are human-readable and easier to understand. However,
computers cannot understand high-level languages directly, so we need translators to
convert them into machine language.

There are two types of translators:

• Interpreter

• Compiler

Interpreter vs Compiler (Differences and Explanation)


Aspect Interpreter Compiler

Translation
Translates line by line Translates the whole program at once
Method

Execution Slower, as it translates each line Faster, as it translates the entire code
Speed at runtime before execution

Error Stops and shows error Shows all errors at the end of
Detection immediately when found compilation

Does not create intermediate Creates intermediate object code


Memory Usage
code, uses less memory (.exe/.class), uses more memory

Easier, as it identifies errors line Harder, as errors appear after full


Debugging
by line compilation

s of Languages Python, Ruby, JavaScript C, C++, Java

No separate output file; runs


Output Creates a separate executable file
directly

Good for small programs or


Efficiency Better for large programs
scripts

Python’s Execution Model

Python uses both a compiler and an interpreter, but not in the traditional sense like C or
Java.

Steps in Python Execution:

1. Writing the Program (Source Code)

• Python programs are written in .py files using any text editor or IDE like PyCharm,
Jupyter, or IDLE.

• code (hello.py):

print("Hello, Python!")

2. Compilation to Byte Code

• Python compiles the code to byte code, which is a low-level set of instructions
understood by the Python Virtual Machine (PVM).
• Byte code is stored in .pyc files inside a folder called __pycache__.

• This step makes the code platform-independent.

3. Interpretation by PVM

• The PVM (Python Virtual Machine) reads the .pyc file and converts byte code into
machine code based on the OS and processor.

• The machine code is executed by the CPU, and the output is shown.

Parts of a Python Program

A typical Python program consists of the following parts:

1. Comments

2. Docstrings

3. Import Statements

4. Variables and Data Types

5. Expressions and Statements

6. Control Structures

7. Functions

8. Classes and Objects (OOP)

PYTHON MODULES
Flow Control in Python
Flow control allows you to control the order in which instructions are executed in a
program. These constructs are found in almost every programming language and are
fundamental to logic building.

Types of Flow Control Structures

1. Sequential Execution

o Statements are executed one after another, from top to bottom.

a = 10
b = 20

print(a + b)

2. Conditional Execution

o Used to make decisions based on certain conditions.

o Uses if, if-else, and if-elif-else statements.

age = 18

if age >= 18:

print("Adult")

else:

print("Minor")

3. Repeated Execution (Loops)

o Used when you want to repeat a block of code multiple times.

o Types:

▪ for loop (useful for iterating over a sequence)

▪ while loop (runs as long as the condition is true)

for i in range(5):

print(i)

4. Reuse (Functions and Modules)

o Define a block of code once and reuse it whenever required.

def greet(name):

print("Hello", name)

greet("Alice")

Identifiers
• Identifiers are names used by a programmer to name variables, functions,
classes, modules, and objects.

• They make the code readable and manageable.


Rules (in detail):

• Must begin with a letter (A-Z, a-z) or an underscore (_)

• Followed by letters, digits (0-9), or underscores (_).

• No special characters like @, #, $, %, ! allowed.

• Cannot be a keyword.

• Case-sensitive: Data and data are different.

s of Invalid Identifiers:

• 2name (cannot start with a number)

• my-name (dash is not allowed)

• class (keyword)

Good Practice:

• Use meaningful names:

total_marks = 450

student_name = "John"

Variables
• A variable is a symbolic name that is a reference to an object.

• Variables do not have fixed type in Python (dynamic typing).

Important Features:

• Assignment happens automatically when you assign a value.

• Reassignment is allowed: You can change the value of a variable anytime.

s:

x = 10 # integer

x = "Hello" # now x is a string

Here, x first holds an integer, then holds a string — dynamic typing.

Tip:
You can assign the same value to multiple variables:

a = b = c = 100

Or assign multiple values:

a, b, c = 1, 2, 3

Keywords
• Keywords are special words reserved by the Python language.

• They define the structure and flow of a program.

Important Notes:

• Total keywords in Python 3.x are around 35+ (depends on version).

• Cannot use keywords as variable names.

List of Important Keywords:

Conditional Looping Others

for, while, break, import, def, return, class, try, except, finally, with, as,
if, else, elif
continue pass, lambda

def my_function(): # def is a keyword

pass # pass is a keyword

Statements
• A statement is a logical instruction that Python interpreter can execute.

• Statements perform actions like assigning a value, making decisions, looping over
data, etc.

Types of Statements in Python:

Type

Assignment Statement x = 10

Conditional Statement if x > 5: print(x)


Type

Looping Statement for i in range(5): print(i)

Import Statement import math

Function Definition Statement def greet(): print("Hi")

Print statement Print(“hello”)

showing multiple statements:

x=5

if x > 0:

print("Positive")

else:

print("Negative")

Each line is a statement!

Expressions
• An expression is a combination of operands (variables, literals) and operators
(like +, *, /) that produces a new value.

Important Features:

• Always evaluates to a value.

• Expressions are used inside statements.

• Can be arithmetic, logical, or relational.

Expression Type Result

Arithmetic 3+5 8

Logical True and False False

Relational 10 > 5 True


in Code:

result = (5 + 3) * 2

# (5+3) = 8 -> 8*2 = 16

Here, (5 + 3) * 2 is the expression, and result = 16 is the assignment statement.

Operators
Operators are special symbols or keywords in Python that are used to perform
operations on variables and values.

Types of Operators in Python:

Type of Operator Description

1. Arithmetic Operators Perform mathematical operations

2. Assignment Operators Assign values to variables

3. Comparison (Relational) Operators Compare two values

4. Logical Operators Perform logical operations

5. Bitwise Operators Perform bit-level operations

6. Membership Operators Test membership in a sequence

7. Identity Operators Compare memory locations of objects

1⃣ Arithmetic Operators

Used to perform basic mathematical operations like addition, subtraction,


multiplication, division, etc.

Operator Meaning Example Output

+ Addition 3+5 8

- Subtraction 10 - 4 6

* Multiplication 2*6 12
Operator Meaning Example Output

/ Division (float result) 8/2 4.0

// Floor Division (integer result) 9 // 2 4

% Modulus (remainder) 9%4 1

** Exponent (power) 2 ** 3 8

a = 10

b=3

print(a + b) # 13

print(a // b) # 3

print(a % b) # 1

2⃣ Assignment Operators

Used to assign values to variables.

Operator Meaning Example

= Assign x=5

+= Add and assign x += 3 → x = x + 3

-= Subtract and assign x -= 2

*= Multiply and assign x *= 4

/= Divide and assign x /= 2

//= Floor divide and assign x //= 2

%= Modulus and assign x %= 2

**= Exponent and assign x **= 3

x=5

x += 2 # x = x + 2 → 7

print(x)
3⃣ Comparison (Relational) Operators

Used to compare two values and return True or False.

Operator Meaning Example Output

== Equal to 5 == 5 True

!= Not equal to 5 != 3 True

> Greater than 5>3 True

< Less than 5<3 False

>= Greater than or equal to 5 >= 5 True

<= Less than or equal to 5 <= 3 False

a = 10

b = 20

print(a < b) # True

print(a == b) # False

4️⃣ Logical Operators

Used to combine multiple conditional statements.

Operator Meaning Example Output

and True if both statements are true (5 > 2) and (4 > 1) True

or True if at least one statement is true (5 > 10) or (4 > 1) True

not Reverses the result not(5 > 2) False

a = True

b = False

print(a and b) # False

print(a or b) # True

print(not a) # False
5⃣ Bitwise Operators

Used to perform operations at bit-level (0s and 1s).

Operator Meaning Example Output (binary)

& AND 5 & 3 → 0101 & 0011 0001 (1)

` ` OR `5

^ XOR 5^3 0110 (6)

~ NOT ~5 -(5+1) = -6

<< Left Shift 5 << 1 10

>> Right Shift 5 >> 1 2

a = 5 # 0101

b = 3 # 0011

print(a & b) # 1

print(a | b) # 7

6️⃣ Membership Operators

Test if a value is a member of a sequence (like string, list, tuple).

Operator Meaning Example Output

in True if value is found in sequence "a" in "cat" True

not in True if value not found in sequence "x" not in "cat" True

fruits = ["apple", "banana", "mango"]

print("apple" in fruits) # True

print("grape" not in fruits) # True

7️⃣ Identity Operators

Compare memory locations (whether two variables refer to the same object).
Operator Meaning Example Output

is True if both variables point to same object x is y

is not True if both variables do not point to same object x is not y

a = [1,2,3]

b=a

c = [1,2,3]

print(a is b) # True (same memory reference)

print(a is c) # False (different memory reference)

Precedence and Associativity


When an expression has multiple operators, Python follows operator precedence and
associativity rules to evaluate them correctly.

Operator Precedence (PEMDAS Rule)

Priority Operator Description

1 () Parentheses

2 ** Exponentiation

3 *, /, //, % Multiplication, Division, etc.

4 +, - Addition and Subtraction

5 <, >, ==, etc. Comparison

6 not Logical NOT

7 and Logical AND

8 or Logical OR

Associativity
• Left to Right: Most operators like +, -, *, /, //, % follow left-to-right associativity.

• Right to Left: The ** (exponentiation) operator is right associative.

print(2 ** 3 ** 2) # 512, not 64

# Explanation: 3**2 = 9, then 2**9 = 512

Full Combining All Rules

result = (3 + 2) * 4 ** 2 // 5 % 3

# Step-by-step:

# (3 + 2) = 5

# 4 ** 2 = 16

# 5 * 16 = 80

# 80 // 5 = 16

# 16 % 3 = 1

print(result) # 1

Data Types
Data types define the nature of data a variable can hold. Python is dynamically typed,
meaning the type is assigned at runtime.

1. Numbers

Python supports:

• int: Integer numbers (e.g., 10, -3)

• float: Decimal numbers (e.g., 3.14, -0.5)

• complex: Numbers with real and imaginary parts (e.g., 3 + 4j)

a = 10 # int

b = 3.14 # float

c = 2 + 3j # complex

2. Boolean
• Stores only two values: True or False.

• Mainly used in conditional statements and logical operations.

is_valid = True

3. Strings

• A sequence of characters.

• Can be enclosed in single ' ', double " ", or triple quotes ''' '''.

• Triple quotes are used for multiline strings.

s1 = 'Hello'

s2 = "World"

s3 = '''This is

a multiline

string'''

4️. List

• An ordered, mutable (changeable) collection of elements.

• Defined using square brackets [ ].

• Can contain mixed data types.

my_list = [1, 2.5, 'Python', True]

5. Tuple

• An ordered, immutable (unchangeable) collection.

• Defined using parentheses ( ).

my_tuple = (10, 'apple', 3.14)

6️. Dictionary

• An unordered collection of key: value pairs.

• Keys must be unique.

• Defined using curly braces {}.

my_dict = {1: 'Apple', 2: 'Banana', 3: 10.5}


7️. None

• Represents the absence of a value.

• Commonly used for initializing variables or returning from functions that don’t return
anything.

x = None

Indentation
• Indentation is mandatory in Python to define blocks of code.

• It improves readability and replaces the need for {} braces like in other languages.

Rules of Indentation:

• A block of code is defined by the same level of indentation.

• Four spaces per indentation level are standard (tabs should be avoided).

• Improper indentation causes IndentationError.

if True:

print("Block 1") # Correct indentation

if 5 > 2:

print("Block 2") # Nested block

Comments
• Comments are non-executable lines meant to explain code.

• Help in understanding complex logic or purpose behind the code.

• Python supports:

o Single-line comments using #

o Multi-line comments using triple quotes ''' ''' or """ """

# This is a single-line comment

'''
This is a

multiline comment

explaining the code

'''

Best Practices:

• Use comments to explain why something is done.

• Avoid explaining the obvious (e.g., i = i + 1 # increment i is unnecessary).

String Formatting Methods


1. % Operator Formatting (Old Style)

• This is C-style string formatting using the % operator.

• You use placeholders like %s, %d, %f, etc., inside the string.

Syntax:

"string % placeholder" % (values)

Common Placeholders:

Placeholder Meaning

%s String

%d Integer (Decimal)

%f Floating-point number

%x / %X Hexadecimal

%o Octal number

name = "Alice"

age = 23

print("Name: %s, Age: %d" % (name, age))

# Output: Name: Alice, Age: 23


2. str.format() Method (New Style)

• Introduced in Python 2.6️ and 3.0.

• More powerful and flexible than % formatting.

• Uses {} as placeholders and .format() method.

Syntax:

"string with {} and {}".format(values)

Positional and Keyword Arguments:

print("Hello {}, you are {} years old".format("Alice", 23))

# Output: Hello Alice, you are 23 years old

print("Hello {0}, you are {1} years old".format("Alice", 23))

# Output: Hello Alice, you are 23 years old

print("Hello {name}, you are {age} years old".format(name="Alice", age=23))

# Output: Hello Alice, you are 23 years old

Formatting numbers:

result = 5/3

print("Result: {:.2f}".format(result))

# Output: Result: 1.67

• :.2f → 2 decimal places

3. f-Strings (Literal String Interpolation) → Modern Way (Python 3.6️+)

• Fastest and cleanest way.

• You directly embed variables inside {} using a string prefixed with f.

Syntax:

f"string with {variable}"

name = "Alice"

age = 23

print(f"Name: {name}, Age: {age}")


# Output: Name: Alice, Age: 23

f-Strings with expressions:

a=5

b = 10

print(f"Sum is {a+b}")

# Output: Sum is 15

f-Strings with formatting:

pi = 3.14159

print(f"Value of pi: {pi:.2f}")

# Output: Value of pi: 3.14

4️. Template Strings (from string module)

• Secure and safe for user inputs (avoids code injection attacks).

• Useful in situations like web development where strings come from external
sources.

Import it first:

from string import Template

Syntax:

Template('Hello, $name').substitute(name='Alice')

from string import Template

temp = Template('Hello, $name!')

message = temp.substitute(name='Alice')

print(message)

# Output: Hello, Alice!

Note:

• Use $$ to escape a dollar sign:

Template('$$ is the symbol for dollars.').substitute()


# Output: $ is the symbol for dollars.

Parameters of format() Method

1. Positional Arguments

• These are arguments passed without any keywords.

• Their order determines which placeholder they fill.

• Indexing starts from 0.

➤ 1: Simple Positional Formatting

print("{} is a good college".format("RNSIT"))

# Output: RNSIT is a good college

➤ 2: Using Indexes

print("{1} department {0} college".format("RNSIT", "EC"))

# Output: EC department RNSIT college

➤ 3: Without Indexes (Automatically ordered)

print("Every {} should learn {} {}".format("student", "Python", "Programming"))

# Output: Every student should learn Python Programming

➤ 4️: Reversing Order with Indexes

print("Every {2} needs {1} and {0}".format("logic", "practice", "programmer"))

# Output: Every programmer needs practice and logic

2. Keyword Arguments

• These are arguments passed as key=value.

• You can use these keys as placeholders.

print("Department {0}, Section {section}".format("CSE", section="B"))

# Output: Department CSE, Section B

Type
Type Conversion in Python
Python is a dynamically typed language, which means you don’t need to declare a
variable’s type before using it. However, there are situations where explicit type
conversion is necessary.

This is where type conversion functions come in handy. Python provides built-in
functions to convert values from one data type to another.

Common Type Conversion Functions

Function Description

int() Converts a value to an integer

float() Converts a value to a floating-point number

str() Converts a value to a string

int() Function

• Used to convert strings or float values to integers.

• It does not round a float, it simply truncates (removes) the decimal part.

print(int('32')) # Output: 32

print(int(3.9999)) # Output: 3 (decimal chopped)

print(int(-2.3)) # Output: -2

Invalid Case:

print(int('Hello'))

# Output: ValueError: invalid literal for int() with base 10: 'Hello'

float() Function

• Converts integers or valid numeric strings to a floating-point number.

print(float(32)) # Output: 32.0

print(float('3.124')) # Output: 3.124

str() Function

• Converts numbers (int or float) into a string format.


• Very useful when concatenating numbers with text.

print(str(32)) # Output: '32'

print(str(3.124)) # Output: '3.124'

a) Implicit Type Conversion

• Performed automatically by Python.

• Happens when Python converts smaller data types to larger ones to avoid data loss.

• No programmer intervention needed.

a=5 # int

b = 2.0 # float

c = a + b # int + float → float

print(c) # Output: 7.0

print(type(c)) # Output: <class 'float'>

Explanation:
Here, Python automatically converted int (5) to float (5.0) to match 2.0.

b) Explicit Type Conversion (Type Casting)

• Done manually by the programmer.

• Use built-in functions to convert data types.

Common Casting Functions:

Function Description

int() Converts to Integer

float() Converts to Floating Point

str() Converts to String

bool() Converts to Boolean

list() Converts to List


Function Description

tuple() Converts to Tuple

set() Converts to Set

x = "123"

y = int(x) # string to integer

print(y) # Output: 123

print(type(y)) # Output: <class 'int'>

The type() Function


Purpose:

The type() function returns the type/class of the object passed to it. It is often used for
debugging and verification purposes.

Syntax:

type(variable_or_value)

x = 10

print(type(x)) # Output: <class 'int'>

y = 3.14

print(type(y)) # Output: <class 'float'>

z = "Hello"

print(type(z)) # Output: <class 'str'>

is Operator in Python
Python provides two types of comparisons:

• == operator → checks for value equality (are the contents same?)

• is operator → checks for identity (are both variables pointing to the same memory
location?)
Identity vs. Equivalence

Concept Description

Identical Objects Refer to the same object in memory (a is b → True)

Equivalent Objects Have the same value but may be different objects

1: Identical Objects (Strings are interned)

a = 'banana'

b = 'banana'

print(a is b) # Output: True

2: Equivalent but Not Identical

s1 = input("Enter a string: ")

s2 = input("Enter a string: ")

print(s1 is s2) # Output: False (Different memory)

print(s1 == s2) # Output: True (Same content)

Even if two strings have the same value from input, they are stored in different memory
locations, so is returns False, but == returns True.

Control Flow Statements in Python


1. if Decision Control Flow Statement
The if statement is the simplest form of decision-making in Python. It is used to execute a
block of code only if a specified condition is true.

Syntax:

if condition:

# block of code

Explanation:

• The condition is a Boolean expression that evaluates to either True or False.


• If the condition is True, the indented block under if is executed.

• If False, the block is skipped.

x = 10

if x > 5:

print("x is greater than 5")

Notes:

• Python uses indentation to define blocks of code, not curly braces {}.

• If the indentation is wrong, Python raises an IndentationError.

2. if…else Decision Statement


The if…else statement is used for alternative execution: when you want one block to run
if the condition is true, and a different block to run if it's false.

Syntax:

if condition:

# block A (executed if condition is true)

else:

# block B (executed if condition is false)

x=4

if x % 2 == 0:

print("Even")

else:

print("Odd")

Explanation:

• Python evaluates the condition.

• If true → executes the if block.

• Else → executes the else block.

Use Case:
Useful when you need to choose between two mutually exclusive options, like checking
user authentication, eligibility, etc.

3. if…elif…else – Chained Conditionals


When there are multiple conditions to evaluate, Python provides the if…elif…else
structure, known as chained conditional statements.

Syntax:

if condition1:

# block A

elif condition2:

# block B

elif condition3:

# block C

else:

# default block

marks = 75

if marks >= 90:

print("Grade A")

elif marks >= 75:

print("Grade B")

elif marks >= 60:

print("Grade C")

else:

print("Grade D")

Explanation:

• Python checks each condition top to bottom.


• As soon as it finds a True condition, it executes that block and skips the rest.

Notes:

• Only one block will be executed.

• elif can be repeated multiple times.

• else is optional, but recommended to catch unmatched cases.

4️. Nested if Statements


Nested if statements are conditional statements written inside other conditional
blocks. They allow more complex decision trees.

Syntax:

if condition1:

if condition2:

# inner block

else:

# inner else

else:

# outer else

x = 20

y=5

if x > 10:

if y > 0:

print("x > 10 and y > 0")

else:

print("x > 10 but y <= 0")

else:

print("x <= 10")

Notes:
• Too much nesting can make code hard to read.

• Prefer combining conditions using logical operators like and, or.

Iteration (Looping Statements)


Iteration refers to the process of repeating a sequence of instructions until a specific
condition is met.

It is a fundamental concept in programming, enabling developers to execute a block of


code multiple times efficiently.

Iteration, combined with conditional execution (e.g., if statements), forms the backbone of
algorithm design. Loops are used to automate repetitive tasks, process collections of data,
or solve problems that require repeated computations.

There are two primary types of loops in most programming languages:

1. Indefinite loops (e.g., while loops): Used when the number of iterations is unknown
in advance.

2. Definite loops (e.g., for loops): Used when the number of iterations is known or can
be determined.

1. Definite Loops

A definite loop is a loop that executes a known, fixed number of times.

• The number of iterations is known before the loop starts.

• Typically achieved using a for loop.

for i in range(5):

print(i)

• Here, the loop will run exactly 5 times (from 0 to 4).

• range(5) makes it a definite loop.

2. Indefinite Loops

An indefinite loop is a loop that keeps running until a certain condition becomes false.

• The number of iterations is not known in advance.


• Typically achieved using a while loop.

n=5

while n > 0:

print(n)

n -= 1

• Here, the loop continues until n becomes 0.

• We don't know in advance exactly how many steps it will take without examining
the code.

3. Finite Loops

A finite loop is any loop (definite or indefinite) that eventually terminates after
completing a certain number of iterations.

• The loop has a clear stopping condition.

Both examples below are finite:

Definite Finite:

for i in range(3):

print(i)

(Stops after 3 iterations.)

Indefinite Finite:

password = ""

while password != "python123":

password = input("Enter password: ")

print("Access granted!")

(Loop stops when correct password is entered.)

4️. Infinite Loops

An infinite loop is a loop that never ends unless forcibly stopped (manually or with a
break).

• The loop's condition always remains True.


• Can happen accidentally or intentionally.

while True:

print("This will run forever!")

• Here, True is always True, so the loop never ends.

n=5

while n > 0:

print(n)

# Missing: n -= 1 → So, n stays 5 forever → Infinite loop

Summary Table

Term Description Example Loop Type

Definite Loop Known number of iterations for loop over range

Indefinite Loop Unknown number of iterations while loop with condition

Finite Loop Loop that eventually stops Proper for or while

Infinite Loop Loop that never ends without interruption

While Loop
What is a While Loop?

A while loop is an indefinite loop that repeatedly executes a block of code as long as a
specified condition evaluates to True.

It is ideal for situations where the number of iterations is not predetermined, such as
waiting for user input, processing data until a certain condition is met, or performing
calculations until convergence.

Syntax of While Loop

while condition:

# Body of the loop

# Statements to be executed

• while: A keyword that initiates the loop.


• condition: A Boolean expression (e.g., x < 10) that is evaluated before each
iteration.

• Body: An indented block of code that executes if the condition is True.

Flow of Execution

1. The condition is evaluated.

2. If the condition is True, the body of the loop is executed, and the program returns to
step 1.

3. If the condition is False, the loop terminates, and the program proceeds to the next
statement after the loop.

Key Components

• Iteration Variable (Counter Variable): A variable that controls the loop’s execution
by changing its value in each iteration. For , a counter incremented inside the loop.

• Condition Update: The iteration variable must be updated within the loop to
eventually make the condition False. Failure to update the variable can lead to an
infinite loop.

1: Printing Numbers 1 to 5

i=1

while i <= 5:

print(i)

i=i+1

Infinite Loops

An infinite loop occurs when the condition never becomes False, causing the loop to run
indefinitely. This can happen due to:

• A condition that is always True (e.g., while True:).

• Failure to update the iteration variable.

• Logical errors in the condition.

of an Infinite Loop:

i=1
while i <= 5:

print(i)

# Missing i = i + 1

• Here, i remains 1, and the condition i <= 5 is always True, causing the loop to print 1
indefinitely.

Avoiding Infinite Loops

• Always ensure the iteration variable is updated to eventually make the condition
False.

• Use debugging techniques (e.g., print statements) to trace the variable’s value.

• Use break statements to exit the loop under specific conditions (covered later).

Break
The break statement is used to exit a loop prematurely, regardless of whether the loop’s
condition is still True. It is commonly used in while and for loops to provide an alternative
exit condition, especially in indefinite loops or when a specific event occurs.

Syntax

while condition:

# Statements

if some_condition:

break

# More statements

How Break Works

• When the break statement is executed, the program immediately exits the
innermost loop (while or for) and proceeds to the first statement after the loop.

• Any remaining iterations are skipped.

1: Limiting Input to 10 Numbers

count = 0

while count < 10:


num = int(input("Enter a number (negative to stop): "))

if num < 0:

break

print("You entered:", num)

count += 1

print("Loop ended.")

Explanation:

• The loop allows up to 10 iterations (count < 10).

• If the user enters a negative number, break is executed, terminating the loop early.

2: Exiting on “done”

while True:

user_input = input("Enter something (type 'done' to stop): ")

if user_input == "done":

break

print("You entered:", user_input)

print("Finished!")

Explanation:

• The loop uses while True, making it infinite by default.

• The break statement exits the loop when the user types “done”.

Key Points About Break

• Scope: break only exits the innermost loop. In nested loops, outer loops continue
running.

• Use Case: Ideal for sentinel-controlled loops (e.g., stopping when a specific input is
received).

• Caution: Overusing break can make code harder to read. Use it when the exit
condition is complex or not easily incorporated into the loop’s main condition.

Common Pitfalls
• Forgetting to include the break condition, leading to an infinite loop.

• Placing break in a way that skips important cleanup code in the loop.

Continue
The continue statement is used to skip the rest of the current iteration in a loop and
move to the next iteration. Unlike break, which exits the loop entirely, continue allows the
loop to keep running but bypasses certain iterations based on a condition.

Syntax

while condition:

# Statements

if some_condition:

continue

# More statements

How Continue Works

• When continue is executed, the program skips the remaining statements in the
current iteration and returns to the loop’s condition check (for while loops) or the
next item (for for loops).

• The loop continues until its condition becomes False or a break is encountered.

1: Skipping Lines Starting with #

while True:

line = input("Enter a line (type 'done' to stop): ")

if line == "done":

break

if line.startswith("#"):

continue

print("Line:", line)

print("Finished!")

2: Printing Only Even Numbers


i=0

while i < 10:

i += 1

if i % 2 != 0: # Skip odd numbers

continue

print(i)

Explanation:

• The loop iterates from i = 1 to i = 10.

• If i is odd (i % 2 != 0), continue skips the print statement.

• Only even numbers are printed.

Key Points About Continue

• Scope: Like break, continue affects only the innermost loop.

• Use Case: Useful for filtering out specific cases (e.g., skipping invalid inputs or
comments).

• Caution: Ensure continue doesn’t skip critical updates to the iteration variable, as
this could cause an infinite loop.

Common Pitfalls

• Accidentally skipping the update of the iteration variable, leading to an infinite loop.

• Overusing continue, which can make the loop logic harder to follow.

For Loop
A for loop is a definite loop used to iterate over a known set of items, such as a list, tuple,
string, or range of numbers. It is ideal when the number of iterations is predetermined or
can be derived from the data structure being processed.

Syntax

There are two common forms of the for loop:

1. For Loop with Sequence (e.g., list, string):

for variable in sequence:


# Body of the loop

# Statements to be executed

2. For Loop with range():

for variable in range(start, end, step):

# Body of the loop

# Statements to be executed

Key Components

• variable: The iteration variable that takes on each value in the sequence or range.

• sequence: A collection (e.g., list, tuple, string) or an iterable object (e.g., range()).

• Body: The indented block of code executed for each value of the iteration variable.

For Loop with Sequence

This form iterates over elements in a collection, such as a list or string.

1: Iterating Over a List

friends = ["Alice", "Bob", "Charlie"]

for name in friends:

print("Hello,", name)

2: Iterating Over a String

for char in "Python":

print(char)

For Loop with range()

The range() function generates a sequence of numbers, making it ideal for iterating a
specific number of times.

Syntax of range():

range(start, end, step)

• start: The starting value (inclusive, default is 0).

• end: The ending value (exclusive).


• step: The increment/decrement (default is 1, optional).

1: Printing Numbers 1 to 5

for i in range(1, 6):

print(i)

2: Printing Even Numbers from 2 to 10

for i in range(2, 11, 2):

print(i)

3: Counting Down from 5 to 1

for i in range(5, 0, -1):

print(i)

Key Points About For Loops

• Definite Nature: The number of iterations is determined by the length of the


sequence or range.

• Iteration Variable: Automatically updated to the next item in the sequence; no


manual update needed.

• Use Cases:

o Processing lists, tuples, or dictionaries.

o Performing a task a fixed number of times.

o Iterating over files or other iterables.

Using Break and Continue in For Loops

Both break and continue work in for loops similarly to while loops.

Break in For Loop

for i in range(1, 10):

if i == 5:

break

print(i)

: Continue in For Loop


for i in range(1, 6):

if i % 2 == 0:

continue

print(i)

Pass
• The pass statement in Python is a null operation.

• It is used when a statement is syntactically required, but no action is needed.

• Python will not throw an error when it encounters pass; it simply moves on.

Why do we need pass?

• To create empty blocks of code for future development.

• To avoid errors when a block must not be left empty.

• Useful as a placeholder for:

o Empty functions

o Empty classes

o Empty loops

o Empty conditionals

Syntax:

pass

• It is written as a single line.

Example 1: pass in an empty function

def future_function():

pass # I'll add the logic later

• Without pass, Python would raise an IndentationError because function bodies


can't be empty.

Example 2: pass in an if-else block


x = 10

if x > 0:

pass # To be implemented later

else:

print("Negative number")

• Here, pass acts as a placeholder until the if block is properly coded later.

Example 3: pass in a loop

for i in range(5):

pass # No operation inside the loop yet

• The loop runs, but does nothing during each iteration.

Difference between pass, continue, and break

Statement Purpose

pass Do nothing (null operation); just a placeholder.

continue Skip the current iteration and continue with the next iteration.

break Exit the loop immediately.

Functions
A function in Python is a sequence of instructions grouped together to perform a specific,
independent task.

Functions are essential for organizing code, making it reusable, modular, and easier to
maintain.

They allow programmers to avoid repeating code by defining a task once and calling it
multiple times as needed.

Key Features of Functions:

• Reusability: Write a function once and use it multiple times.

• Modularity: Break down complex programs into smaller, manageable tasks.


• Data Processing: Functions can accept input (arguments), process it, and return
output.

• Object Nature: In Python, functions are treated as objects, allowing flexibility (e.g.,
passing functions as arguments to other functions).

Types of Functions in Python:

1. Built-in Functions: Predefined functions provided by Python (e.g., max(), len(),


print()).

2. User-defined Functions: Custom functions created by the programmer to perform


specific tasks.

Built-in Functions
• Built-in functions are functions already defined by Python.

• These functions are ready to use at any point in the program without needing any
extra coding.

• They are designed to handle common programming tasks like:

o Displaying output

o Taking input

o Performing type conversion

o Doing mathematical calculations

o Managing sequences (lists, strings, etc.)

• Python’s standard library contains hundreds of such built-in functions.

• These functions are highly reliable, optimized, and error-free because they are
developed and tested by the creators of Python.

• Built-in functions increase productivity because you do not need to "reinvent the
wheel" every time you want to perform a basic task.

Common Examples of Built-in Functions:

Function Purpose

print() Displays output on screen


Function Purpose

input() Takes user input

len() Returns length of an object

type() Returns type of a variable

max(), min() Finds maximum or minimum value

sum() Adds all elements in an iterable

sorted() Sorts an iterable

print("Hello")

x = [1, 2, 3]

print(len(x)) # Output: 3

a=5

print(type(a)) # Output: <class 'int'>

Advantages of Built-in Functions:

• Time-saving: No need to create common logic.

• Reliable: Tested and error-free.

• Easy-to-use: Simple syntax for all programmers.

User-defined Functions
• User-defined functions are functions written by the programmer to perform
specific, customized tasks.

• When built-in functions are not enough, or you want to repeat a task many times
with different values, you create your own function.

• They allow breaking complex problems into small manageable parts.

• They increase code reusability — you can call the same function multiple times
without writing the same code again.

• In Python, functions are created using the def keyword, followed by:
o A function name (identifier)

o Optional parameters (inputs)

o A body of statements

o An optional return value

Syntax:

def function_name(parameters):

# statements

return value

Example 1: Simple function without parameters

def greet():

print("Good Morning!")

greet()

Example 2: Function with parameters

def add(a, b):

print(a + b)

add(2, 3)

Example 3: Function with return value

def square(n):

return n * n

print(square(4)) # Output: 16

Types of User-defined Functions:

Type Example

No arguments, no return greet()

With arguments, no return add(a, b)


Type Example

No arguments, with return Function that returns a value without input

With arguments and return square(n) returning value

Importance of User-defined Functions:

• Code Reuse: Write once, use many times.

• Clean Code: Split big programs into small functions.

• Easier Maintenance: Update one function without changing the whole program.

• Easy Debugging: Track errors easily inside small blocks.

Commonly Used Modules


Python provides modules like math and random that contain additional functions for
specific tasks. These functions are not built-in and require importing the respective
module.

Math Module

The math module provides mathematical functions for advanced calculations. To use
these functions, you must import the module using:

import math

Key Math Functions:

Function Description

math.sqrt() math.sqrt(16) → 4.0 Returns the square root of a number.

math.sin() math.sin(0) → 0.0 Returns the sine of an angle (in radians).

math.cos() math.cos(0) → 1.0 Returns the cosine of an angle (in radians).

math.pi math.pi → 3.141592653589793 Constant representing the value of π.

math.log(2) → Returns the natural logarithm (base e) of a


math.log()
0.6931471805599453 number.

Program Using Math Module:

import math
# Calculate square root

print("Square root of 16:", math.sqrt(16)) # Output: 4.0

# Trigonometric functions

print("Sine of 0 radians:", math.sin(0)) # Output: 0.0

print("Cosine of 0 radians:", math.cos(0)) # Output: 1.0

# Constants

print("Value of pi:", math.pi) # Output: 3.141592653589793

# Logarithm

print("Natural log of 2:", math.log(2)) # Output: 0.6931471805599453

Random Module

The random module provides functions to generate pseudo-random numbers, which are
useful for applications like games, simulations, and testing.

Key Random Functions:

Function Description

Returns a random float


random.random() random.random() → 0.723942837 between 0.0 and 1.0
(excluding 1.0).

Returns a random integer


random.randint(low, high) random.randint(1, 10) → 7 between low and high
(inclusive).

random.choice(['apple', 'banana', Returns a random element


random.choice(sequence)
'orange']) → 'banana' from a sequence.

Program Using Random Module:

import random

# Generate 5 random floats between 0.0 and 1.0

print("Random floats:")

for i in range(5):
print(random.random())

# Generate a random integer between 1 and 10

print("Random integer:", random.randint(1, 10))

# Choose a random element from a list

fruits = ['apple', 'banana', 'orange']

print("Random fruit:", random.choice(fruits))

Function Calls
What is Function Calling?

• Function calling means executing or invoking a function that has been defined
earlier.

• When a function is called:

1. The program jumps to the function’s code.

2. Executes the statements inside the function.

3. Returns back to the point where it was called.

How to Call a Function?

• You call a function by writing its name followed by parentheses ().

• If the function requires arguments, pass the values inside parentheses.

Syntax:

function_name(arguments)

• function_name: Name of the function to call.

• arguments: Values passed to the function (if any).

Example 1: Calling a function without arguments

def greet():

print("Hello, Welcome!")

# Calling the function

greet()
Example 2: Calling a function with arguments

def add(a, b):

print(a + b)

# Calling the function with values

add(2, 3)

Important Points:

• Order Matters: Arguments must match the order and number expected by the
function.

• Return Values: If the function returns a value, you can store it in a variable.

def square(x):

return x * x

result = square(4) # Calling and storing the result

print(result)

Types of Function Calling:

Type Description Example

Without Arguments No input given greet()

With Arguments Input values given add(2, 3)

With Return Value Function sends back a value square(5)

Without Return Value Function just performs an action print_message()

Why is Function Calling Important?

• Reusability: You can call the same function multiple times without rewriting the
code.

• Code Structure: Keeps the code organized and modular.

• Efficiency: Reduces repetition and helps in easy debugging.

• Flexibility: Functions can be called with different inputs to perform the same task
differently.
Return Statement and Void Functions in Python
The return Statement

What is the return Statement?

• In Python, the return statement is used inside a function to:

o Send a value back to the place where the function was called.

o Exit the function immediately once the return is executed.

• Without return, a function will perform actions but won't give any output back.

Syntax:

def function_name(parameters):

# code

return value

• value can be:

o A number

o A string

o A list, dictionary, tuple, etc.

o Or nothing (just return without anything)

Example 1: Returning a single value

def square(x):

return x * x

result = square(5)

print(result)

Example 2: Returning multiple values

def calculate(a, b):

return a+b, a-b


x, y = calculate(10, 5)

print("Sum:", x)

print("Difference:", y)

Example 3: Return without any value

def greet():

print("Hello!")

return

greet()

Important Points about return:

• Stops the function execution immediately.

• Optional: If you don't use return, Python automatically returns None.

• If multiple return statements are there, only the first one that is hit gets executed.

Void Functions

• A Void Function is a function that does NOT return any value to the caller.

• It performs some task (like printing output) but returns None by default.

Characteristics of Void Functions:

• No return value (or returns just return without value).

• Their main job is to cause an effect, display something, or update something —


not to calculate and give back results.

• After execution, Python automatically assigns them a return value of None.

Example of a Void Function:

def display_message():

print("Python is fun!")

display_message()

Checking what a void function returns:

def hello():
print("Hello World")

result = hello()

print(result)

Scope and Lifetime of Variables


The scope of a variable determines the portion of a program where the variable can be
accessed. In Python, variables are not accessible everywhere in a program; their
accessibility depends on where they are declared. Python has two primary types of variable
scopes:

• Global Variables: Variables defined outside any function or block, accessible


throughout the entire program, including inside functions (unless shadowed by a
local variable).

• Local Variables: Variables defined inside a function, accessible only within that
function's body.

1.2 Lifetime of Variables

The lifetime of a variable is the duration for which it exists in memory:

• Global Variables: Exist for the entire duration of the program's execution.

• Local Variables: Exist only during the execution of the function in which they are
defined. They are created when the function is called and destroyed when the
function returns.

1.3 Global vs. Local Variables

• Global Variables: Declared outside functions, they can be accessed by all


functions in the program. However, to modify a global variable inside a function, the
global keyword must be used.

• Local Variables: Declared inside a function, they are confined to that function’s
scope. If a local variable has the same name as a global variable, the local variable
shadows (hides) the global one within the function.

Program: Global vs. Local Variables

x = 10 # Global variable
def my_function():

y = 5 # Local variable

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

print("Inside function, y:", y)

my_function()

print("Outside function, x:", x)

# print("Outside function, y:", y) # This will cause an error

Explanation:

x is a global variable (can be accessed inside and outside the function).

y is a local variable (only accessible inside my_function).

Trying to print y outside will cause an error, because local variables exist only inside
their function.

Functional Parameters
Python supports several types of function parameters to make functions flexible and
reusable. Below is a detailed explanation of all types of functional parameters, including
default parameters, keyword arguments, *args, **kwargs, and positional-only/parameters.

1. Positional Parameters

Parameters that are assigned values based solely on the order in which they are passed
during the function call.

• The order of arguments in the function call must exactly match the order in the
function definition.

• Most straightforward way to pass arguments.

• If the number of arguments or their order is wrong, an error occurs.

def greet(name, age):

print(f"Hello {name}, you are {age} years old.")

greet("Alice", 25)
Key Points:

• Position matters.

• Matching number and order is required.

2. Keyword Parameters

Parameters are explicitly passed by specifying the parameter name in the call.

In contrast to positional arguments, keyword arguments specify which parameter they


correspond to.

This improves readability and makes the purpose of each argument immediately clear.

They allow arguments to be passed out of order.

Keyword parameters must match the parameter names defined in the function.

In a function call, all positional arguments must come before any keyword
arguments.

• The caller specifies which value corresponds to which parameter.

• The order does not matter since each argument is linked by name.

• Improves code readability.

greet(age=25, name="Alice")

Key Points:

Reduces mistakes by ensuring arguments are passed correctly by name.

Especially important when a function has many parameters or parameters with similar
types.

• Order becomes irrelevant.

• Increases clarity and self-documentation of the code.

3. Default Parameters

Parameters that are given a default value during the function definition, allowing the caller
to omit them if desired.

Default parameters are defined by assigning a value in the function signature.

They make some function arguments optional for the caller.


If an argument is passed during the call, the default value is overridden.

Defaults must always be defined after non-default parameters.

Default values are evaluated once at function definition time, not at each call.

Mutable default values (like lists or dictionaries) can cause unexpected behavior if not
handled carefully.

• Default values are used if no argument is provided for those parameters.

• Helps to create functions with optional behavior.

def greet(name, age=18):

print(f"Hello {name}, you are {age} years old.")

greet("Bob")

Key Points:

Default parameters are shared across all function calls unless specifically overridden.

Use immutable objects (e.g., integers, strings, tuples) as default values whenever
possible to avoid side effects.

• Defaults must come after non-default parameters in the function signature.

• You can override defaults by explicitly providing a value.

4️. *Variable-Length Positional Parameters (args)

Allows a function to accept an arbitrary number of positional arguments.

Allows a function to accept an arbitrary number of positional arguments.

Useful when you do not know in advance how many arguments might be passed.

Inside the function, args is a tuple containing all extra positional arguments.

*args must appear after all normal positional parameters.

• Extra positional arguments are gathered into a tuple.

• Useful when the number of inputs is unknown beforehand.

Syntax:
An asterisk (*) before a parameter name in the function definition.

def add_numbers(*numbers):
print(numbers)

add_numbers(1, 2, 3)

Key Points:

You can still have named positional or keyword parameters along with *args.

If no extra arguments are passed, args will simply be an empty tuple.

• Internally, numbers is a tuple.

• Can iterate or process them like any tuple.

5. **Variable-Length Keyword Parameters (kwargs)

Allows a function to accept an arbitrary number of named arguments.

Allows a function to accept any number of keyword arguments not explicitly declared in
the function signature.

Inside the function, kwargs is a dictionary mapping parameter names to values.

**kwargs must appear after all positional parameters and *args.

• Extra keyword arguments are gathered into a dictionary.

• Useful for flexible interfaces or when handling many named arguments.

Syntax:
Two asterisks (**) before the parameter name in the function definition.

def print_info(**info):

print(info)

print_info(name="Alice", age=25)

Key Points:

Useful when building functions with flexible configurations.

Like *args, if no extra keyword arguments are passed, kwargs will be an empty dictionary.

**kwargs can also be unpacked when calling another function, forwarding arguments
dynamically.

• Internally, info is a dictionary.

• Keys are the parameter names; values are the corresponding arguments.
6️. Positional-Only Parameters (introduced in Python 3.8)

Parameters that must be passed by position only and cannot be passed using keyword
syntax.

• Indicated by placing a / symbol in the function signature.

• Prevents accidental naming of parameters in the call.

• Useful for API stability and optimization.

def greet(name, /, age):

print(f"Hello {name}, you are {age} years old.")

greet("Alice", 25) # Correct

# greet(name="Alice", age=25) # Incorrect

Key Points:

• Everything before / must be positional.

• Improves control over the function interface.

7️. Keyword-Only Parameters

Parameters that must be specified only by name, not by position.

• Introduced by placing a * symbol in the function signature.

• Increases code clarity, especially when functions have many optional parameters.

def greet(*, name, age):

print(f"Hello {name}, you are {age} years old.")

greet(name="Alice", age=25)

Key Points:

• All parameters following * must be passed as keywords.

• Helps prevent accidental wrong positional arguments.

8. Required Parameters and Required Arguments

Required parameters are those that must be provided with corresponding arguments
when calling the function.
Important Characteristics:

• Required parameters do not have default values.

• You must pass the correct number of required arguments during the function call.

• Missing or extra arguments cause an error at runtime.

Example of Required Parameters and Arguments

def greet(name, age): # name and age are required parameters

print(f"Hello {name}, you are {age} years old.")

greet("Alice", 25) # Correct usage

Why are Required Arguments Important?

• They ensure that the function has enough information to perform its task.

• Required parameters force the caller to think about what information is necessary.

• They make code safer by preventing incomplete function calls.

Key Rules for Required Parameters

Rule Description

No Defaults Required parameters are ones without any assigned default value.

Correct When calling the function, you must supply arguments in the correct order
Order unless using keyword arguments.

No Skipping You cannot skip required parameters when calling the function.

Type Python doesn't enforce types on required arguments (dynamic typing), but
Flexible logically they should be correct.

Command-Line Arguments in Python


• Definition:
Command-line arguments are parameters passed to a Python script directly from
the terminal (or command prompt) when executing the script.
• Usage:
They allow users to provide input without modifying the script's source code.

How Python Handles Command-Line Arguments

• The sys Module


Python provides a built-in module called sys that allows you to interact with the
system, including accessing command-line arguments.

• sys.argv
This is a list in Python that contains all command-line arguments passed to the
script.

How sys.argv Works

• sys.argv[0]: Name of the script (always present).

• sys.argv[1:]: Arguments passed by the user (if any).

import sys

print(sys.argv)

If you run the script as:

python myscript.py hello 42

Accessing Command-Line Arguments

You can directly access the arguments by their index.

import sys

if len(sys.argv) > 1:

print("First argument:", sys.argv[1])

Important Notes

• All arguments are read as strings.

o You need to convert them manually if you want numbers (using int(), float(),
etc.).

• Always check the length of sys.argv before accessing an index to avoid IndexError.

Example with Type Conversion

import sys
if len(sys.argv) != 3:

print("Usage: python script.py <name> <age>")

else:

name = sys.argv[1]

age = int(sys.argv[2])

print(f"Hello {name}, you are {age} years old.")

Why Use Command-Line Arguments?

• Automation: Allows scripts to be executed with varying inputs without modifying


code.

• Flexibility: Users can supply options/flags dynamically.

• Integration: Essential for creating tools and CLI applications.

Docstrings in Python
• Docstrings are special documentation strings written inside a function, class, or
module.

• They describe what the function/class/module does.

• They are written inside triple quotes (""" """ or ''' ''').

• They are the first statement after the def, class, or module declaration.

• Docstrings are accessible at runtime via the . __doc__ attribute.

Why Use Docstrings?

• To explain what your function/class/module does.

• To help other programmers (or your future self) understand your code.

• To automatically generate documentation using tools like help().

• To make code professional and readable.

Syntax

def function_name(parameters):
"""Summary line.

More description if needed.

"""

# Function body

Small Code Example

def add(a, b):

"""Add two numbers and return the result."""

return a + b

print(add(5, 3))

print(add.__doc__)

Example for Class

class Calculator:

"""A simple calculator class."""

def multiply(self, x, y):

"""Return the product of two numbers."""

return x * y

obj = Calculator()

print(obj.multiply(3, 4))

print(Calculator.__doc__)

print(obj.multiply.__doc__)

Important Points

• Use triple quotes even if the docstring is only one line.

• Keep the first line short and descriptive (summary line).

• You can add a more detailed explanation after a blank line if needed.

• It’s a good habit to always add docstrings for functions and classes.
PROGRAM
1. Find Area of Square, Rectangle, Circle

import math

def area_square(side):

return side * side

def area_rectangle(length, width):

return length * width

def area_circle(radius):

return math.pi * radius * radius

print(area_square(4))

print(area_rectangle(5, 3))

print(area_circle(7))

2. Add Two Numbers

def add(a, b):

return a + b

print(add(5, 7))

3. Tell if Number is Even or Not

def is_even(num):

return num % 2 == 0

print(is_even(10)) # True

print(is_even(7)) # False

4️. Check if Input Year is Leap or Not


def is_leap(year):

return (year % 4 == 0 and year % 100 != 0) or (year % 400 == 0)

print(is_leap(2024)) # True

print(is_leap(1900)) # False

5. Print This Pattern

12

123

1234

12345

for i in range(1, 6):

for j in range(1, i+1):

print(j, end="")

print()

6️. Take List of Numbers as Input and Return Unique Numbers

def unique_numbers(numbers):

return list(set(numbers))

nums = [1, 2, 2, 3, 4, 4, 5]

print(unique_numbers(nums))

7️. Fibonacci Series up to Nth Number

def fibonacci(n):

a, b = 0, 1

for _ in range(n):
print(a, end=" ")

a, b = b, a + b

fibonacci(7)

Find only nth Fibonacci number:

def nth_fibonacci(n):

a, b = 0, 1

for _ in range(n-1):

a, b = b, a + b

return a

print(nth_fibonacci(7))

8. Telephone Directory using Dictionary (Add, Delete, Search Contact)

directory = {}

def add_contact(name, number):

directory[name] = number

def delete_contact(name):

directory.pop(name, None)

def search_contact(name):

return directory.get(name, "Not found")

add_contact("Alice", "12345")

add_contact("Bob", "67890")

print(search_contact("Alice"))

delete_contact("Alice")

print(search_contact("Alice"))

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy