Python Solutions
Python Solutions
Arithmetic Operators:
Logical Operators:
and: Evaluates to True only if both operands are True (e.g., True and
False evaluates to False)
or: Evaluates to True if at least one operand is True (e.g., True or
False evaluates to True)
not: Inverts the true value of the operand (e.g., not True evaluates to False)
PROGRAM:
a=float(input(“Enter the value of a: “))
b=float(input(“Enter the value of b: “)) #conver ng a and b from strings to
numbers
#Arithme c operators
Sum= a+b
Difference = a-b
Product = a * b
Quo ent = a / b
Remainder = a%b
Exponent = a**b
2) Comments in Python
Comments in Python are essen al for wri ng clear and understandable code. They
are lines of text ignored by the Python interpreter when execu ng the program.
However, comments serve as valuable explana ons for human readers, making it
easier to understand the code's logic and func onality.
The different types of comments in Python:
Single-line comments: These comments start with the hash symbol (#) and extend to
the end of the line. They are useful for providing brief explana ons for specific lines
of code.
#This is a single line comment explaining the code below
Multiline comments: While Python doesn't have a dedicated syntax for multiline
comments like some other languages, there are two common approaches to achieve
this:
a)Using multiple hash symbols: You can add a hash symbol (#) at the beginning of
each line to create a multiline comment block.
b)Using triple-quoted strings: You can enclose your comment within triple quotes
(either three single quotes '' or three double quotes "" ). This approach allows you to
"""
This is a multiline comment
using triple-quoted strings.
It's useful for more detailed explanations.
"""
# Replace characters
print("Replacing spaces with underscores:", user_string.replace("e", "a"))
# Slicing (extracting substring)
print("Extracting first 3 characters:", user_string[:3])
print("Extracting characters from 4th to the end:", user_string[3:])
# Check prefix
print("Checking if the string starts with 'Hello':", user_string.startswith("Hello"))
# Check suffix
print("Checking if the string ends with 'world!':",
user_string.endswith("world!"))
# Remove whitespaces
print("Removing leading/trailing whitespaces:", user_string.strip())
# Get characters from index 7 to the end (everything after ' ')
last_part = my_string[7:]
print(last_part) # Output: for Beginners
1)[:stop_index]: Extracts characters from the beginning of the string up to, but not
including, the stop_index.
2)[start_index:]: Extracts characters from the start_index (inclusive) to the end of the
string.
4)[::step]: Extracts characters with a specified step. It iterates through the string,
picking every stepth character. A step of 2 extracts every other character.
The key differences between lists, tuples, sets, and dictionaries in Python:
1. Mutability:
2. Ordering:
3. Duplicates:
4. Use Cases:
List: Used for storing collections of ordered items that may need to be
changed later. (e.g., shopping list, to-do list)
Tuple: Used for representing fixed data that shouldn't be modified after
creation. (e.g., coordinates, configuration settings)
Set: Used for storing unique elements and performing set operations like
union, intersection, difference. (e.g., removing duplicates from a list, checking
for membership)
Dictionary: Used for storing key-value pairs where the key acts like a unique
identifier for the associated value. (e.g., phonebook, student data with name
as key and marks as value)
# Accessing elements
first_element = my_list[0] # Access by index (0-based)
last_element = my_list[-1] # Access last element
# Modifying elements
my_list[2] = False # Change element at index 2
print("List after modification:", my_list)
# Adding elements
my_list.append("grape") # Add element to the end
my_list.insert(1, "mango") # Insert element at specific index (1)
# Removing elements
# Checking membership
is_present = "mango" in my_list
print("Is 'mango' in the list?", is_present)
# List length
list_length = len(my_list)
print("Length of the list:", list_length)
# Create a dictionary
my_dict = {
"name": "Alice",
"age": 30,
"city": "New York",
"interests": ["music", "reading", "coding"]
}
print("Name:", name)
print("Age:", age)
print("Interests:", interests)
print("First interest:", first_interest)
x = my_dict.keys()
print("The list of keywords is:",x)
1. For Loop:
The for loop iterates over a sequence of elements (like a list, tuple, or string). It's
ideal for processing elements in a collection one by one.
Syntax:
Example:
print(fruit)
2. While Loop:
The while loop keeps executing a block of code as long as a certain condition remains
True. It's suitable for situations where you don't know the exact number of iterations
beforehand
Syntax:
while condition:
# Code to be executed while the condition is True
count = 0
while count < 5:
print(count)
count += 1
3. Nested Loops:
You can have loops within loops. This allows you to iterate over multiple sequences
or create complex patterns.
Example:
for i in range(2):
for j in range(3):
print(f"({i}, {j})")y
This will print all combinations of coordinates (0,0), (0,1), (0,2), (1,0), (1,1), and (1,2).