[go: up one dir, main page]

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

? Chapter 4 Practice Set

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

? Chapter 4 Practice Set

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
You are on page 1/ 6

📘 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):
li.append(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):
students.append(int(input("Enter the marks of the student: "))) #
Append the marks to the list
students.sort() # 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(tuple.count(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.

You might also like