Get a grip on Python basics through our easy-to-follow Python Basics Exercise and Solutions. Whether you’re new to coding or want to sharpen your skills, this exercise offers step-by-step practice problems with answers. Start your Python journey with hands-on learning and build a solid foundation in a fun and approachable way!
Question 1 : Calculate the Sum of the previous number and the current number from 0 to 10.
Code:
previous_number = 0
for i in range(1, 11):
print(f"Previous Number = {previous_number}, Current Number = {i}, Sum = {previous_number+i}")
previous_number = i
Explanation:
In this code, the for loop is used that iterates through the numbers from 1 to 11 (11 not included). The loop variable i takes on values from 1 to 10 in each iteration.
In each iteration, this line prints a formatted string. It includes information about the previous number, the current number (i), and the sum of the previous number and the current number.
The f”…” syntax is used for formatted string literals in Python, allowing variables to be inserted directly into the string.
After printing the information, the value of previous_number is updated to the current value of i. This is done so that in the next iteration, previous_number will hold the value of the current number for that iteration.
So, the output of this code is the series of lines, each showing the previous number, the current number, and their sum as i iterates from 1 to 10. The sum is calculated by adding the current number i to the previous number.
Output:
Previous Number = 0, Current Number = 1, Sum = 1
Previous Number = 1, Current Number = 2, Sum = 3
Previous Number = 2, Current Number = 3, Sum = 5
Previous Number = 3, Current Number = 4, Sum = 7
Previous Number = 4, Current Number = 5, Sum = 9
Previous Number = 5, Current Number = 6, Sum = 11
Previous Number = 6, Current Number = 7, Sum = 13
Previous Number = 7, Current Number = 8, Sum = 15
Previous Number = 8, Current Number = 9, Sum = 17
Previous Number = 9, Current Number = 10, Sum = 19
Question 2 : Remove the first n elements from the string.
Code:
name = "Logical Python"
n = int(input("Enter the number of characters to remove = "))
final_string = name[n:]
print(final_string)
Explanation:
We prompt the user to enter a number of characters to remove (n). The input function takes user input as a string, and int() is used to convert it to an integer.
Next line creates a new string final_string by using slicing. It starts from the n-th character of the original string (name) and goes until the end. So, it removes the first n characters from the original string.
Finally, the code prints the final_string which is the original string (name) with the first n characters removed.
Output:
Enter the number of characters to remove = 5
al Python
Question 3 : Count the number of times the substring “Python” occurs in the given string.
Given String:
str = "Logical Python is the website to learn Python. Logical Python is the best."
Expected Output:
3
Code:
str = "Logical Python is the website to learn Python. Logical Python is the best."
str.count("Python")
Explanation:
The count method is applied to the string str with the argument “Python”. This method returns the number of non-overlapping occurrences of the specified substring within the string.
In this case, it will count how many times the substring “Python” appears in the given string. The result will be the total count of occurrences.
Output:
3
Question 4 : Print multiplication tables from 1 to 5.
Code:
for i in range (1,6):
print("Table of",i,"= ", end="")
for j in range (1,11):
print(i*j, end = " ")
print('')
Explanation:
The outer loop iterates over numbers from 1 to 5, representing the base numbers for multiplication tables.
For each base number, it prints a header indicating the table of that number, without moving to the next line (end=””).
The inner loop iterates over multipliers from 1 to 10, and it prints the products of the base number and multipliers in the same line.
After printing one complete multiplication table, a newline is added to move to the next line.
The code produces a set of multiplication tables, each spanning from 1 to 10, for numbers 1 to 5.
Question 8 : In which case id() will return the same value?
# 1
a = 10
print(id(a))
#2
a = a - 1
print(id(a))
#3
a = "Logical"
print(id(a))
Answer:
None of the case. Because every time we assign a new value to the variable, a new id is assigned.
Code:
# 1
a = 10
print(id(a))
#2
a = a - 1
print(id(a))
#3
a = "Logical"
print(id(a))
Output:
140705349477040
140705349477008
1871821162736
Question 9 : Will the id() will return the same value or the different?
# 1
a = 20
print(id(a))
#2
b = 20
print(id(b))
Answer:
It is the same in this case because we are assigning the same value to both the variables.
In Python, small integers (usually between -5 and 256) are cached and reused. This is an optimization strategy to save memory and improve performance. When you assign the same value to multiple variables within this range, they may end up referencing the same object in memory.
Note: This behavior might not hold for larger integers or different values, where separate objects in memory would be created.
Code:
# 1
a = 20
print(id(a))
#2
b = 20
print(id(b))
Output:
140705349477360
140705349477360
Question 10 : What is the output of the following code?
print(2 < 2 or 4)
print(2 < 3 or 4)
print(2 < (2 or 4))
print(2 < (4 or 2))
Explanation:
1. print(2 < 2 or 4)
The expression 2 < 2 is False, so the or operator evaluates the second operand 4. The result is 4, and the print statement outputs 4.
2. print(2 < 3 or 4)
Here, 2 < 3 is True, so the or operator short-circuits and doesn’t evaluate the second operand. The result is True, and the print statement outputs True.
3. print(2 < (2 or 4))
The expression (2 or 4) evaluates to 2 because the or operator returns the first truthy value. So, the comparison becomes 2 < 2, which is False. The print statement outputs False.
4. print(2 < (4 or 2))
Similarly, (4 or 2) evaluates to 4. The comparison becomes 2 < 4, which is True. The print statement outputs True.
Output:
4
True
False
True
Question 11 : What is the output of the following code?
import math
print(-2**2)
print(-2*-2)
print(math.pow(-2,2))
Output:
-4
4
4.0
Explanation:
1. print(-2**2)
Why is it -4 while others are 4?
This expression involves the exponentiation operator (**). In Python, exponentiation has higher precedence than negation. So, -2**2 is equivalent to -(2**2). This means the square of 2 is calculated first (resulting in 4), and then the negation is applied. Therefore, the output is -4.
2. print(-2*-2)
This expression involves the multiplication of two negative numbers. The product of -2 and -2 is 4. So, the output is 4.
3. print(math.pow(-2, 2))
This line uses the pow function from the math module to calculate the power of -2 raised to the exponent 2. The result is 4, and the output is 4.
Question 12 : What is the output of the following code?