Here’s a list of Python programming questions with example code for each question. These questions are designed to test your understanding of various Python concepts.
1. Basic Python Concepts:
1.1. Question: Calculate the sum of all even numbers between 1 and 50.
# Example code for question 1.1
total = sum(x for x in range(1, 51) if x % 2 == 0)
print(total)
2. Variables and Data Types:
2.1. Question: Swap the values of two variables without using a temporary variable.
# Example code for question 2.1
a = 5
b = 10
a, b = b, a
print("a =", a)
print("b =", b)
3. Conditional Statements:
3.1. Question: Write a Python program to check if a number is positive, negative, or zero.
# Example code for question 3.1
num = float(input("Enter a number: "))
if num > 0:
print("Positive")
elif num < 0:
print("Negative")
else:
print("Zero")
4. Loops:
4.1. Question: Write a program to print the first 10 numbers in the Fibonacci sequence.
# Example code for question 4.1
a, b = 0, 1
for _ in range(10):
print(a, end=" ")
a, b = b, a + b
5. Lists:
5.1. Question: Find the maximum and minimum values in a list.
# Example code for question 5.1
numbers = [5, 2, 9, 1, 5, 6]
max_value = max(numbers)
min_value = min(numbers)
print("Max:", max_value)
print("Min:", min_value)
6. Functions:
6.1. Question: Write a function to calculate the factorial of a number.
# Example code for question 6.1
def factorial(n):
if n == 0:
return 1
return n * factorial(n - 1)
num = 5
result = factorial(num)
print(f"Factorial of {num} is {result}")
7. String Manipulation:
7.1. Question: Reverse a string.
# Example code for question 7.1
text = "Ideasorblogs"
reversed_text = text[::-1]
print(reversed_text)
8. Dictionaries:
8.1. Question: Count the frequency of words in a text using a dictionary.
# Example code for question 8.1
text = "This is a simple text. This text contains sample words for example."
word_count = {}
words = text.split()
for word in words:
if word in word_count:
word_count[word] += 1
else:
word_count[word] = 1
print(word_count)
9. File I/O:
9.1. Question: Write a program to read data from a file and count the number of lines.
# Example code for question 9.1
with open("data.txt", "r") as file:
lines = file.readlines()
line_count = len(lines)
print(f"Number of lines: {line_count}")
These questions cover a wide range of Python programming topics. You can use the example code provided to understand how to solve each question and then try similar exercises on your own to further practice and reinforce your Python skills.
- Create a Python program to find the DNS record - November 26, 2023
- Billing system using Python project with source code - November 20, 2023
- Python Programming questions with real examples PDF & slides - October 31, 2023