0% found this document useful (0 votes)
5 views3 pages

Python Lab Programs for Beginners

Uploaded by

proz25912
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)
5 views3 pages

Python Lab Programs for Beginners

Uploaded by

proz25912
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

Prem’s Python Lab Programs

G. Pullaiah College of Engineering and Technology (Autonomous)


Department of Computer Science and Engineering

Python Programming (Skill Enhancement Course R23)

Unit – 3

# [Link] a program to create tuples (name, age, address, college)


# for at least two members and concatenate the tuples and print
# the concatenated tuples.

# Define tuples for two members


member1 = ("Prem", 21, "123 Bhagyanagar, Kurnool", "GPCET")
member2 = ("Kumar", 22, "456 Venkayapalli, Kurnool", "GPCET")

# Concatenate the tuples


concatenated_tuple = member1 + member2

# Print the concatenated tuple


print("Concatenated Tuple:")
print(concatenated_tuple)

'''OUTPUT:
Concatenated Tuple:
('Prem', 21, '123 Bhagyanagar, Kurnool', 'GPCET', 'Kumar', 22, '456 SBI circle, Kurnool',
'GPCET')
'''

#14. Write a program to count the number of vowels in a string (No control
flow allowed).

# Input: A string from the user


input_string = input("Enter a string: ")

# Define vowels
vowels = "aeiouAEIOU"

# Count the number of vowels using a list comprehension and sum


vowel_count = sum([1 for char in input_string if char in vowels])

# Display the number of vowels


print(f"The number of vowels in the string is: {vowel_count}")
Prem’s Python Lab Programs

'''OUTPUT:
Enter a string: Prem Kumar
The number of vowels in the string is: 3
'''

# 15. Write a program to check if a given key exists in a dictionary or not.

# Initialize a dictionary
my_dict = {
'name': 'Prem',
'age': 23,
'address': '123, Bhagyanagar',
'college': '[Link] College of Engineering'
}

# Input: Key to check


key_to_check = input("Enter the key to check: ")

# Check if the key exists in the dictionary


if key_to_check in my_dict:
print(f"The key '{key_to_check}' exists in the dictionary.")
else:
print(f"The key '{key_to_check}' does not exist in the dictionary.")

'''OUTPUT:
Enter the key to check: name
The key 'name' exists in the dictionary.
'''

# [Link] a program to add a new key-value pair to an existing dictionary.

# Initialize an existing dictionary


my_dict = {
'name': 'Prem',
'age': 21,
'address': '123 Bhagyanagar, Kurnool'
}

# Input: New key and value to add


new_key = input("Enter the new key: ")
new_value = input("Enter the new value: ")
Prem’s Python Lab Programs

# Add the new key-value pair to the dictionary


my_dict[new_key] = new_value

# Display the updated dictionary


print("Updated dictionary:")
print(my_dict)

'''OUTPUT:
Enter the new key: email
Enter the new value: prem@[Link]
Updated dictionary:
{'name': 'Prem', 'age': 21, 'address': '123 Bhagyanagar, Kurnool', 'email': 'prem@[Link]'}
'''

# [Link] a program to sum all the items in a given dictionary

# Initialize a dictionary with numeric values


my_dict = {
'a': 10,
'b': 20,
'c': 30,
'd': 40
}

# Calculate the sum of all values in the dictionary


total_sum = sum(my_dict.values())

# Display the total sum


print(f"The sum of all items in the dictionary is: {total_sum}")

'''OUTPUT:
The sum of all items in the dictionary is: 100
'''

Common questions

Powered by AI

To add a new key-value pair to an existing dictionary in Python, you define the key and value and use the assignment syntax `my_dict[new_key] = new_value`. For example, to add an email to the dictionary, the code would accept inputs and execute `my_dict['email'] = 'prem@gmail.com'`, which updates the dictionary with the new key-value pair.

To count the number of vowels in a string without control flow, you can use a list comprehension combined with the `sum` function. By iterating over each character in the string and checking if it exists in a string of vowels `'aeiouAEIOU'`, you can create a list of counts, each representing a found vowel. The `sum` function then totals these counts. For example, `sum([1 for char in input_string if char in vowels])` provides the total count of vowels.

The sum of all items in a dictionary with numeric values is calculated using the `sum` function on the dictionary's values, as in `sum(my_dict.values())`. This expression iterates over all the numeric values and computes their total, which is then printed to display: `The sum of all items in the dictionary is: 100`.

The code uses the `in` keyword to check if a key exists in a dictionary, as demonstrated with `if key_to_check in my_dict:`. This method is efficient because it is implemented in constant time O(1) average complexity due to Python's dictionary hashing mechanism, which allows for fast lookups by checking the presence of the key in the dictionary's keys.

The program adds a key-value pair by assigning the value to the specific key in the dictionary using `my_dict[new_key] = new_value`. Afterward, it verifies the update by directly printing the dictionary, allowing visual confirmation of the newly inserted pair. This immediate verification step ensures that users can see the successful update operation in the output: `{'name': 'Prem', 'age': 21, 'address': '123 Bhagyanagar, Kurnool', 'email': 'prem@gmail.com'}`.

The document's approach illustrates efficiency by utilizing Python’s built-in `sum` function to aggregate numeric values in a dictionary, as in `sum(my_dict.values())`. This function succinctly handles iteration and accumulation internally, optimizing performance and reducing code complexity. The use of `sum` leverages Python's optimized C-level operations for handling numerical data, making it both simple and efficient for calculating totals in dictionaries.

To create and concatenate tuples in Python, you can define multiple tuples and use the '+' operator to concatenate them. In the example provided, two tuples are defined: `member1` and `member2`. They are concatenated using `member1 + member2` to form `concatenated_tuple`, which is then printed, outputting: `('Prem', 21, '123 Bhagyanagar, Kurnool', 'GPCET', 'Kumar', 22, '456 SBI circle, Kurnool', 'GPCET')`.

The benefits of using list comprehension to count vowels include concise and readable code, along with efficient iteration over the string. It eliminates the need for explicit loop constructs, resulting in cleaner syntax. However, a limitation is that it evaluates all characters initially, which could be inefficient for very long strings. Moreover, it may be less straightforward for beginners to understand due to Python's functional programming elements.

Checking for a key's existence in a dictionary is crucial because it prevents errors that occur when attempting to access non-existent keys, which would typically raise a `KeyError`. This practice is essential for ensuring the robustness of applications that dynamically interact with user data or APIs where not all keys may always be present. The example program ensures safe access by verifying the presence of the key using `if key_to_check in my_dict:`, safeguarding against potential runtime errors.

Tuple concatenation is considered powerful because it allows the efficient combination of immutable ordered sequences, enabling the aggregation of related data without modifying the original tuples. This operation provides a straightforward way to create complex data structures while maintaining Python's immutability and integrity guarantees. The simplicity of using the '+' operator makes the syntax intuitive, as shown when combining `member1` and `member2` into `concatenated_tuple`.

You might also like