0% found this document useful (0 votes)
14 views15 pages

Python Exercises for Beginners

The document contains a series of Python exercises covering various programming concepts such as multiplication, string manipulation, list operations, and pattern printing. Each exercise provides a problem statement, expected output, and a solution in Python code. The exercises range from basic arithmetic operations to more complex tasks like checking for palindromes and calculating income tax.

Uploaded by

bayanayohit
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)
14 views15 pages

Python Exercises for Beginners

The document contains a series of Python exercises covering various programming concepts such as multiplication, string manipulation, list operations, and pattern printing. Each exercise provides a problem statement, expected output, and a solution in Python code. The exercises range from basic arithmetic operations to more complex tasks like checking for palindromes and calculating income tax.

Uploaded by

bayanayohit
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

Exercise 1: Calculate the multiplication and sum

of two numbers
Given two integer numbers, write a Python code to return their product only if the
product is equal to or lower than 1000. Otherwise, return their sum.

Given 1:

number1 = 20

number2 = 30

Expected Output:

The result is 600

Given 2:

number1 = 40

number2 = 30

Expected Output:

The result is 70

def multiplication_or_sum(num1, num2):

# calculate product of two number

product = num1 * num2

# check if product is less then 1000

if product <= 1000:

return product
else:

# product is greater than 1000 calculate sum

return num1 + num2

# first condition

result = multiplication_or_sum(20, 30)

print("The result is", result)

# Second condition

result = multiplication_or_sum(40, 30)

print("The result is", result)

Exercise 2: Print the Sum of a Current Number


and a Previous number
Write a Python code to iterate the first 10 numbers, and in each iteration, print the
sum of the current and previous number.

Expected Output:

Printing current and previous number sum in a range(10)

Current Number 0 Previous Number 0 Sum: 0

Current Number 1 Previous Number 0 Sum: 1

Current Number 2 Previous Number 1 Sum: 3

Current Number 3 Previous Number 2 Sum: 5

Current Number 4 Previous Number 3 Sum: 7

Current Number 5 Previous Number 4 Sum: 9

Current Number 6 Previous Number 5 Sum: 11


Current Number 7 Previous Number 6 Sum: 13

Current Number 8 Previous Number 7 Sum: 15

Current Number 9 Previous Number 8 Sum: 17

print("Printing current and previous number and their sum in a range(10)")

previous_num = 0

# loop from 1 to 10

for i in range(1, 11):

x_sum = previous_num + i

print("Current Number", i, "Previous Number ", previous_num, " Sum: ", x_sum)

# modify previous number

# set it to the current number

previous_num = i

Exercise 3: Print characters present at an even


index number
Write a Python code to accept a string from the user and display characters present
at an even index number.

For example, str = "PYnative". so your code should display ‘P’, ‘n’, ‘t’, ‘v’.
Expected Output:

Orginal String is PYnative


Printing only even index chars
P
n
t
v

# accept input string from a user

word = input('Enter word ')

print("Original String:", word)

# get the length of a string

size = len(word)

# iterate a each character of a string

# start: 0 to start with first character

# stop: size-1 because index starts with 0

# step: 2 to get the characters present at even index like 0, 2, 4

print("Printing only even index chars")

for i in range(0, size - 1, 2):

print("index[", i, "]", word[i])


Exercise 4: Remove first n characters from a
string
Write a Python code to remove characters from a string from 0 to n and return a new string.

For Example:

 remove_chars("PYnative", 4) so output must be tive. Here, you need to remove the first
four characters from a string.

 remove_chars("PYnative", 2) so output must be native. Here, you need to remove the first
two characters from a string.
Note: n must be less than the length of the string.

Show Solution

def remove_chars(word, n):


print('Original string:', word)
x = word[n:]
return x

print("Removing characters from a string")


print(remove_chars("pynative", 4))
print(remove_chars("pynative", 2))

Exercise 5: Check if the first and last numbers of


a list are the same
Write a code to return True if the list’s first and last numbers are the same. If the numbers
are different, return False.

Given:

numbers_x = [10, 20, 30, 40, 10]

numbers_y = [75, 65, 35, 75, 30]

Expected Output:
Given list: [10, 20, 30, 40, 10]

result is True

numbers_y = [75, 65, 35, 75, 30]

result is False

Show Solution

def first_last_same(numberList):

print("Given list:", numberList)

first_num = numberList[0]

last_num = numberList[-1]

if first_num == last_num:

return True

else:

return False

numbers_x = [10, 20, 30, 40, 10]

print("result is", first_last_same(numbers_x))

numbers_y = [75, 65, 35, 75, 30]

print("result is", first_last_same(numbers_y))

Exercise 6: Display numbers divisible by 5


Write a Python code to display numbers from a list divisible by 5

Expected Output:
Given list is [10, 20, 33, 46, 55]

Divisible by 5

10

20

55

Show Solution

num_list = [10, 20, 33, 46, 55]

print("Given list:", num_list)

print('Divisible by 5:')

for num in num_list:

if num % 5 == 0:

print(num)

Exercise 7: Find the number of occurrences of a


substring in a string
Write a Python code to find how often the substring “Emma” appears in the given string.

Given:

str_x = "Emma is good developer. Emma is a writer"

Expected Output:

Emma appeared 2 times

Show Solution

str_x = "Emma is good developer. Emma is a writer"

# use count method of a str class

cnt = str_x.count("Emma")
print(cnt)

Exercise 8: Print the following pattern

22

333

4444

55555

Show Solution

for num in range(10):

for i in range(num):

print (num, end=" ") #print number

# new line after each row to display pattern correctly

print("\n")

Exercise 9: Check Palindrome Number


Write a Python code to check if the given number is palindrome. A palindrome number is a
number that is the same after reverse. For example, 545 is the palindrome number.

Expected Output:

original number 121


Yes. given number is palindrome number

original number 125

No. given number is not palindrome number

Show Solution

def palindrome(number):

print("original number", number)

original_num = number

# reverse the given number

reverse_num = 0

while number > 0:

reminder = number % 10

reverse_num = (reverse_num * 10) + reminder

number = number // 10

# check numbers

if original_num == reverse_num:

print("Given number palindrome")

else:

print("Given number is not palindrome")

palindrome(121)

palindrome(125)

Exercise 10: Merge two lists using the following


condition
Given two lists of numbers, write a Python code to create a new list such that the latest list
should contain odd numbers from the first list and even numbers from the second list.

Given:

list1 = [10, 20, 25, 30, 35]

list2 = [40, 45, 60, 75, 90]

Expected Output:

result list: [25, 35, 40, 60, 90]

Show Solution

def merge_list(list1, list2):

result_list = []

# iterate first list

for num in list1:

# check if current number is odd

if num % 2 != 0:

# add odd number to result list

result_list.append(num)

# iterate second list

for num in list2:

# check if current number is even

if num % 2 == 0:

# add even number to result list

result_list.append(num)

return result_list

list1 = [10, 20, 25, 30, 35]


list2 = [40, 45, 60, 75, 90]

print("result list:", merge_list(list1, list2))

Exercise 11: Get each digit from a number in the


reverse order.
For example, If the given integer number is 7536, the output shall be “6 3 5 7“, with a space
separating the digits.

Show Solution

number = 7536

print("Given number", number)

while number > 0:

# get the last digit

digit = number % 10

# remove the last digit and repeat the loop

number = number // 10

print(digit, end=" ")

Exercise 12: Calculate income tax


Calculate income tax for the given income by adhering to the rules below

Taxable Income Rate (in %)

First $10,000 0

Next $10,000 10

The remaining 20

Expected Output:
For example, suppose the income is 45000, and the income tax payable is

10000*0% + 10000*10% + 25000*20% = $6000.

Show Solution

income = 45000

tax_payable = 0

print("Given income", income)

if income <= 10000:

tax_payable = 0

elif income <= 20000:

# no tax on first 10,000

x = income - 10000

# 10% tax

tax_payable = x * 10 / 100

else:

# first 10,000

tax_payable = 0

# next 10,000 10% tax

tax_payable = 10000 * 10 / 100

# remaining 20%tax

tax_payable += (income - 20000) * 20 / 100

print("Total tax to pay is", tax_payable)

Exercise 13: Print multiplication table from 1 to 10


Expected Output:

1 2 3 4 5 6 7 8 9 10

2 4 6 8 10 12 14 16 18 20

3 6 9 12 15 18 21 24 27 30

4 8 12 16 20 24 28 32 36 40

5 10 15 20 25 30 35 40 45 50

6 12 18 24 30 36 42 48 54 60

7 14 21 28 35 42 49 56 63 70

8 16 24 32 40 48 56 64 72 80

9 18 27 36 45 54 63 72 81 90

10 20 30 40 50 60 70 80 90 100

Show Solution

for i in range(1, 11):

for j in range(1, 11):

print(i * j, end=" ")

print("\t\t")

Exercise 14: Print a downward half-pyramid


pattern of stars

*****

****

***

**
*

Show Solution

for i in range(6, 0, -1):

for j in range(0, i - 1):

print("*", end=' ')

print(" ")

Exercise 15: Get an int value of base raises to


the power of exponent
Write a function called exponent(base, exp) that returns an int value of base raises to the power
of exp.

Note here exp is a non-negative integer, and the base is an integer.

Expected output

Case 1:

base = 2

exponent = 5

2 raises to the power of 5: 32 i.e. (2 *2 * 2 *2 *2 = 32)

Case 2:

base = 5

exponent = 4

5 raises to the power of 4 is: 625


i.e. (5 *5 * 5 *5 = 625)

def exponent(base, exp):

num = exp

result = 1

while num > 0:

result = result * base

num = num - 1

print(base, "raises to the power of", exp, "is: ", result)

exponent(5, 4)

Common questions

Powered by AI

To write a Python code that returns the product of two integers if the product is less than or equal to 1000; otherwise, return their sum, the conditional logic is implemented as follows: Firstly, calculate the product of the two numbers. Then, use an 'if' statement to check if the product is less than or equal to 1000. If true, return the product; if false, return the sum. For example, the function 'multiplication_or_sum' takes two inputs, calculates their product, and checks if it meets the specified condition .

To accomplish this, initialize a variable for the previous number starting at 0, and iterate over a range of numbers. In each iteration, add the current number to the previous, print the result, and then update the previous number to the current number for the next iteration. This logic enables the sequence production in the expected pattern as demonstrated in the code provided .

To compute income tax based on provided rates, segment the income into brackets: the first $10,000 at 0%, the next $10,000 at 10%, and any remainder beyond $20,000 at 20%. For an income of $55,000, tax is calculated as 0 for the first $10,000, $1,000 for the next $10,000, and $7,000 from the remaining $35,000, totaling $8,000 in tax .

To reverse a number in Python, repeatedly extract the last digit using modulus '%', append it to the reverse result, and then remove it by performing integer division '//'. A number is considered a palindrome if the original number equals the reversed number. In the implementation shown, reversing is done in a loop and compared for equality to determine the result .

To generate a multiplication table from 1 to 10, employ two nested loops: the outer loop for the multiplicands and the inner loop for the multipliers. Multiply the current indices of both loops and format the output using 'end=" "' to ensure each row stays on a single line before proceeding to the next one with a new print statement to separate them .

To check for numbers divisible by 5 in a list, iterate through the list and use the modulus operator to determine divisibility. If 'num % 5 == 0' evaluates to true, it indicates divisibility. By applying this to the list [10, 20, 33, 46, 55], the numbers 10, 20, and 55 meet the condition, thus these are printed .

In Python, the 'count' method of the string class is used to determine the number of occurrences of a substring in a string. Applying it to count 'Emma' in 'Emma is a good developer. Emma is a writer' yields a result of 2, indicating the substring appears twice .

To write a Python function that removes the first 'n' characters from a string, ensure 'n' is less than the string’s length to avoid errors. The function 'remove_chars' accepts a string and an integer 'n', then uses slicing to return a substring from index 'n' to the end of the string. For example, 'remove_chars("PYnative", 4)' would return 'tive' .

In the pattern exercise, nested loops are used to print the pattern. The outer loop runs from 1 to 5, and for each number, the inner loop prints that number as many times as its value. For example, '1' is printed once, '2' twice, and so on, up to '5' printed five times each on a new line. The Python code iterates over a range, using 'end=" "' to format correctly .

To merge two lists by extracting odd numbers from the first list and even numbers from the second list, iterate through each list separately. Use a simple 'if' condition to check if the number is odd in the first list or even in the second list before appending it to the result list. The function 'merge_list' demonstrates this approach, handling both lists separately and creating a new list containing required elements .

You might also like