0% found this document useful (0 votes)
30 views

Python Solutions

The document discusses various Python programming concepts like operators, comments, string methods, slicing operations, and differences between lists, tuples, sets and dictionaries. It provides examples and sample Python code to demonstrate each concept. For arithmetic and logical operators, it shows the usage and examples. For comments, it explains single-line, multiline and triple quoted string comments. It also provides string methods like upper(), lower(), title() etc and explains slicing operations on strings with examples. Finally, it summarizes the key differences between lists, tuples, sets and dictionaries in terms of mutability, ordering, allowing duplicates etc.
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
30 views

Python Solutions

The document discusses various Python programming concepts like operators, comments, string methods, slicing operations, and differences between lists, tuples, sets and dictionaries. It provides examples and sample Python code to demonstrate each concept. For arithmetic and logical operators, it shows the usage and examples. For comments, it explains single-line, multiline and triple quoted string comments. It also provides string methods like upper(), lower(), title() etc and explains slicing operations on strings with examples. Finally, it summarizes the key differences between lists, tuples, sets and dictionaries in terms of mutability, ordering, allowing duplicates etc.
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 11

1)Python program to demonstrate various arithme c and logical operators

Arithmetic Operators:

 +: Addition (e.g., 5 + 3 evaluates to 8)


 -: Subtraction (e.g., 10 - 2 evaluates to 8)
 *: Multiplication (e.g., 4 * 5 evaluates to 20)
 /: Division (e.g., 12 / 3 evaluates to 4.0)
 //: Floor division - Quotient without remainder (e.g., 11 // 3 evaluates to 3)
 %: Modulo - Remainder after division (e.g., 11 % 3 evaluates to 2)
 **: Exponentiation (e.g., 2 ** 3 evaluates to 8)

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

print(“Sum of a and b is : “,Sum)


print(“Difference of a and b is : “,Difference)

Prepared by:Tejas Poojary


print(“Product of a and b is : “,Product)
print(“Quo ent of a and b is : “,Quo ent)
print(“Remainder of a and b is : “,Remainder)
print(“Exponent of a and b is : “,Exponent)
#Logical operators
print(a>b and 5<10) #logical and operator
print(a<b or 7>5)
print (not(a==b and 2!=5))

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.

# This is a multiline comment


# explaining multiple lines of code.
# It can be used for longer descriptions.

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

Prepared by:Tejas Poojary


write multiline text without being affected by the newline characters within the
string.

"""
This is a multiline comment
using triple-quoted strings.
It's useful for more detailed explanations.
"""

3) String methods in Python with a suitable program


user_string = input("Enter a string: ") # User Input

print("Original String:", user_string)


print("Uppercase:", user_string.upper()) # Convert to uppercase
print("Lowercase:", user_string.lower()) # Convert to lowercase
print("Title Case:", user_string.title()) # Convert to title case

# 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())

Prepared by:Tejas Poojary


#Check for existence of word
keyword="Hello"
print("Is Hello present in the string: ",keyword in user_string)
Or
print("Is Hello present in the string: ",”Hello” in user_string)
#Splitting string based on separator
print("The string after split is:",user_string.split("l"))
#Joining the string back after split
print("The string after joining is:",'#'.join(user_string.split("l")))
#Check for count
print("The number of times word Hello has repeated:",user_string.count(keyword))

4) Python program to demonstrate slicing operations in String.


# Sample string
my_string = "Python for Beginners"

# Extracting characters using slicing


# Get the first 6 characters (up to, but not including, index 6)
first_six = my_string[:6]
print(first_six) # Output: Python

# Get characters from index 7 to the end (everything after ' ')
last_part = my_string[7:]
print(last_part) # Output: for Beginners

# Get characters from index 3 (inclusive) to index 10 (exclusive)


middle_part = my_string[3:10]
print(middle_part) # Output: hon for

Prepared by:Tejas Poojary


# Get every other character (starting from the first)
alternate_chars = my_string[::2]
print(alternate_chars) # Output: Pto o einr

# Reverse the string


reversed_string = my_string[::-1]
print(reversed_string) # Output: srennigeB rof nohtyP

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.

3)[start_index:end_index]: Extracts characters from the start_index (inclusive) up to,


but not including, the end_index.

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.

5)[::-1]: Reverses the entire string.

5) Differences between List, Tuple, Set and Dictionary

The key differences between lists, tuples, sets, and dictionaries in Python:

1. Mutability:

 List: Mutable (elements can be changed after creation)


 Tuple: Immutable (elements cannot be changed after creation)
 Set: Mutable (elements can be added or removed, but the order is not
maintained)

Prepared by:Tejas Poojary


 Dictionary: Mutable (key-value pairs can be added, removed, or modified)

2. Ordering:

 List: Ordered (elements retain the order they were added)


 Tuple: Ordered (elements retain the order they were added)
 Set: Unordered (elements have no specific order)
 Dictionary: Unordered (elements are not stored in a specific order)

3. Duplicates:

 List: Allows duplicates (elements can appear multiple times)


 Tuple: Allows duplicates (elements can appear multiple times)
 Set: Does not allow duplicates (each element must be unique)
 Dictionary: Keys must be unique (no duplicate keys allowed, but values can
have 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)

6) Various List operations with a suitable program

Prepared by:Tejas Poojary


# Create a sample list
my_list = [3, "apple", True, 1.5, ["orange", "banana"]]

# Print the list


print("Original List:", my_list)

# Accessing elements
first_element = my_list[0] # Access by index (0-based)
last_element = my_list[-1] # Access last element

print("First element:", first_element)


print("Last element:", last_element)

# Slicing (extracting a portion)


sublist = my_list[1:3] # Extract elements from index 1 (inclusive) to 3 (exclusive)

print("Sublist (1:3):", sublist)

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

print("List after adding elements:", my_list)

# Removing elements

Prepared by:Tejas Poojary


my_list.remove("apple") # Remove the first occurrence of "apple"
del my_list[3] # Remove element at index 3

print("List after removing elements:", my_list)

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

# Looping through elements


for item in my_list:
print(item)

# Concatenation (joining lists)


fruits = ["watermelon", "kiwi"]
combined_list = my_list + fruits

print("Combined list:", combined_list)

# Sorting (ascending order)


my_list.sort()
print("List after sorting:", my_list) #only possible for elements of same datatype

# Reversing the order


my_list.reverse()

Prepared by:Tejas Poojary


print("List after reversing:", my_list)

7) Program to access the elements of a dictionary

# Create a dictionary
my_dict = {
"name": "Alice",
"age": 30,
"city": "New York",
"interests": ["music", "reading", "coding"]
}

# Accessing elements by key


name = my_dict["name"]
age = my_dict["age"]

print("Name:", name)
print("Age:", age)

# Checking for key existence (using get method)


does_key_exist = "occupation" in my_dict # Checking directly (returns
False)
occupation = my_dict.get("occupation", "Not specified") # Using get method
with default value

print("Does 'occupation' key exist?", does_key_exist)


print("Occupation:", occupation)

# Accessing elements within a list value


interests = my_dict["interests"]

Prepared by:Tejas Poojary


first_interest = interests[0]

print("Interests:", interests)
print("First interest:", first_interest)

x = my_dict.keys()
print("The list of keywords is:",x)

8) Different loop statements in Python

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:

for element in sequence:

# Code to be executed for each element

Example:

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

for fruit in fruits:

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

Prepared by:Tejas Poojary


Example:

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

Prepared by:Tejas Poojary

You might also like