Python Basics Exercise and Solutions


Python Basics Exercise

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!

Python Basics Exercise

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:

  1. 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.
  2. 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.
  3. The f”…” syntax is used for formatted string literals in Python, allowing variables to be inserted directly into the string.
  4. 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.
  5. 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:

  1. 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.
  2. 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.
  3. 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:

  1. 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.
  2. 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:

  1. The outer loop iterates over numbers from 1 to 5, representing the base numbers for multiplication tables.
  2. For each base number, it prints a header indicating the table of that number, without moving to the next line (end=””).
  3. 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.
  4. After printing one complete multiplication table, a newline is added to move to the next line.
  5. The code produces a set of multiplication tables, each spanning from 1 to 10, for numbers 1 to 5.

Output:

Table of 1 = 1 2 3 4 5 6 7 8 9 10 
Table of 2 = 2 4 6 8 10 12 14 16 18 20 
Table of 3 = 3 6 9 12 15 18 21 24 27 30 
Table of 4 = 4 8 12 16 20 24 28 32 36 40 
Table of 5 = 5 10 15 20 25 30 35 40 45 50 


Question 5 : Two ways to create multi-line strings in Python?

Way 1 : Using the backslash at the end of each line

str = "Welcome \
to \
Logical \
Python"
print(str)

Output:

Welcome to Logical Python

Way 2 : Using the triple quotes

str = """Welcome 
to 
Logical 
Python"""
print(str)

Output:

Welcome 
to 
Logical 
Python

Note: in both the cases, the output is not similar. Using triple quotes, it maintains the formatting of the text.


Question 6 : Find error with the following code?

print("Hello World!")
print("Welcome to")
    print("Logical Python!")

This code does not follow the required indentation. As the python’s indentation rules, all lines of the code were supposed to be on the same line.

Correct Code:

print("Hello World!")
print("Welcome to")
print("Logical Python!")

Question 7 : Find the output of each?

type(0)
type(int(0))
type(float(0))
type(int("0"))
type("0")
type(int(1.0))

Code:

print(type(0))
print(type(int(0)))
print(type(float(0)))
print(type(int("0")))
print(type("0"))
print(type(int(1.0)))

Output:

<class 'int'>
<class 'int'>
<class 'float'>
<class 'int'>
<class 'str'>
<class 'int'>

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?

print(bool(0.0))
print(bool('0.0'))
print(bool(''))
print(bool('0'))
print(bool('1'))

Output:

False
True
False
True
True

Explanation:

The bool() function is used to convert the argument to a Boolean value.

1. print(bool(0.0))

The 0.0 is considered as False. The output is False.

2. print(bool(‘0.0’))

A non-empty string, even if it contains characters other than digits, evaluates to True. Therefore, the output is True.

3. print(bool(”))

An empty string evaluates to False. So, the output is False.

4. print(bool(‘0’))

A non-empty string, regardless of its content, evaluates to True. Therefore, the output is True.

5. print(bool(‘1’))

Similar to the previous case, a non-empty string evaluates to True. So, the output is True.