0% found this document useful (0 votes)
12 views6 pages

Python Programming Practice Exercises

The document contains a practice set of Python programming exercises covering various topics such as lists, tuples, string manipulation, and functions. Each exercise includes a code snippet, an explanation of the code, and a pro tip for better understanding. Additionally, it poses extra questions to deepen knowledge on concepts like list comprehensions and decorators.

Uploaded by

dhaksha8708
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)
12 views6 pages

Python Programming Practice Exercises

The document contains a practice set of Python programming exercises covering various topics such as lists, tuples, string manipulation, and functions. Each exercise includes a code snippet, an explanation of the code, and a pro tip for better understanding. Additionally, it poses extra questions to deepen knowledge on concepts like list comprehensions and decorators.

Uploaded by

dhaksha8708
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

📘 Chapter 4 Practice Set

💡 1. Write a Python program to store seven fruits in a list entered by the


user.

# List to store the fruits


li = []

# Loop to store the fruits


for i in range(7):
[Link](input("Enter the fruit: ")) # Append the fruit to the
list

print(li) # Print the list

Explanation:

● We create an empty list li to store the fruits.


● Using a loop, we take input for seven fruits and append each to the list.
● Finally, we print the list containing all the fruits.

Pro Tip:

● Lists in Python are dynamic; you can append as many elements as you like!

💡 2. Write a program to accept marks of 6 students and display them in a


sorted manner.

# List to store the marks of the students


students = []

# Loop to store the marks of the students


for i in range(6):
[Link](int(input("Enter the marks of the student: "))) #
Append the marks to the list
[Link]() # Sort the list
print(students) # Print the sorted list

Explanation:

● We initialize an empty list students.


● After collecting the marks, we use the sort() method to arrange them in ascending
order.
● Finally, the sorted list is printed.

Pro Tip:

● Sorting is useful when you need to rank or order data. Use reverse=True in the
sort() method to sort in descending order!

💡 3. Check that a tuple cannot be changed in Python.


testing = (1, 2, 3, 4, 5)

testing[0] = 10 # This will give an error

print(testing)

Explanation:

● Tuples are immutable in Python, meaning their elements cannot be changed after
creation.
● Attempting to modify any element of a tuple will raise a TypeError.

Pro Tip:

● Use tuples when you need a collection that should remain constant throughout the
program.

💡 4. Write a program to sum a list with 4 numbers.


list = [1, 2, 3, 4]

print(sum(list)) # Print the sum of the list

Explanation:

● We use the sum() function to add all elements of the list.


● The result, which is the sum of the list elements, is printed.

Pro Tip:

● sum() is highly optimized for summing numbers in Python lists, making it preferable
over manual loops.

💡 5. Write a program to count the number of zeros in the following tuple:


tuple = (7, 0, 8, 0, 0, 9)

print([Link](0)) # Print the number of zeros in the tuple

Explanation:

● The count() method counts occurrences of a specified value in the tuple.


● We count how many times 0 appears and print the result.

Pro Tip:

● The count() method works on both tuples and lists to count specific elements.

💡 6. Write a program to find the largest number in a list.


numbers = [3, 5, 1, 8, 2] # List of numbers
largest = max(numbers) # Find the largest number
print(f"The largest number is: {largest}") # Output the largest
number
Explanation:

● The max() function is used to find the largest number in the list.
● The result is printed in a formatted string.

Pro Tip:

● max() and min() are fast and effective for finding extremes in lists.

💡 7. Write a program to reverse a string entered by the user.


user_string = input("Enter a string: ") # Get user input

reversed_string = user_string[::-1] # Reverse the string

print(f"Reversed string: {reversed_string}") # Output the reversed


string

Explanation:

● We take a string as input and use slicing [::-1] to reverse it.


● The reversed string is printed.

Pro Tip:

● String slicing is a powerful feature in Python for various string manipulations.

💡 8. Write a program to check if a number is prime.


num = int(input("Enter a number: ")) # Get user input
is_prime = True # Assume the number is prime

if num > 1: # Check for prime condition


for i in range(2, int(num**0.5) + 1):
if num % i == 0:
is_prime = False # Not prime if divisible
break
else:
is_prime = False # Numbers less than 2 are not prime

print(f"{num} is {'a prime' if is_prime else 'not a prime'} number.")


# Output result

Explanation:

● We check if the number is prime by testing divisibility from 2 to the square root of the
number.
● The result is printed to indicate whether the number is prime.

Pro Tip:

● Checking divisibility up to the square root of the number reduces the number of iterations
and improves efficiency.

💡 9. Write a program to calculate the factorial of a number.


def factorial(n): # Function to calculate factorial
if n == 0 or n == 1:
return 1
else:
return n * factorial(n - 1)

num = int(input("Enter a number to find its factorial: ")) # Get user


input
print(f"The factorial of {num} is: {factorial(num)}") # Output the
factorial

Explanation:

● We define a recursive function to calculate the factorial of a number.


● The result is printed using formatted output.

Pro Tip:

● Recursive functions are elegant but be cautious with large inputs due to potential stack
overflow.
💡 10. Write a program to create a dictionary from two lists.
keys = ['name', 'age', 'city'] # List of keys
values = ['Alice', 25, 'New York'] # List of values

dictionary = dict(zip(keys, values)) # Create dictionary


print(dictionary) # Output the dictionary

Explanation:

● We use the zip() function to pair keys and values and create a dictionary.
● The dictionary is printed.

Pro Tip:

● zip() is a versatile function that can combine multiple iterables into tuples.

📝 Additional Questions:
1. What is a list comprehension? Provide an example.
2. Explain the difference between a list and a tuple.
3. How do you handle exceptions in Python? Give an example.
4. What are lambda functions? Provide a simple use case.
5. Explain the concept of decorators in Python with an example.

Common questions

Powered by AI

The square root method in prime checking algorithms reduces the number of potential divisors significantly, improving efficiency. By only checking for divisibility up to the square root of a number, unnecessary calculations are avoided, as a larger factor of the number must be smaller than the square root unless it's a perfect square . This optimization reduces the number of iterations, leading to quicker determinations of non-primality.

Tuples in Python are immutable, meaning once they are created, their elements cannot be changed or updated, which makes them ideal for fixed collections of data that should not change . In contrast, lists are mutable, allowing for dynamic storage where elements can be added, removed, or changed, providing flexibility in data manipulation and making them suitable for collections that require frequent updates .

Calculating factorial using recursion in Python is concise but can be inefficient and risky with large inputs due to the recursive depth limit and the potential for stack overflow errors . Python's recursion limits are relatively low compared to iterative approaches, and extensive use can lead to performance degradation and memory issues. Iterative methods or using built-in functions like factorial from the math module offer better efficiency and safety for large inputs.

List comprehensions in Python offer a more concise and readable way to create lists compared to traditional loops. They allow for in-line generation of list elements with optional conditionals, making the code more declarative and less verbose. This can lead to performance improvements as list comprehensions are generally faster due to optimization by the Python interpreter .

Exception handling in Python through try-except blocks enhances code reliability by allowing developers to catch and manage unexpected errors without crashing the program. This mechanism provides a way to gracefully handle errors, log issues, or provide alternative logic paths, which improves user experience and maintains program stability . Properly managed exceptions also facilitate debugging and maintenance.

The max() and min() functions in Python are optimized for quickly finding the largest and smallest elements in a list. These functions iterate through the list to find the extremes, making them fast and efficient under typical use cases . Their performance is notably better than manually iterating through a list and comparing each element, especially with large datasets.

String slicing in Python allows accessing subsets of strings using the syntax string[start:stop:step]. By setting the step parameter to -1, the slicing operation can reverse the string as it iterates from the last character to the first, which provides an elegant one-liner for string reversal without the need for loops or additional variables . This flexibility in manipulation is powerful for various text processing tasks.

Tuples' immutability makes them suitable for use cases where a fixed collection of values needs to be maintained without the risk of alteration, ensuring data integrity. This property is advantageous in situations like storing multiple return values from functions, serving as dictionary keys, or representing rows returned from a database query, where stability and predictability are important .

Lambda functions in Python are useful for simplifying code that requires small, unnamed functions, particularly in contexts like filtering or mapping. Their succinct syntax makes them ideal for use in higher-order functions like map(), filter(), and sorted() where a full function definition would be verbose and unnecessary. They enhance code clarity and reduce boilerplate for straightforward operations .

The zip() function in Python efficiently pairs elements from multiple iterables (like lists) into tuples, which can then be directly passed to dict() to form a dictionary . This method is concise and less error-prone compared to a manual loop-based method, which would require iterating over the indices and manually adding items to the dictionary. The zip() approach reduces code complexity and enhances readability, preventing typical loop-related errors.

You might also like