0% found this document useful (0 votes)
80 views53 pages

Python Basics Code Full Notes

Uploaded by

mevi.programs
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
Download as docx, pdf, or txt
0% found this document useful (0 votes)
80 views53 pages

Python Basics Code Full Notes

Uploaded by

mevi.programs
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1/ 53

Chapter 1: Starting with Python Basics

1. The First print Statement


The print() function in Python is used to display output on the screen.
It is one of the most fundamental and frequently used functions in
programming. Let's write the first Python program:

print("Hello, World!")
Output: Hello, World!

Explanation:
● The print keyword is a built-in Python function.

● "Hello, World!" is a string (text) that will be displayed when


the program runs.

2. Different Types of print Statements


Python's print() function can do much more than just display simple
text. Let's explore a few variations:
● Printing Multiple Values:

name = "Meghna"
age = 25
print("Name:", name, "Age:", age)

● Formatted Strings (f-strings):


name = "Meghna" age = 25
print(f"My name is {name} and I am {age} years old.")

● Using sep and end Parameters:


o sep (Separator): Defines how multiple values are separated.
o end: Defines what comes at the end of the print statement
(default is a newline).
print("Python", "is", "fun", sep="-", end=“!”)

Output:
Python-is-fun!

3. Understanding Variables
A variable is like a container that stores data values. In Python,
variables are created when you assign a value to them.

Example:

x = 10
name = "Meghna"
is_active = True

Explanation:
♦ x = 10: Assigns an integer value to x.

♦ name = "Megha": Assigns a string value to name.

♦ is_active = True: Assigns a Boolean value (True or False).

4. Printing Variables
You can combine variables with text in the print function:

Example:
name = "Meghna"
age = 25
printf("My name is {name} and I am {age} years old.")

Multiple Variables:

x, y, z = 10, 20, 30
print(f"x = {x}, y = {y}, z = {z}")
Chapter 2: Data Types in Python

1. What are Data Types?


In Python, every value belongs to a specific data type. Data types
define the kind of value a variable holds and the operations that can
be performed on it. Python provides various built-in data types to
handle different kinds of data.

2. Classification of Data Types

1. Numeric Types
◦ Integer (int)
◦ Floating-point (float)
◦ Complex (complex)
2. Text Type
◦ String (str)
3. Boolean Type
◦ Boolean (bool)
4. Sequence Types
◦ List (list)
◦ Tuple (tuple)
◦ Range (range)
5. Mapping Type
◦ Dictionary (dict)
6. Set Types
◦ Set (set)
◦ Frozen Set (frozenset)
7. Binary Types
◦ Bytes (bytes)
◦ Byte Array (bytearray)
◦ Memory View (memoryview)
3. Detailed Overview of Data Types

A. Numeric Types
1. Integer (int):
o Stores whole numbers without a decimal point.
o Example:
x = 10
y = -5
print(type(x)) # Output: <class 'int'>

2. Floating-point (float):
o Stores numbers with a decimal point.
o Example:
x = 10
y = -5
print(type(x)) # Output: <class 'int'>

3. Complex (complex):
o Stores numbers with a real and imaginary part.
o Example:
num = 4 + 3j
print(type(num)) # Output: <class 'complex'>

B. Text Type
1. String (str):
o A sequence of characters enclosed in single, double, or triple
quotes.
o Example:
name = "Python"
print(type(name)) # Output: <class 'str'>
Strings are immutable, meaning they cannot be changed
after creation.

C. Boolean Type
1. Boolean (bool):
o Represents one of two values: True or False.
o Example:
is_active = True
print(type(is_active)) # Output: <class 'bool'>

D. Sequence Types
1. List (list):
o An ordered collection of items, which can be modified
(mutable).
o Example:
fruits = ["apple", "banana", "cherry"]
print(type(fruits)) # Output: <class 'list'>

2. Tuple (tuple):
o An ordered collection of items, which cannot be modified
(immutable).
o Example:
person = {"name": "John", "age": 30}
print(type(person)) # Output: <class 'dict'>

E. Set Types
1. Set (set):
o An unordered collection of unique items.
o Example:
colors = {"red", "green", "blue"}
print(type(colors)) # Output: <class 'set'>
2. Frozen Set (frozenset):
o Like a set, but immutable.
o Example
frozen_colors = frozenset(["red", "green", "blue"])
print(type(frozen_colors)) # Output: <class 'frozenset'>

F. Binary Types
1. Bytes (bytes):
o Immutable sequence of bytes.
o Example
data = b"Python"
print(type(data)) # Output: <class 'bytes'>

2. Byte Array (bytearray):


o Mutable sequence of bytes.
o Example
data = bytearray(b"Python")
print(type(data)) # Output: <class 'bytearray'>

Memory View (memoryview):


o Provides a view of the memory of another object.
o Example
data = memoryview(b"Python")
print(type(data)) # Output: <class 'memoryview'>

4. Checking Data Types


Use the type() function to determine the type of a variable.
Example:
x = 10
print(type(x)) # Output: <class 'int'>

5. Converting Between Data Types


Python provides built-in functions to convert data types.
Examples:

1. Convert Integer to String:


x = 10
x_str = str(x)
print(type(x_str)) # Output: <class 'str'>

2. Convert String to Integer:


x = "25"
x_int = int(x)
print(type(x_int)) # Output: <class 'int'>

3. Convert List to Set:


fruits = ["apple", "banana", "apple"] unique_fruits = set(fruits)
print(unique_fruits) # Output: {'apple', 'banana'}

Hands-on Practice

1. Create variables of each type (int, float, str, bool, list, dict, etc.)
and print their types.
2. Write a program to convert a string of digits (e.g., "12345") into
an integer and add 10 to it.
3. Create a dictionary to store the names and ages of your friends.
Print the dictionary.

Lists, tuples, sets, and dictionaries in Python are considered both data
types and data structures, depending on the context. Here's a detailed
explanation to clarify this:

As Data Types
1. Definition: In Python, everything is an object, and every object
has a type. Lists, tuples, sets, and dictionaries are built-in data types
that represent collections of data.
2. Why Data Types?
◦ They define the kind of data being stored (e.g.,
ordered/unordered, mutable/ immutable).
◦ The type() function confirms their data type:

print(type([1, 2, 3])) # Output: <class 'list'> print(type((1, 2, 3))) #


Output: <class 'tuple'> print(type({1, 2, 3})) # Output: <class 'set'>
print(type({"key": "value"})) # Output: <class 'dict'>

◦ Python treats them as distinct, predefined data types.

As Data Structures
1. Definition: A data structure refers to how data is organized,
stored, and manipulated in memory. Lists, tuples, sets, and
dictionaries provide structures to store multiple elements efficiently.

2. Why Data Structures?


◦ They are used to solve real-world problems by organizing data
in meaningful ways.
◦ Example use cases:
▪ Lists: Store ordered collections, like a list of student names.
▪ Tuples: Represent fixed collections, like coordinates (x, y, z).
▪ Sets: Manage unique items, like tracking unique email IDs.
▪ Dictionaries: Map keys to values, like storing student records
with IDs as keys.

Summary
Concept Data Type Data Structure
Definition Predefined types in Python How data is organized for
(list, etc.). efficient use.
Focus Type/class of the object. Logical organization of data.
Example type([1, 2, 3]) returns <class Used to store, access, and
'list'>. manipulate data.

In essence:
• Technically: They are data types in Python because they belong
to predefined classes (list, tuple, etc.).

• Practically: They function as data structures when you use them


to organize and manage data.

Chapter 3: Understanding the input() Function in Python


In this chapter, we will explore the input() function, which is a
fundamental tool for making Python programs interactive. By the end
of this chapter, you will understand how to use input() effectively
and how to handle the data entered by users.

What is the input() Function?


The input() function allows a Python program to accept input from
the user during runtime. This makes programs dynamic and
interactive. The input provided by the user is always returned as a
string.

Syntax of input()
input(prompt)
• prompt: A string that is displayed on the screen to instruct or
request the user to provide input. This is optional.
• The function waits for the user to type something and press
Enter, then returns the entered value as a string.

Examples of Using input()


1. Basic Example

name = input("What is your name? ")


print("Hello, " + name + "!")

Output:
What is your name? Alice Hello, Alice!

Explanation: The program asks the user for their name and greets
them using the provided input.

2. Using Input Without a Prompt

value = input()
print("You entered:", value)
Output:

Python is fun!
You entered: Python is fun!
Explanation: If no prompt is given, the program still waits for the
user’s input.

Handling Numeric Input

Since the input() function returns a string, you need to convert it into
the desired numeric type (e.g., int, float) for mathematical operations.

Example: Converting Input to Integer

age = input("Enter your age: ")


age = int(age) # Convert the string to an integer print("Next year,
you will be", age + 1, "years old.")

Output:
Enter your age: 25
Next year, you will be 26 years old.

Example: Converting Input to Float

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


number = float(number)
print("Half of the number is", number / 2)

Output:

Enter a decimal number: 10.5 Half of the number is 5.25

Common Mistakes with input()


1. Forgetting to Convert Input

# Incorrect
num1 = input("Enter first number: ")
num2 = input("Enter second number: ")
print("The sum is:", num1 + num2)

Output:
Enter first number: 5
Enter second number: 10
The sum is: 510

Explanation:
The input values are strings, so the + operator concatenates them
instead of performing arithmetic addition.
Solution:

num1 = int(input("Enter first number: "))


num2 = int(input("Enter second number: "))
print("The sum is:", num1 + num2)
Exercises
1. Simple Input Program
Write a program that asks the user for their favorite color and
displays a message including their input.

2. Number Validation
Write a program that asks the user to enter a number and validates
the input. If the input is not a number, it should display an error
message.

3. Simple Calculator
Create a program that takes two numbers from the user and prints
their sum, difference, product, and quotient.

Chapter 4: Strings in Python

What is a String?
A string in Python is a sequence of characters enclosed within single
quotes ('), double quotes ("), or triple quotes (''' or """). Strings are one
of the most commonly used data types in Python and are immutable,
meaning their content cannot be changed once created.

Examples:
# Single-quoted string string1 = 'Hello, World!'

# Double-quoted string
string2 = "Python is awesome!"

# Triple-quoted string (useful for multi-line text)

string3 = '''This is
a multi-line string.'''
Creating Strings
Strings can be created using:
1. Single quotes ('example')
2. Double quotes ("example")
3. Triple quotes for multi-line strings ('''example''' or """example""")

Example:

single = 'Hello' double = "World"


multi_line = '''This is
a multi-line string.'''

Accessing Strings
You can access individual characters or slices of a string using
indexing and slicing.

Indexing:
Strings are indexed, starting from 0 for the first character and -1 for
the last character.
Example:

string = "Python"
print(string[0]) #
print(string[-1])
Output: P(first character)
Output: n(last character)

Use the slice operator: to extract a part of the string.


Syntax:
string[start:end:step]
• start: Starting index (inclusive).
• end: Ending index (exclusive).
• step: Step size (optional).
Example:

string = "Python"
print(string[0:4]) #
Output: Pyth (characters from index 0 to 3)
print(string[::2]) #
Output: Pto (every second character)

String Methods
Python provides several built-in methods to manipulate and interact
with strings. These methods do not modify the original string
(because strings are immutable) but return a new string.

Common String Methods:


1. len(): Returns the length of the string.

string = "Hello"
print(len(string))
# Output: 5

2. lower(): Converts all characters to lowercase.


string = "HELLO"
print(string.lower()) # Output: hello

3. upper(): Converts all characters to uppercase.


string = "hello"
print(string.upper()) # Output: HELLO

4. strip(): Removes leading and trailing whitespace.


string = " Hello "
print(string.strip()) # Output: Hello

5. replace(): Replaces a substring with another.


string = "Hello, World!"
print(string.replace("World", "Python")) # Output: Hello, Python!

6. split(): Splits a string into a list of substrings based on a


delimiter.
string = "apple,banana,cherry"
print(string.split(",")) # Output: ['apple', 'banana', 'cherry']

7. join(): Joins elements of a list into a string using a delimiter.

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


print(",".join(fruits)) # Output: apple,banana,cherry

8. find(): Returns the index of the first occurrence of a substring.

string = "Hello, World!"


print(string.find("World")) # Output: 7

9. startswith(): Checks if the string starts with a specified


substring.
string = "Python"
print(string.startswith("Py")) # Output: True

10. endswith(): Checks if the string ends with a specified substring.


string = "Python"
print(string.endswith("on")) # Output: True

11. isalpha(): Checks if the string contains only alphabetic


characters.
string = "Hello"
print(string.isalpha()) # Output: True

12. isdigit(): Checks if the string contains only digits.


string = "12345"
print(string.isdigit()) # Output: True

String Operations
Concatenation:
Joining two or more strings using the + operator.
str1 = "Hello" str2 = "World"
print(str1 + " " + str2) # Output: Hello World
Repetition:
Repeating a string using the * operator.
string = "Hello"
print(string * 3) # Output: HelloHelloHello

Membership:
Checking if a substring exists within a string using in and not in.
string = "Python"
print("Py" in string) # Output: True print("Java" not in string)
#Output: True

String Types
1. Empty String: A string with no characters.
empty = ""
print(empty)
# Output: (blank line)

2. Single-Line String: A single line of text.


single_line = "This is a single line."

3. Multi-Line String: Text spanning multiple lines using triple


quotes.
multi_line = """This is
a multi-line string

.””"

### Practice Exercise:

1. Create a string and print its length.


2. Convert a string to uppercase and lowercase.
3. Replace a word in a sentence with another word.
4. Check if a string starts and ends with certain characters.
5. Use f-strings to format a message containing variables.

Chapter 5: Operators in Python


In Python, operators are special symbols or keywords used to
perform operations on variables and values. Python supports a wide
range of operators, categorized by the types of operations they
perform.

Types of Operators:
1. Arithmetic Operators
2. Comparison (Relational) Operators
3. Logical Operators
4. Bitwise Operators
5. Assignment Operators
6. Membership Operators
7. Identity Operators

1. Arithmetic Operators
Arithmetic operators are used to perform mathematical operations.

Operator Description Example


+ Addition 5+3
- Subtraction
* Multiplication 6*7
/ Division
% Modulus (Remainder) 10 % 3
** Exponentiation 2 ** 3
// Floor Division 17 // 3

Example:

num1 = 15
num2 = 4
print("Addition:", num1 + num2) # Output: 19
print("Subtraction:", num1 - num2) # Output: 11
print("Multiplication:", num1 * num2) # Output: 60
print("Division:", num1 / num2) # Output: 3.75
print("Modulus:", num1 % num2) # Output: 3
print("Exponentiation:", num1 ** num2) # Output: 50625
print("Floor Division:", num1 // num2) # Output: 3

2. Comparison (Relational) Operators


Comparison operators compare two values and return a boolean
result (True or False).

Operator Description Example Output


== Equal to 5 == 5 TRUE
!= Not equal to 5 != 3 TRUE
> Greater than 10 > 5 TRUE
< Less than 5<3 FALSE
Greater than or
>= 7 >= 7 TRUE
equal to
<= Less than or equal to 4 <= 8 TRUE

Example:
x = 10
y = 20
print("x == y:", x == y) # False
print("x != y:", x != y) # True
print("x > y:", x > y) # False
print("x < y:", x < y) # True
print("x >= y:", x >= y) # False
print("x <= y:", x <= y) # True

3. Logical Operators
Logical operators are used to combine conditional statements.

Operator Description Example Output

Returns True if both


and True and False FALSE
conditions are True
Returns True if at least
or True or False TRUE
one condition is

not Reverses the logical state not True FALSE

Example:

x=5
y = 10
print((x > 2) and (y > 5)) # True
print((x > 6) or (y > 5)) # True
print(not(x > 2)) # False

4. Bitwise Operators
Bitwise operators work on binary numbers at the bit level.
Operator Description Example Output
& AND 5&3 1
` ` `5 OR `3 7
^ XOR 5^3 6
~ NOT ~5 -6
<< Left Shift 5 << 1 10
>> Right Shift 5 >> 1 2

Example:

a = 5 # 0b0101 b = 3 # 0b0011
print("AND:", a & b) # Output: 1
print("OR:", a | b) # Output: 7
print("XOR:", a ^ b) # Output: 6
print("NOT:", ~a) # Output: -6
print("Left Shift:", a << 1) # Output: 10
print("Right Shift:", a >> 1) # Output: 2

5. Assignment Operators

Assignment operators are used to assign values to variables.

Operato
Description Example Equivalent To
r
= Assigns value x=5 -
+= Add and assign x+=3 x=x + 3
-= Subtract and assign x-=3 x=x - 2
*= Multiply and assign x*=4 x=x * 4
/= Divide and assign x/=2 x=x / 2
%= Modulus and assign x%=3 x=x % 3
**= Exponent and assign x**=2 x=x **2
//= Floor divide and assign x//=3 x=x //3
Example:

x = 10
x += 5 # Equivalent to x = x + 5
print(x) # Output: 15

6. Membership Operators

Membership operators check for membership in a sequence (e.g.,


string, list, tuple).

Operator Description Example Output


in Returns True if found a' in 'apple' TRUE
not in Returns True if not found b' not in apple TRUE

Example:
my_list = [1, 2, 3, 4]
print(3 in my_list) # True
print(5 not in my_list) # True

7. Identity Operators
Identity operators compare memory locations of two objects.

Operator Description Example Output


is Returns True if same object x is y TRUE
is not Returns True if not same x is not y TRUE

Example:

a =b =[1, 2, 3]
c = [1, 2, 3,4]
print(a is b) # True
print(a is c) # False
print(a is not c)# True

Summary
This chapter introduces Python operators and their applications in
performing various operations. Operators are essential in
programming and are used across a variety of scenarios. By
mastering them, you’ll be able to write powerful and efficient Python
code!

Chapter 6: Conditional Statements in Python


Conditional statements are a fundamental concept in programming,
allowing a program to make decisions based on specific conditions.
Python offers several constructs to implement conditional logic in a
program.

6.1 What Are Conditional Statements?


Conditional statements are used to execute a block of code only if a
certain condition is met. They allow your program to react differently
depending on the input or situation.
In Python, the main conditional statements are:

• if
• else
• elif (short for "else if")

6.2 Syntax of Conditional Statements


The general syntax of conditional statements in Python is:

if condition1:
# Code block to execute if condition1 is true elif condition2:
# Code block to execute if condition2 is true else:
# Code block to execute if none of the conditions are
True
6.3 Understanding Conditions
Conditions in Python are usually comparisons or logical expressions
that evaluate to True or
False.
Examples of conditions:

• x > 5 (Checks if x is greater than 5)


• y == 10 (Checks if y is equal to 10)
• z != 0 (Checks if z is not equal to 0)
• a >= b and b < c (Checks multiple conditions with logical
operators)

6.4 Types of Conditional Statements


6.4.1 The if Statement
The if statement is used to test a condition. If the condition evaluates
to True, the indented code block under the if statement is executed.
Example:

age = 18
if age >= 18:
print("You are eligible to vote!")

6.4.2 The else Statement


The else statement provides an alternative block of code if the if
condition evaluates to
False.
Example:

age = 16
if age >= 18:
print("You are eligible to vote!") else:
print("You are not eligible to vote yet.")
6.4.3 The elif Statement

The elif statement allows for multiple conditions to be checked


sequentially. It is used when you need to test more than one
condition.

Example:

marks = 85
if marks >= 90:
print("Grade: A+")
elif marks >= 75:
print("Grade: A")
elif marks >= 60:
print("Grade: B")
else:
print("Grade: C")

6.5 Nested Conditional Statements


You can use one conditional statement inside another. This is called
nesting.

Example:

number = 10
if number > 0:
if number % 2 == 0:
print("The number is positive and even.")
else:
print("The number is positive but odd.")
else:
print("The number is not positive.")

6.6 Logical Operators in Conditions


Logical operators can combine multiple conditions in a single
statement.

• and: Returns True if both conditions are true.


• or: Returns True if at least one condition is true.
• not: Reverses the logical state of the condition.

Example:

age = 20
citizenship = "Indian"
if age >= 18 and citizenship == "Indian":
print("You are eligible to vote.")

6.7 The pass Statement in Conditional Statements


Sometimes, you may need a placeholder for a conditional block. The
pass statement does nothing and is used to avoid errors in empty
code blocks.

Example:

x = 10
if x > 0:
pass # Code to be written later

6.8 Practical Examples of Conditional Statements

Example 1: Checking Even or Odd

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


if number % 2 == 0:
print("The number is even.")
else:
print("The number is odd.")

Example 2: Simple Login System

username = input("Enter username: ")


password = input("Enter password: ")

if username == "admin" and password == "1234":


print("Login successful!")
else:
print("Invalid credentials!”)

Example 2: Grading System

marks = int(input("Enter your marks: "))


if marks >= 90:
print("Grade: A+")
elif marks >= 80:
print("Grade: A")
elif marks >= 70:
print("Grade: B")
elif marks >= 60:
print("Grade: C")
else:
print("Grade: F")

6.9 Common Mistakes in Conditional Statements


• Indentation Errors: Make sure all code blocks under a
conditional statement are indented properly.
• Logical Errors: Ensure conditions are logically sound.
• Using Assignment (=) Instead of Equality (==): Remember, = is
for assignment, while == is for comparison.
Example of Mistake:
# Incorrect
if x = 10: # This will cause a syntax error
print("x is 10")

# Correct
if x == 10:
print("x is 10")

Key Takeaways
• Conditional statements allow programs to make decisions based
on conditions.
• Use if for a single condition, else for alternative actions, and elif
for multiple conditions.
• Logical operators (and, or, not) help in combining conditions.
• Always test and debug your conditions to ensure logical
correctness.

Exercise:
1. Write a program to check whether a number is positive,
negative, or zero.
2. Create a program that asks for a user's age and prints whether
they are a child, teenager, adult, or senior citizen.

Chapter 7: Loops in Python


In programming, loops are used to execute a block of code repeatedly
as long as a specified condition is met. Python supports two primary
types of loops:

1. for Loop: Iterates over a sequence (e.g., list, tuple, string).


2. while Loop: Repeats as long as a condition is true.

This chapter explains both types in detail, including their syntax,


usage, and examples.

1. Why Use Loops?


Loops are used to:

• Avoid repetitive code.


• Perform operations on each item in a sequence.
• Simplify tasks like data processing, user input collection, or
iterations over files. For example:

# Without a loop print(1) print(2) print(3)

# With a loop
for i in range(1, 4):
print(i)

2. The for Loop


The for loop iterates over items in a sequence (list, tuple, string, etc.)
or uses the range()
function for numerical iterations.

Syntax:

for variable in sequence: # Code block


Example 1: Iterating Over a List

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


for fruit in fruits:
print(fruit)
Output:

apple
banana
cherry
Example 2: Using range()

for i in range(5):
print(i)
Output:

0
1
2
3
4

Example 3: Iterating Over Strings

for char in "hello":


print(char)
Output:
h
e
l
l
o

3. The while Loop


The while loop runs as long as its condition is true. It is suitable for
situations where the number of iterations is not predetermined.

Syntax:

while condition: # Code block


Example 1: Basic Usage

counter = 0
while counter < 5:
print(counter)
counter += 1
Output:

0
1
2
3
4

Example 2: User Input

password = "python123"
user_input = ""
while user_input != password:
user_input = input("Enter password: ")
print("Access granted!")

4. Nested Loops
Loops can be nested, meaning one loop is inside another.

Example:

for i in range(1, 4):


for j in range(1, 4):
print(f"i={i}, j={j}")
Output:

i=1, j=1 i=1, j=2 i=1, j=3 i=2, j=1


...

5. Control Statements
break
Exits the loop prematurely.

for i in range(10):
if i == 5:
break
print(i)
Output:

0
1
2
3
4

continue
Skips the current iteration and moves to the next one.

for i in range(5):
if i == 2:
continue
print(i)

Output:

0
1
3
4

pass
Does nothing; acts as a placeholder.
for i in range(3):
pass
Problem 1: Multiplication Table

Write a program to print the multiplication table of a given


number.

Problem 2: Sum of First N Numbers

Write a program to calculate the sum of the first n numbers using a


while loop.

Problem 3: Nested Loops for Patterns

Write a program to print a right-angled triangle pattern.

while True in Python


The while True loop in Python is a special type of infinite loop that
runs until it is explicitly stopped using a break statement or another
termination condition. This loop is useful in scenarios where you
need the program to keep running indefinitely until a specific event
occurs, like user input, a condition being met, or external interaction.

while True:
# Code block if condition:
break

How It Works
1. Condition Check: The while loop checks the condition, which in
this case is True. Since True is always True, the loop runs infinitely.
2. Execution of Code Block: The statements inside the loop are
executed repeatedly.
3. Termination: The loop is terminated when a break statement is
encountered or the program is stopped manually.
Example 1: Basic Infinite Loop

while True:
print("This will print endlessly unless we stop it.")

Example 2: User Input with Exit Condition

while True:
user_input = input("Enter something (type 'exit' to quit): ")
if user_input.lower() == "exit":
print("Exiting the loop. Goodbye!")
break
print(f"You entered: {user_input}")

Explanation:

• The loop keeps asking for user input until the user types exit.
• When exit is typed, the if condition becomes True, and the break
statement stops the loop.
Sample Output:

Enter something (type 'exit' to quit): Hello You entered: Hello


Enter something (type 'exit' to quit): Python You entered: Python
Enter something (type 'exit' to quit): exit Exiting the loop. Goodbye!

Example 3: Repeated Guessing Game


import random

# Generate a random number between 1 and 10 number_to_guess =


random.randint(1, 10)

while True:
guess = int(input("Guess the number (between 1 and 10): "))

if guess == number_to_guess:
print("Correct! You guessed the number!")
break
elif guess < number_to_guess:
print("Too low. Try again!")
else:
print("Too high. Try again!")

Explanation:

• The program generates a random number.


• The user is asked to guess the number repeatedly until they
guess correctly.
• When the correct number is guessed, the break statement ends
the loop.

Use Cases of while True


1. Menu-Driven Programs: Used to create menus that repeat until
the user exits.
2. Real-Time Systems: Continuously monitor inputs like sensors in
embedded systems or servers.
3. Error Handling Loops: Retry operations (e.g., asking for valid
input) until success.
4. Interactive Programs: Interactive games, chatbots, or command-
driven systems.

Precautions

1. Avoid Infinite Loops Without Exit Conditions: Ensure the loop


has a valid break
condition or user-interrupt mechanism.
2. Resource Consumption: Infinite loops consume CPU resources.
Use them judiciously.
3. Debugging Tips: If a while True loop doesn’t terminate as
expected, review the conditions leading to the break statement.

Practice Problems
1. Write a while True loop that asks for a password. Break out of
the loop when the correct password is entered.
2. Create a loop to simulate a basic ATM system where users can
check their balance, deposit, or withdraw money until they choose to
exit.

Chapter 8: Practice Problems and Libraries


Practice Problems
This chapter provides a variety of practice problems for loops,
conditional statements, strings, and operators, along with a detailed
explanation of Python libraries like math, random, and more.

Practice Problems
1. Guess the Number Game
Write a program where the user has to guess a randomly generated
number between 1 and 100. The program should provide feedback if
the guess is too high or too low and continue until the user guesses
correctly.

high or too low and continue until the user guesses correctly.

import random
number_to_guess = random.randint(1, 100)
while True:
guess = int(input("Guess the number (between 1 and
100):"))

if guess == number_to_guess:
print("Congratulations! You guessed the
correctnumber.")
break
elif guess < number_to_guess:
print("Too low! Try again.")
else:
print("Too high! Try again.")

Explanation:
• Uses the random library to generate a random number.
• Implements a while loop to repeatedly take guesses.
• Uses conditional statements to guide the user.

2. Palindrome Checker

Check if a given string is a palindrome.

def is_palindrome(string):
string = string.lower().replace(" ", "") # Normalize the string
return string == string[::-1]

user_input = input("Enter a string to check if it's a palindrome: ")


if is_palindrome(user_input):
print("It's a palindrome!")
else:
print("Not a palindrome.")

Explanation:
• Converts the string to lowercase and removes spaces.
• Compares the string with its reverse using slicing.
• Uses an if statement to check the condition.

3. Multiplication Table
Print the multiplication table of a number provided by the user.
number = int(input("Enter a number: "))
for i in range(1, 11):
print(f"{number} x {i} = {number * i}")

Explanation:
• Uses a for loop to iterate from 1 to 10.
• Prints the result of the multiplication using an f-string.

4. Calculate Factorial
Calculate the factorial of a given number using a while loop.

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


result = 1

while number > 1:


result *= number
number -= 1
print(f"Factorial: {result}")

Explanation:
• Multiplies the number by decrementing it in a while loop.
• Stops when the number becomes 1.

5. Count Vowels in a String

Count the number of vowels in a given string.

string = input("Enter a string: ")


vowels = "aeiouAEIOU"
count = 0
for char in string:
if char in vowels:
count += 1
print(f"Number of vowels: {count}")

Explanation:
• Uses a for loop to iterate through the string.
• Checks if each character is in the set of vowels.

Exploring Libraries
1. Math Library
The math library provides mathematical functions.
Example Functions:

import math

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

# Power
print(math.pow(2, 3)) # Output: 8.0

# Trigonometric functions
print(math.sin(math.pi / 2)) # Output: 1.0

# Rounding
print(math.floor(4.7)) # Output: 4 print(math.ceil(4.3)) #
Output: 5

2. Random Library
The random library is used to generate random numbers and choices.
Example Functions:

import random

# Random integer
print(random.randint(1, 10)) # Random number between 1 and
10

# Random choice
colors = ["red", "blue", "green"]
print(random.choice(colors))

# Shuffle a list
numbers = [1, 2, 3, 4, 5] random.shuffle(numbers)
print(numbers)

# Random float
print(random.uniform(1.5, 3.5)) # Random float between 1.5 and
3.5

3. Time Library
The time library is used to manage time-related tasks.
Example Functions:

import time

# Current time in seconds since epoch


print(time.time())
# Sleep for a few seconds
print("Start")
time.sleep(2)
print("End after 2 seconds")

# Current local time

print(time.ctime())

4. OS Library
The os library provides a way to interact with the operating system.
Example Functions:

import os

# Get current working directory


print(os.getcwd())

# List files in a directory


print(os.listdir("."))

# Create a new directory


os.mkdir("new_folder")

Practice Problems with Libraries


1. Generate Random Password
Generate a random password with letters, digits, and symbols.

import random
import string

length = int(input("Enter password length: "))

characters = string.ascii_letters + string.digits +


string.punctuation password = ''.join(random.choice(characters)
for _ in range(length))

print(f"Generated Password: {password}")

Chapter 9: Python Data Structures


Python provides a rich set of built-in data structures to manage and
organize data efficiently. In this chapter, we will explore lists, tuples,
sets, and dictionaries, along with their features, examples, and
methods. We'll also understand why certain data structures are
mutable, ordered, or unordered.

1. Lists
Definition:
A list is an ordered collection of items that can hold elements of any
data type. Lists are mutable, meaning their contents can be changed
after creation.

Characteristics:
• Ordered: Elements maintain their insertion order.
• Mutable: Elements can be added, modified, or removed.
• Heterogeneous: Can store elements of different data types.

Examples:

# Creating a list
fruits = ["apple", "banana", "cherry"]
print(fruits) # Output: ['apple', 'banana', 'cherry']

# Mixed data types


mixed = [1, "hello", 3.14]
print(mixed) # Output: [1, 'hello', 3.14]
Common Methods:

Needs to be table
Method Description Example
append(element) Adds an element to the end of the
fruits.append("orang
insert(index, element) Inserts an element at a specified index
fruits.insert(1, "grape")
pop([index]) Removes and returns an element at an index
fruits.pop(2)
remove(element) Removes the first occurrence of a
fruits.remove("banan
sort() Sorts the list in ascending order fruits.sort()
reverse() Reverses the list order fruits.reverse()
len() Returns the number of elements in len(fruits)

Why Mutable?
Lists are mutable because they allow in-place modifications, making
them suitable for scenarios where the data needs to change
dynamically.

2. Tuples
Definition:
A tuple is an ordered collection of items similar to a list, but tuples
are immutable.

Characteristics:
• Ordered: Elements maintain their insertion order.
• Immutable: Cannot modify elements after creation.
• Heterogeneous: Can store elements of different data types.

Examples:

# Creating a tuple
tuple_example = ("apple", "banana", "cherry")
print(tuple_example) # Output: ('apple', 'banana', 'cherry')

# Single-element tuple
single = ("hello",) # Comma is necessary for a single- element
tuple
print(single) # Output: ('hello',)
Common Methods:
Needs to be a table
Method Description Example
count(value) Counts occurrences of a value
tuple_example.count("apple")
index(value) Returns the index of the value
tuple_example.index("banana")

Why Immutable?
Tuples are immutable to ensure data integrity, making them suitable
for fixed collections of data such as coordinates or configuration
values.

3. Sets
Definition:

A set is an unordered collection of unique elements.

Characteristics:
• Unordered: Does not maintain any specific order.
• Mutable: Elements can be added or removed.
• Unique: No duplicate elements.

Examples:

# Creating a set
numbers = {1, 2, 3, 4, 5}
print(numbers) # Output: {1, 2, 3, 4, 5}

# Adding an element numbers.add(6)


print(numbers) # Output: {1, 2, 3, 4, 5, 6}
# Duplicate elements unique_set = {1, 1, 2, 2, 3}
print(unique_set) # Output: {1, 2, 3}
Common Methods:

Method Description Example


add(value) Adds a value to the set numbers.add(6)
Removes a value;
remove(value) raises an error if numbers.remove(3)
missing
Removes a value
discard(value) numbers.discard(7)
without raising
Returns a new set with
union(set2) numbers.union({6, 7})
all elements
Returns common
intersection(s et2) numbers.intersection({3,4})
elements between sets

Why Unordered?
Sets are unordered because they are optimized for fast lookups and
ensure uniqueness, making them ideal for membership tests.

4. Dictionaries
Definition:
A dictionary is an unordered collection of key-value pairs, where
each key is unique.

Characteristics:
• Unordered (Python < 3.7): Keys are not stored in any specific
order.
• Ordered (Python ≥ 3.7): Maintains insertion order.
• Mutable: Can add, modify, or delete key-value pairs.
• Unique Keys: Keys must be unique, but values can repeat.

Examples:
# Creating a dictionary
person = {"name": "John", "age": 30, "city": "New York"}
print(person) # Output: {'name': 'John', 'age': 30, 'city': 'New
York'}

# Accessing values print(person["name"]) # Output: John

# Adding a new key-value pair


person["job"] = "Engineer"
print(person) # Output: {'name': 'John', 'age': 30, 'city': 'New
York', 'job': 'Engineer'}

Common Methods:

Method Description Example


get(key) Returns the value for the given key person.get("age"
keys() Returns a list of all keys person.keys()
values() Returns a list of all values person.values()
items() Returns a list of key-value pairs person.items()
pop(key) Removes a key-value pair by key person.pop("age"

Why Mutable?
Dictionaries are mutable because they often store dynamic data that
may change during program execution.

Summary Table

Feature List Tuple Set Dictionary


Ordered Yes Yes No Yes (Python ≥ 3.7)
Mutable Yes No Yes Yes
Duplicate Allowed Allowed Not Keys: Not Allowed;
Values Allowed Values: Allowed
Heterogeneous Yes Yes Yes Yes

Conclusion
Understanding Python's built-in data structures is crucial for writing
efficient and readable code. By leveraging the unique features of lists,
tuples, sets, and dictionaries, you can solve various programming
problems effectively. Their characteristics—such as mutability, order,
and uniqueness—determine how and when to use them.

Advanced Examples Combining Data Structures and the


random Library
Here are some interesting programs that combine Python's data
structures with the random
library:

Example 1: Randomly Selecting Elements from a List

import random

# List of fruits
fruits = ["apple", "banana", "cherry", "date", "elderberry"]

# Select a random fruit


random_fruit = random.choice(fruits)
print(f"Random fruit: {random_fruit}")
# Shuffle the list
random.shuffle(fruits)
print(f"Shuffled fruits: {fruits}")

Example 2: Creating a Dictionary with Random Values


import random

# Keys are letters, values are random integers


random_dict = {chr(i): random.randint(1, 100) for i in range(65,
71)} # A to F
print("Random dictionary:", random_dict)

Example 3: Using a Set to Find Unique Random Numbers

import random

# Generate a set of unique random numbers unique_numbers =


set()
while len(unique_numbers) < 5:
unique_numbers.add(random.randint(1, 10))
print(f"Unique random numbers: {unique_numbers}")

Example 4: Nested Data Structures with Random Values

import random

# Create a nested dictionary

nested_dict = {
f"list_{i}": [random.randint(1, 10) for _ in range(5)] for i in
range(3)
}

print("Nested dictionary with random values:")


for key, value in nested_dict.items():
print(f"{key}: {value}")

Example 5: Simulating a Deck of Cards


import random

# Create a deck of cards


suits = ["Hearts", "Diamonds", "Clubs", "Spades"] values = ["2",
"3", "4", "5", "6", "7", "8", "9", "10","Jack", "Queen", "King", "Ace"]
deck = [f"{value} of {suit}" for suit in suits for value in values]

# Shuffle the deck random.shuffle(deck)

# Draw 5 cards
hand = [deck.pop() for _ in range(5)] print("Your hand:")
for card in hand:
print(card)

Example 6: Grouping Randomly Generated Numbers

import random

# Generate random numbers and group them into even and odd
numbers = [random.randint(1, 50) for _ in range(20)]

even_numbers = [num for num in numbers if num % 2 == 0]


odd_numbers = [num for num in numbers if num % 2 != 0]

print(f"Numbers: {numbers}")
print(f"Even numbers: {even_numbers}")
print(f"Odd numbers: {odd_numbers}")
These examples highlight the versatility of Python's data structures
and their seamless integration
with libraries like random. Feel free to modify and expand upon
them!

Chapter 10: Python Functions


Functions are reusable blocks of code that perform a specific task.
They help organize code, improve readability, and avoid
redundancy.

1. What is a Function?
A function is a block of code that runs only when it is called.
Functions allow us to pass data, known as parameters, and return
data as a result.

Syntax:

def function_name(parameters): # Code block


return value
Example:

def greet(name):
return f"Hello, {name}!"

# Calling the function greeting = greet("Alice")


print(greeting) # Output: Hello, Alice!

2. Types of Functions
2.1 Built-in Functions
Python comes with many built-in functions, such as print(), len(),
sum(), etc. Example:

numbers = [1, 2, 3, 4, 5]
print(len(numbers)) # Output: 5
print(sum(numbers)) # Output: 15

2.2 User-defined Functions


These are functions you define yourself to perform specific tasks.
Example:
def add_numbers(a, b):
return a + b

result = add_numbers(3, 7)
print(result) # Output: 10

2.3 Anonymous (Lambda) Functions


Lambda functions are small, one-line functions defined without a
name.
Syntax:
lambda arguments: expression
Example:

square = lambda x: x ** 2
print(square(5)) # Output: 25

3. Function Arguments
Functions can accept arguments (inputs) to work with.

3.1 Positional Arguments


Arguments are matched to parameters based on their order. Example:
def describe_person(name, age):
print(f"{name} is {age} years old.")

describe_person("Alice", 30) # Output: Alice is 30 years old.

3.2 Keyword Arguments


Arguments are passed by parameter name, allowing flexibility in
order. Example:
def describe_person(name, age):
print(f"{name} is {age} years old.")

describe_person(age=30, name="Alice") # Output: Alice is 30


years old.
3.3 Default Arguments
Default values can be set for parameters.
Example:

def greet(name="Guest"):
print(f"Hello, {name}!")
greet() # Output: Hello, Guest!
greet("Alice") # Output: Hello, Alice!

3.4 Variable-length Arguments


Functions can accept a variable number of arguments using *args (for
positional arguments) or **kwargs (for keyword arguments).
Example with *args:

def add_all(*numbers):
return sum(numbers)
print(add_all(1, 2, 3, 4)) # Output: 10

Example with **kwargs:

def print_details(**details):
for key, value in details.items():
print(f"{key}: {value}")
print_details(name="Alice", age=30, city="New York")

4. Returning Values
Functions can return a value using the return statement.
Example:

def multiply(a, b):


return a * b
result = multiply(4, 5)
print(result) # Output: 20
5. Scope of Variables
5.1 Local Scope
Variables declared inside a function are local to that function.
Example:
def my_function():
local_var = 10
print(local_var)
my_function() # Output: 10
# print(local_var) # Error: local_var is not defined

5.2 Global Scope


Variables declared outside any function are global and accessible
throughout the program.

Example:

global_var = 20
def my_function():
print(global_var)
my_function() # Output: 20

5.3 Using global Keyword


To modify a global variable inside a function, use the global keyword.
Example:

global_var = 20
def modify_global():
global global_var
global_var += 10
modify_global()
print(global_var) # Output: 30

6. Advanced Examples
Example 1: Factorial Function(with recursion)

def factorial(n):
if n == 0 or n == 1:
return 1
return n * factorial(n - 1)
print(factorial(5)) # Output: 120

Example 2: Fibonacci Sequence


def fibonacci(n):
a, b = 0, 1
for _ in range(n):
print(a, end=" ")
a, b = b, a + b

fibonacci(10) # Output: 0 1 1 2 3 5 8 13 21 34

Example 3: Palindrome Checker

def is_palindrome(string):
return string == string[::-1]
print(is_palindrome("radar")) # Output: True
print(is_palindrome("hello")) # Output: False

Example 4: Using Functions with Random Library

import random
def generate_random_list(size, start, end):
return [random.randint(start, end) for _ in range(size)]
random_list = generate_random_list(5, 1, 100)
print(random_list)

You might also like