PYnative

Python Programming

  • Learn Python
    • Python Tutorials
    • Python Basics
    • Python Interview Q&As
  • Exercises
    • Python Exercises
    • C Programming Exercises
    • C++ Exercises
  • Quizzes
  • Code Editor
    • Online Python Code Editor
    • Online C Compiler
    • Online C++ Compiler
Home » Python Exercises » Python Basic Exercise for Beginners: 40 Coding Problems with Solutions

Python Basic Exercise for Beginners: 40 Coding Problems with Solutions

Updated on: February 8, 2026 | 527 Comments

This Python exercise for beginners is designed to help you practice and improve your coding skills. This page contains over 40 Python exercises curated for beginners.

Each exercise includes a clear problem, a helpful hint, a complete solution, and a detailed explanation. This ensures you not only solve the problem but also understand why the solution works.

Also, See:

  • Python Exercises: A set of 17 topic specific exercises
  • Python Quizzes: Solve quizzes to test your knowledge of fundamental concepts.
  • Basic Python Quiz for beginners
  • Python Basics: Learn the basics of Python to solve this exercise.
  • Beginner Python Interview Questions

Tips and essential learning resources accompany each question. These will help you solve the exercise and become more familiar with Python basics.

This Python exercise covers questions on the following topics:

  • Python for loop and while loop
  • Python list, set, tuple, dictionary, input, and output
  • Use Online Python Code Editor to solve exercises.

Let us know if you have any alternative solutions in the comments section below. This will help other developers.

+ Table of Contents (40 Exercises)

Table of contents

  • Exercise 1. Arithmetic Product and Conditional Logic
  • Exercise 2. Cumulative Sum of a Range
  • Exercise 3. String Indexing and Even Slicing
  • Exercise 4. String Slicing and Substring Removal
  • Exercise 5. Variable Swapping (The In-Place Method)
  • Exercise 6. Calculating Factorial with a Loop
  • Exercise 7. List Manipulation: Add and Remove
  • Exercise 8. String Reversal
  • Exercise 9. Vowel Frequency Counter
  • Exercise 10. Finding Extremes (Min/Max) in a List
  • Exercise 11. Removing Duplicates from a List
  • Exercise 12. List Comparison and Boolean Logic
  • Exercise 13. Filtering Lists with Conditional Logic
  • Exercise 14. Substring Frequency Analysis
  • Exercise 15. Nested Loops for Pattern Generation
  • Exercise 16. Numerical Palindrome Check
  • Exercise 17. Merging Lists with Parity Filtering
  • Exercise 18. Integer Digit Extraction and Reversal
  • Exercise 19. Multi-Tiered Income Tax Calculation
  • Exercise 20. Nested Loops for Multiplication Tables
  • Exercise 21. Downward Half-Pyramid Pattern
  • Exercise 22. Custom Exponentiation Function
  • Exercise 23. Check Palindrome Number
  • Exercise 24. Generate Fibonacci Series
  • Exercise 25. Check Leap Year
  • Exercise 26. Merging Two Dictionaries
  • Exercise 27. Finding Common Elements (Intersections)
  • Exercise 28. Odd/Even List Splitter
  • Exercise 29. Word Length Analysis
  • Exercise 30. Word Frequency Counter (The Histogram)
  • Exercise 31. Print Alternate Prime Numbers
  • Exercise 32. Dictionary of Squares (Mapping Logic)
  • Exercise 33. Character Replacer (Data Sanitization)
  • Exercise 34. Print Reverse Number Pattern
  • Exercise 35. Digit Detection in Strings
  • Exercise 36. Capitalize First Letter (Title Case)
  • Exercise 37. Simple Countdown Timer
  • Exercise 38. File Creation and Basic I/O
  • Exercise 39. External File Word Counter
  • Exercise 40. Introduction to Classes (OOP)

Exercise 1. Arithmetic Product and Conditional Logic

Practice Problem: Write a Python function that accepts two integer numbers. If the product of the two numbers is less than or equal to 1000, return their product; otherwise, return their sum.

Exercise Purpose: Learn basic control flow and the use of if-else statements. Understand how code decisions change output based on a mathematical threshold.

Given Input:

  • Case 1: number1 = 20, number2 = 30
  • Case 2: number1 = 40, number2 = 30

Expected Output:

  • The result is 600
  • The result is 70

Refer:

  • Accept user input in Python
  • Calculate an Average in Python
Hint
  • Define a function that calculates the product two given numbers.
  • Use an if statement to compare that product against 1000 to decide whether to return the product or the sum.
Solution
def multiplication_or_sum(num1, num2):
    # Calculate product
    product = num1 * num2
    
    # Check if product is within the threshold
    if product <= 1000:
        return product
    else:
        return num1 + num2

# Testing Case 1
result = multiplication_or_sum(20, 30)
print("The result is", result)

# Testing Case 2
result = multiplication_or_sum(40, 30)
print("The result is", result)Code language: Python (python)

Explanation to Solution:

  • Function Definition: The code uses def to create a reusable block of logic, Inside the function multiply these two numbers and store their product in a variable.
  • Conditional Branching: The if product <= 1000 line acts as a gatekeeper, routing the program’s logic based on the calculated value.
  • Return Values: Instead of just printing, the function returns the value, allowing the calling code to decide how to display or use the result.

Exercise 2. Cumulative Sum of a Range

Practice Problem: Iterate through the first 10 numbers (0–9). In each iteration, print the current number, the previous number, and their sum.

Exercise Purpose: This exercise teaches “State Tracking.” In programming, you often need to remember a value from a previous loop iteration to calculate results in the current one. This is the basis for algorithms like Fibonacci sequences or running totals.

Given Input: Range: numbers = range(10)

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 8 Previous Number 7 Sum: 15
Current Number 9 Previous Number 8 Sum: 17

Reference article for help:

  • Python range() function
  • Calculate sum and average in Python
Hint
  • Initialize a variable previous_num to 0 outside the loop.
  • At the end of each loop iteration, update previous_num with the value of the current_num.
Solution
print("Printing current and previous number sum in a range(10)")
previous_num = 0

# Loop from 0 to 9
for i in range(10):
    x_sum = previous_num + i
    print(f"Current Number {i} Previous Number {previous_num} Sum: {x_sum}")
    
    # Update previous_num for the next iteration
    previous_num = iCode language: Python (python)

Explanation to Solution:

  • Initialization: previous_num = 0 is set outside the loop so it persists across iterations.
  • for loop Iteration: The for i in range(10) loop automatically increments i from 0 to 9.
  • Next, display the current number (i), the previous number, and the addition of both numbers in each iteration of the loop.
  • State Update: The line previous_num = i is critical; it “shifts” the current value into the “memory” slot for the next cycle of the loop.

Exercise 3. String Indexing and Even Slicing

Practice Problem: Display only those characters which are present at an even index number in given string.

Exercise Purpose: Understand how data is stored in memory using zero-based indexing. In most languages, the first character is at position 0, the second at 1, and so on. Mastering indexing is vital for data parsing.

Given Input: String: "pynative"

Expected Output:

Original String is  pynative
Printing only even index chars
p
n
t
v
Hint
  • You can solve this using a for loop with a range that steps by 2. Iterate through the characters of the string using a loop and the range() function.
  • Use start = 0, stop = len(s) - 1, and step = 2. The step is 2 because we want only even index numbers.
  • Or by using Python’s built-in string slicing syntax [::2].
Solution
word = "pynative"
print("Original String is ", word)

# Method: Using list slicing
# format: [start:stop:step]
even_chars = word[0::2]

print("Printing only even index chars")
for char in even_chars:
    print(char)Code language: Python (python)

Explanation to Solution:

  • Zero-based Indexing: The character ‘p’ is at index 0, ‘y’ is at 1, ‘n’ is at 2.
  • Slicing [0::2]: This is a powerful Python feature. It tells the program: “Start at index 0, go to the end, and skip every 2nd character.”
  • Iteration: The for char in even_chars loop processes the resulting subset of characters individually.

Solution 2: Using loop

# 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])Code language: Python (python)

Exercise 4. String Slicing and Substring Removal

Practice Problem: Write a function to remove characters from a string starting from index 0 up to n and return a new string.

Exercise Purpose: This exercise demonstrates how to truncate data strings, a common data-cleaning task.

Given Input:

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

Expected Output:

  • tive
  • native
Hint
  • Use string slicing to get a substring
  • To remove the first n characters, you essentially want to keep everything from index n to the end of the string: string[n:].
Solution
def remove_chars(word, n):
    print('Original string:', word)
    # Extract string from index n to the end
    res = word[n:]
    return res

print("Removing characters from a string")
print(remove_chars("pynative", 4))
print(remove_chars("pynative", 2))Code language: Python (python)

Explanation to Solution:

  • Slicing word[n:]: By omitting the “stop” value in the slice, Python defaults to the very end of the string.
  • Flexibility: The function is designed to take n as an argument, making it reusable for any length of removal.
  • Memory: Note that strings in Python are immutable; this function doesn’t change the original string but creates and returns a new truncated version.

Also, try to solve Python string exercises

Exercise 5. Variable Swapping (The In-Place Method)

Practice Problem: Write a program to swap the values of two variables, a and b, without using a third temporary variable.

Exercise Purpose: This exercise will help you learn about memory efficiency and Python’s special tuple unpacking feature. In other languages like C or Java, you need a temporary variable to swap values safely. In Python, you can swap values in one line without risking data loss.

Given Input: a = 5, b = 10

Expected Output:

Before Swap: a = 5, b = 10
After Swap: a = 10, b = 5
Hint
  • In Python, you can use the syntax a, b = b, a.
  • This evaluates the right side (creating a tuple) and then assigns the values back to the left side simultaneously.
Solution
a = 5
b = 10
print(f"Before Swap: a = {a}, b = {b}")

# Simultaneous assignment (Tuple Unpacking)
a, b = b, a

print(f"After Swap: a = {a}, b = {b}")Code language: Python (python)

Explanation to Solution:

  • Simultaneous Evaluation: Python evaluates the entire right side (b, a) first, essentially holding both values in a temporary hidden structure (a tuple).
  • Assignment: It then unpacks those values into the variables on the left. This prevents the value of a from being overwritten by b before its original value can be moved.
  • Clean Code: This eliminates the need for three lines of code and an extra “temp” variable, making the script more readable.

Exercise 6. Calculating Factorial with a Loop

Practice Problem: Write a program that calculates the factorial of a given number (e.g., 5!) using a for loop.

Exercise Purpose: This exercise explores “Mathematical Accumulation.” A factorial (e.g., 5! = 5*4*3*2*1) requires you to maintain a running product across multiple iterations, which is a core pattern in scientific computing.

Given Input: number = 5

Expected Output: The factorial of 5 is 120

Hint
  • Initialize a factorial variable to 1.
  • Loop through a range from 1 to the given number, multiplying the factorial variable by the current loop index at each step.
Solution
num = 5
factorial = 1

# Loop from 1 to num (inclusive)
for i in range(1, num + 1):
    factorial = factorial * i

print(f"The factorial of {num} is {factorial}")Code language: Python (python)

Explanation to Solution:

  • Identity Element: We start factorial at 1 because multiplying by zero would ruin the entire calculation.
  • range(1, num + 1): Since the end of a range is exclusive, we use + 1 to ensure the loop includes the number 5.
  • Running Product: Each pass of the loop updates the value of factorial, building the final result step-by-step.

Exercise 7. List Manipulation: Add and Remove

Practice Problem: Create a list of 5 fruits. Add a new fruit to the end of the list, then remove the second fruit (at index 1).

Exercise Purpose: This exercise teaches “Dynamic Collection Management.” Lists are rarely static; being able to modify, expand, and prune them is essential for handling data like shopping carts, user lists, or inventory systems.

Given Input: fruits = ["apple", "banana", "cherry", "date", "elderberry"]

Expected Output: ['apple', 'cherry', 'date', 'elderberry', 'fig']

Hint
  • Use .append() to add an item to the end
  • and .pop(1) or del to remove the item at the specific index.
Solution
fruits = ["apple", "banana", "cherry", "date", "elderberry"]

# Add a fruit to the end
fruits.append("fig")

# Remove the second fruit (index 1)
fruits.pop(1)

print(fruits)Code language: Python (python)

Explanation to Solution:

  • .append(): This method adds the new item without disturbing the existing order.
  • Zero-Based Indexing: In Python, the “second” item is actually at index 1 (0 is the first).
  • .pop(1): This removes the item at index 1 and “shifts” the remaining items (cherry, date, etc.) to the left to fill the gap, maintaining list integrity.

Exercise 8. String Reversal

Practice Problem: Write a program that takes a string and reverses it (e.g., “Python” becomes “nohtyP”).

Exercise Purpose: This exercise demonstrates “Sequence Slicing.” Strings in Python are sequences, and mastering the slicing syntax is a powerful shortcut for data manipulation that would take 5-10 lines of code in other languages.

Given Input: text = "Python"

Expected Output: Reversed: nohtyP

Hint
  • Use Python’s slicing notation [start:stop:step].
  • Setting the step to -1 tells Python to move through the sequence backwards.
Solution
text = "Python"

# Reversing using slicing
reversed_text = text[::-1]

print(f"Original: {text}")
print(f"Reversed: {reversed_text}")Code language: Python (python)

Explanation to Solution:

  • [::-1]: The first two colons imply “start at the very beginning” and “go to the very end.” The -1 indicates the direction of travel.
  • Immutability: This operation doesn’t change the original text variable; instead, it creates a new string in memory with the characters in reverse order.
  • Efficiency: This is the most efficient way to reverse a string in Python, utilizing optimized internal C code.

Exercise 9. Vowel Frequency Counter

Practice Problem: Write a program to count the total number of vowels (a, e, i, o, u) present in a given sentence.

Exercise Purpose: This exercise introduces “Membership Testing.” By checking if a character belongs to a specific group (the vowels), you learn how to filter data based on categories. This is a fundamental step toward building text-analysis tools or spam filters.

Given Input: sentence = "Learning Python is fun!"

Expected Output: Number of vowels: 6

Hint
  • Define a string containing all vowels "aeiou".
  • Loop through the sentence, convert each character to lowercase to ensure the check is case-insensitive, and increment a counter if the character exists in your vowel string.
Solution
sentence = "Learning Python is fun!"
vowels = "aeiou"
count = 0

# Convert to lowercase to handle 'A' and 'a' equally
for char in sentence.lower():
    if char in vowels:
        count += 1

print(f"Number of vowels: {count}")Code language: Python (python)

Explanation to Solution:

  • .lower(): This is essential for robust code. It ensures that “A” and “a” are both counted without needing to write a massive if statement for both cases.
  • The in Keyword: This is a highly optimized Python operator that checks for the existence of an item within a sequence (the string of vowels).
  • Counter Pattern: We use a simple integer (count) that “accumulates” every time the condition evaluates to True.

Exercise 10. Finding Extremes (Min/Max) in a List

Practice Problem: Given a list of integers, find and print both the largest and the smallest numbers.

Exercise Purpose: This exercise explores “Aggregate Functions.” While Python has built-in tools for this, understanding how to identify extremes is critical for data normalization, where you often need to find the range of a dataset before processing it.

Given Input: nums = [45, 2, 89, 12, 7]

Expected Output: Largest: 89 Smallest: 2

Hint
  • Python provides the max() and min() functions which iterate through a collection and return the extreme values in O(n) time.
Solution
nums = [45, 2, 89, 12, 7]

largest = max(nums)
smallest = min(nums)

print(f"Largest: {largest}")
print(f"Smallest: {smallest}")Code language: Python (python)

Explanation to Solution:

  • max(nums): Internally, this function assumes the first element is the largest, then compares it against every other element in the list, updating the “current winner” as it goes.
  • min(nums): Works identically to max, but tracks the lowest value found.
  • Algorithm Efficiency: These functions only need to pass through the list once, making them very fast even for lists with millions of items.

Exercise 11. Removing Duplicates from a List

Practice Problem: Write a script that takes a list containing duplicate items and returns a new list with only unique elements.

Exercise Purpose: This exercise teaches “Data De-duplication.” In real-world data science, datasets are often “messy” with repeating entries. Mastering the conversion between Lists (which allow duplicates) and Sets (which do not) is the fastest way to clean data.

Given Input: data = [1, 2, 2, 3, 4, 4, 4, 5]

Expected Output: Unique List: [1, 2, 3, 4, 5]

Hint

The easiest way to remove duplicates in Python is to convert the list into a set(), then convert it back into a list().

Solution
data = [1, 2, 2, 3, 4, 4, 4, 5]

# Set conversion removes duplicates automatically
unique_data = list(set(data))

print(f"Unique List: {unique_data}")Code language: Python (python)

Explanation to Solution:

  • set(data): A Set is a collection where every element must be unique. When you pass a list into a set, Python automatically discards any value it has already seen.
  • list(...): Since sets are unordered and do not support indexing, we convert the result back into a list so we can use it in standard list operations later.
  • Ordering Note: Converting to a set usually loses the original order of items. If order matters, you would need a loop or a dict.fromkeys() approach.

Exercise 12. List Comparison and Boolean Logic

Practice Problem: Write a function to return True if the first and last number of a given list is the same. If the numbers are different, return False.

Exercise Purpose: This exercise introduces “Collection Indexing” and “Boolean Flags.” Comparing data structure boundaries is common in pattern matching and data integrity checks.

Given Input:

  • numbers_x = [10, 20, 30, 40, 10]
  • numbers_y = [75, 65, 35, 75, 30]

Expected Output:

Given list: [75, 65, 35, 75, 30] | result is False
Given list: [10, 20, 30, 40, 10] | result is True
Hint

Use index 0 to access the first element and index -1 to access the very last element of the list.

Solution
def first_last_same(number_list):
    print("Given list:", number_list)
    
    first_num = number_list[0]
    last_num = number_list[-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))Code language: Python (python)

Explanation to Solution:

  • Negative Indexing: Python allows [-1] to represent the last item in a list regardless of the list’s length. This is safer and cleaner than calculating len(list) - 1.
  • Equality Operator (==): This operator compares the values of the two objects and evaluates to a Boolean (True/False).
  • Logic Gate: The function provides a clear binary answer based on the structural properties of the input list.

Exercise 13. Filtering Lists with Conditional Logic

Practice Problem: Iterate through a given list of numbers and print only those numbers which are divisible by 5.

Exercise Purpose: This exercise teaches the use of the modulo operator (%) and loop filtering. In data processing, you often need to sift through large datasets to extract subsets that meet mathematical criteria.

Given Input: num_list = [10, 20, 33, 46, 55]

Expected Output:

Divisible by 5:
10, 20, 55
Hint
  • Use a for loop to go through each number.
  • Inside the loop, check if number % 5 == 0. If the remainder is zero, the number is divisible by 5.
Solution
num_list = [10, 20, 33, 46, 55]
print("Given list is", num_list)
print("Divisible by 5:")

# Iterate through each element
for num in num_list:
    # Check divisibility
    if num % 5 == 0:
        print(num)Code language: Python (python)

Explanation to Solution:

  • for num in num_list: This construct allows the program to visit every item in the collection without needing to track indices manually.
  • num % 5 == 0: The modulo operator returns the remainder. If the remainder of division by 5 is 0, the number is a multiple of 5.
  • Filtering Logic: Only when the if condition evaluates to True does the print function execute, effectively “filtering” the list.

Also, try to solve Python list Exercise

Exercise 14. Substring Frequency Analysis

Practice Problem: Write a program to find how many times the substring “Emma” appears in a given string.

Exercise Purpose: Text analysis and pattern matching are core pillars of programming. This exercise introduces searching for a “needle in a haystack,” a fundamental concept for building search engines or data validation tools.

Given Input:

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

Expected Output: Emma appeared 2 times

Hint

Python strings have a built-in method called .count() that can search for occurrences of a specific sequence of characters.

Solution
str_x = "Emma is good developer. Emma is a writer"
count = str_x.count("Emma")
print(f"Emma appeared {count} times")Code language: Python (python)

Explanation to Solution:

  • str_x.count("Emma"): This is a high-level abstraction that handles the complex logic of scanning the string and incrementing a counter internally.
  • Case Sensitivity: Note that string methods like count are case-sensitive; searching for “emma” (lowercase) would return 0.

Exercise 15. Nested Loops for Pattern Generation

Practice Problem: Print the following pattern where each row contains a number repeated a specific number of times based on its value.

1 
2 2
3 3 3
4 4 4 4
5 5 5 5 5

Exercise Purpose: Pattern printing is a classic way to learn “Nested Loops.” You coordinate an outer loop for rows and an inner loop for columns or repetitions. This improves spatial logic and control over output formatting.

Given Input: Range: 1 to 5

Expected Output: (The pattern shown above)

Refer:

  • Print Pattern using for loop
  • Nested loops in Python
Hint
  • The outer loop should iterate from 1 to 5.
  • The inner loop should repeat the current number of the outer loop based on its value (e.g., when the outer number is 3, the inner loop runs 3 times).
Solution
# Outer loop for rows
for num in range(1, 6):
    # Inner loop for repetition
    for i in range(num):
        print(num, end=" ") # end=" " keeps it on the same line
    # New line after each row
    print("\n")Code language: Python (python)

Explanation to Solution:

Notice that each row contains the same number repeated, and the number of repetitions increases with the row number.

  • Nested Loops: The outer loop num sets the “context” for the row. The inner loop i performs the work for that specific row.
  • end=" ": By default, print() adds a newline. Overriding this with a space allows multiple numbers to appear side-by-side.
  • Formatting: The final print("\n") acts as a “carriage return,” starting the next row of the pattern on a clean line.

Exercise 16. Numerical Palindrome Check

Practice Problem: Write a program to check if a given number is a palindrome (reads the same forwards and backwards).

Exercise Purpose: This exercise introduces the idea of “Reversing Logic.” Reversing a string is simple, but reversing an integer takes some math, like using division and modulo, or changing its type. This shows how data types can work differently.

Given Input:

  • Case 1: number = 121
  • Case 2: number = 125

Expected Output:

Number 125 is not palindrome number
Number 121 is palindrome number

Refer: Python Programs to Check Palindrome Number

Hint

Use a simple “Pythonic” way str(number) to convert the number to a string and check if str_num == str_num[::-1].

Solution
def check_palindrome(number):
    print("original number", number)
    # Convert to string to reverse easily
    original_str = str(number)
    reversed_str = original_str[::-1]
    
    if original_str == reversed_str:
        print("Yes. given number is palindrome number")
    else:
        print("No. given number is not palindrome number")

check_palindrome(121)
check_palindrome(125)Code language: Python (python)

Explanation to Solution:

  • str(number): Type casting is used here to transform a math object into a sequence of characters.
  • [::-1]: This is the slice notation for reversing a sequence. It tells Python to step through the entire string backwards.
  • Boolean Comparison: The == operator determines if the two states (original vs. mirror) are identical.

Exercise 17. Merging Lists with Parity Filtering

Practice Problem: Create a new list from two given lists such that the new list contains odd numbers from the first list and even numbers from the second list.

Given Input:

  • list1 = [10, 20, 25, 30, 35]
  • list2 = [40, 45, 60, 75, 90]

Expected Output: [25, 35, 40, 60, 90]

Note: Try to solve the Python list exercises

Hint
  • Create an empty result list.
  • Use two separate loops to iterate through each source list and append only the numbers that satisfy the odd/even condition.
Solution
def merge_list(list1, list2):
    result_list = []
    
    # Get odd numbers from list1
    for num in list1:
        if num % 2 != 0:
            result_list.append(num)
            
    # Get even numbers from list2
    for num in list2:
        if num % 2 == 0:
            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))Code language: Python (python)

Explanation to Solution:

  • result_list = []: Initializing an empty list is a standard pattern for gathering data dynamically.
  • num % 2 != 0: This checks for “not divisible by 2,” effectively finding odd numbers.
  • append(): This method adds elements to the end of the new list, preserving the order in which they were found in the source lists.

Exercise 18. Integer Digit Extraction and Reversal

Practice Problem: Write a program to extract each digit from an integer in the reverse order.

Exercise Purpose: This exercise explores “Mathematical Parsing.” Instead of converting a number to a string, use the modulo operator (%) and floor division (//) to isolate digits. This is common in low-level programming and algorithm challenges where type conversion is restricted.

Given Input: number = 7536

Expected Output: 6 3 5 7

Refer: Python Programs to Reverse an Integer Number

Hint
  • Use number % 10 to get the last digit.
  • Then, use number // 10 to “chop off” that last digit and repeat the process in a loop until the number becomes zero.
Solution
number = 7536
print("Given Number:", number)

while number > 0:
    # Get the last digit
    digit = number % 10
    
    # Remove the last digit from number
    number = number // 10
    
    print(digit, end=" ")Code language: Python (python)

Explanation to Solution:

  • number % 10: This operation returns the remainder of the number divided by 10, which is always the rightmost digit.
  • number // 10: Floor division removes the decimal part, effectively shifting the number one decimal place to the right.
  • end=" ": This keeps the output on a single line, separated by spaces, rather than printing each digit on a new line.

Exercise 19. Multi-Tiered Income Tax Calculation

Practice Problem: Calculate income tax for a given income based on these rules:

  • First $10,000: 0% tax
  • Next $10,000: 10% tax
  • Remaining income: 20% tax

Exercise Purpose: This exercise introduces “Tax Brackets” logic, a classic example of complex conditional branching. It shows how to calculate values cumulatively instead of applying a single percentage to the entire amount.

Given Input: income = 45000

Expected Output: Total income tax to pay is 6000

Hint
  • Subtract the brackets one by one.
  • For an income of 45,000: the first 10k is free, the next 10k is taxed at 10% (1,000), and the remaining 25k is taxed at 20% (5,000).
Solution
income = 45000
tax_payable = 0
print("Given income:", income)

if income <= 10000:
    tax_payable = 0
elif income <= 20000:
    # Tax on first 10k is 0. Tax on the rest is 10%
    tax_payable = (income - 10000) * 10 / 100
else:
    # First 10,000 (0% tax)
    # Next 10,000 (10% tax = 1,000)
    tax_payable = 0 + (10000 * 10 / 100) 
    # Remaining income (20% tax)
    tax_payable += (income - 20000) * 20 / 100

print("Total income tax to pay is", tax_payable)Code language: Python (python)

Explanation to Solution:

  • Cumulative Logic: The code doesn’t just check one condition; it accounts for every bracket the income “passes through.”
  • elif chain: This ensures that only the relevant calculation block is executed based on the total income range.
  • Mathematical Precision: By breaking the calculation into steps, you avoid the common mistake of taxing the entire 45,000 at the highest rate.

Exercise 20. Nested Loops for Multiplication Tables

Practice Problem: Print a multiplication table from 1 to 10 in a formatted grid.

Exercise Purpose: To master “Matrix Generation.” This builds on the nested loop concepts from Exercise 8 and applies them to generate a structured data table. This is essential for understanding how to populate 2D arrays or generate spreadsheets.

Given Input: Range: 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
... (up to 10)

Refer:

  • Nested loops in Python
  • Create Multiplication Table in Python
Hint
  • Use an outer loop for the rows (1 to 10) and an inner loop for the columns (1 to 10).
  • Inside the inner loop, multiply the two loop variables.
Solution
for i in range(1, 11):
    for j in range(1, 11):
        # Print product followed by a tab space
        print(i * j, end="\t")
    print("\n")Code language: Python (python)

Explanation to Solution:

  • range(1, 11): Remember that Python’s range is exclusive of the stop value, so we use 11 to include 10.
  • \t (Tab Character): This is a string escape sequence that ensures the numbers align in neat columns regardless of whether they are one or two digits long.
  • Row/Column Coordination: For every iteration of the outer loop (i), the inner loop (j) completes a full cycle of 1 to 10.

Exercise 21. Downward Half-Pyramid Pattern

Practice Problem: Print a downward half-pyramid pattern using stars (*).

Exercise Purpose: Learn about reverse indexing. Controlling loop boundaries in reverse is important for algorithms that process data from end to beginning.

Given Input: Rows: 5

Expected Output:

* * * * * 
* * * *
* * *
* *
*

Refer:

  • Print Pattern using for loop
  • Nested loops in Python
Hint
  • Use a loop that starts at 5 and ends at 0, moving backwards by -1.
  • In each step, print the star character multiplied by the current loop value.
Solution
# Loop from 5 down to 1
for i in range(5, 0, -1):
    for j in range(0, i):
        print("*", end=" ")
    print("\n")Code language: Python (python)

Explanation to Solution:

  • range(5, 0, -1): The third argument -1 is the “step.” It tells the loop to decrement the value of i in each iteration.
  • String Multiplication (Alternative): In Python, you could also write print("* " * i), which is a more concise “Pythonic” way to repeat characters.
  • Inner Loop Constraint: The inner loop’s range is bound by the current value of the outer loop, causing the line length to decrease over time.

Exercise 22. Custom Exponentiation Function

Practice Problem: Write a function called exponent(base, exp) that returns an integer value of the base raised to the power of the exponent.

Exercise Purpose: Learn about “Accumulator Patterns.” Although Python has a built-in power operator (**), making your own version shows how repeated multiplication works and how functions return results to the main program.

Given Input: base = 2, exp = 5

Expected Output: 2 raises to the power of 5: 32

Hint
  • Initialize a result variable to 1.
  • Use a loop that runs exp times, and in each iteration, multiply the result by the base.
Solution
def exponent(base, exp):
    num = exp
    result = 1
    # Repeat multiplication 'exp' times
    while num > 0:
        result = result * base
        num = num - 1
    print(base, "raises to the power of", exp, "is:", result)

exponent(2, 5)
exponent(5, 4)Code language: Python (python)

Explanation to Solution:

  • Base Case: result starts at 1 because 1 is the identity element for multiplication (anything multiplied by 1 remains itself).
  • The while Loop: This controls the number of multiplications. Each cycle represents one “power.”
  • Function Reusability: By passing base and exp as parameters, the same block of code can calculate 25, 54, or any other combination.

Exercise 23. Check Palindrome Number

Practice Problem: Write a program to check if a given number is a palindrome. A palindrome number remains the same when its digits are reversed (e.g., 121, 545).

Exercise Purpose: This exercise teaches “Algorithmic Reversal.” While strings are easy to reverse in Python, reversing a number mathematically using the modulo (%) and floor division (//) operators deepens understanding of how integers are stored in memory and how to manipulate digits individually.

Given Input: number = 121

Expected Output:

Original number 121
Yes. given number is palindrome number

Refer:

  • Python Programs to Check Palindrome Number
  • Python Programs to Reverse an Integer Number
Hint
  • You can reverse the number by repeatedly extracting the last digit (num % 10) and building a new number.
  • Alternatively, for a “Pythonic” shortcut, convert the integer to a string and use slicing [::-1] to compare it to its original form.
Solution
def check_palindrome(number):
    # Convert to string to easily reverse
    str_num = str(number)
    reverse_str = str_num[::-1]
    
    if str_num == reverse_str:
        print(f"Original number {number}")
        print("Yes. given number is palindrome number")
    else:
        print(f"Original number {number}")
        print("No. given number is not palindrome number")

check_palindrome(121)Code language: Python (python)

Explanation to Solution:

  • str(number): Converts the integer into a sequence of characters so we can treat it like a list.
  • [::-1]: This is the slice notation for “start at the end, end at the beginning, and move backwards by 1.” It effectively mirrors the string.
  • if str_num == reverse_str: A boolean comparison that checks for exact symmetry.

Exercise 24. Generate Fibonacci Series

Practice Problem: Write a program to print the first 15 terms of the Fibonacci series. The sequence starts with 0 and 1, and each subsequent number is the sum of the two preceding ones.

Exercise Purpose: The Fibonacci sequence is a classic way to learn about state management in loops. You keep track of two changing variables at once to find the next number, which helps you see how data moves through each step.

Given Input: Terms = 15

Expected Output: 0 1 1 2 3 5 8 13 21 34 55 89 144 233 377

Refer: Generate Fibonacci Series in Python

Hint
  • Initialize two variables, num1 = 0 and num2 = 1.
  • In each iteration of a loop, the next number is num1 + num2.
  • Then, update num1 to be num2, and num2 to be the new sum.
Solution
num1, num2 = 0, 1
print("Fibonacci series:")

for i in range(15):
    print(num1, end="  ")
    # Calculate next term
    res = num1 + num2
    # Update values for next iteration
    num1 = num2
    num2 = resCode language: Python (python)

Explanation to Solution:

  • num1, num2 = 0, 1: Python’s tuple unpacking allows for clean initialization of multiple variables.
  • res = num1 + num2: This creates the new term based on the current state of the two pointers.
  • num1 = num2 and num2 = res: This “shifts” the window forward by one position, preparing the variables for the next cycle.

Exercise 25. Check Leap Year

Practice Problem: Write a program that takes a year as input and determines if it is a leap year.

A leap year is a year in the Gregorian calendar that contains an extra day, making it 366 days long instead of the usual 365. This extra day, February 29th, is added to keep the calendar synchronized with the Earth’s revolution around the Sun.

Rules for leap years: a year is a leap year if it’s divisible by 4, unless it’s also divisible by 100 but not by 400.

Exercise Purpose: This exercise is vital for mastering “Complex Conditional Logic.” A leap year isn’t just “every 4 years”; there are specific exceptions for century years. This forces the programmer to use nested if statements or compound logical operators (and/or).

Given Input: year = 2024

Expected Output: 2024 is a leap year

Hint
  • A year is a leap year if it is divisible by 4. However, if it is divisible by 100, it is NOT a leap year UNLESS it is also divisible by 400.
Solution
def is_leap(year):
    # Standard Leap Year Logic
    if (year % 4 == 0 and year % 100 != 0) or (year % 400 == 0):
        print(f"{year} is a leap year")
    else:
        print(f"{year} is not a leap year")

is_leap(2024)
is_leap(2100)Code language: Python (python)

Explanation to Solution:

  • year % 4 == 0: Checks the basic 4-year cycle.
  • year % 100 != 0: Excludes years like 1900 or 2100, which are divisible by 4 but are not leap years.
  • or (year % 400 == 0): The “exception to the exception,” ensuring years like 2000 are correctly identified as leap years.

Exercise 26. Merging Two Dictionaries

Practice Problem: Write a program that takes two separate dictionaries and merges them into one single dictionary.

Exercise Purpose: This introduces “Key-Value Consolidation.” Merging dictionaries is a common task when combining configuration files or user profiles. It also teaches you about “Key Overwriting”—what happens when both dictionaries share the same key.

Given Input:

dict1 = {"name": "Alice", "age": 25}
dict2 = {"city": "New York", "job": "Engineer"}Code language: Python (python)

Expected Output:

{'name': 'Alice', 'age': 25, 'city': 'New York', 'job': 'Engineer'}
Hint
  • In modern Python (3.9+), you can use the union operator | to merge two dictionaries effortlessly.
  • For older versions, the .update() method is used.
Solution
dict1 = {"name": "Alice", "age": 25}
dict2 = {"city": "New York", "job": "Engineer"}

# Modern Python merge (Union Operator)
merged_dict = dict1 | dict2

print(merged_dict)Code language: Python (python)

Explanation to Solution:

  • The | Operator: This creates a new dictionary containing the keys and values of both inputs.
  • Conflict Resolution: If both dictionaries had an “age” key, the value from the second dictionary (dict2) would prevail in the final merge.
  • Immutability: This method preserves the original dict1 and dict2 while creating a third, combined object.

Exercise 27. Finding Common Elements (Intersections)

Practice Problem: Take two lists and find the elements that appear in both. Use Sets to perform the operation.

Exercise Purpose: This exercise explores “Mathematical Set Operations.” Finding intersections is vital for recommendation engines (e.g., finding “mutual friends” or “shared interests”). It demonstrates why using the right data structure (Set) is more efficient than nested loops.

Given Input:

list_a = [1, 2, 3, 4, 5]
list_b = [4, 5, 6, 7, 8]Code language: Python (python)

Expected Output: Common Elements: {4, 5}

Hint
  • Convert both lists to sets.
  • Use the & operator (Intersection) to find the elements that exist in both sets.
Solution
list_a = [1, 2, 3, 4, 5]
list_b = [4, 5, 6, 7, 8]

set_a = set(list_a)
set_b = set(list_b)

# Find common elements using intersection
common = set_a & set_b

print(f"Common Elements: {common}")Code language: Python (python)

Explanation to Solution:

  • set_a & set_b: The ampersand represents the “Intersection” operation. It returns a set containing only items that are present in both set_a AND set_b.
  • Performance: Doing this with sets is significantly faster than using nested for loops, as set lookups are nearly instantaneous (O(1) average case).
  • Result Type: The output is a set {4, 5}, which effectively highlights that we are looking for a unique collection of shared items.

Exercise 28. Odd/Even List Splitter

Practice Problem: Start with a list of 10 numbers. Iterate through them and sort them into two separate lists: one for even numbers and one for odd numbers.

Given Input: numbers = [12, 7, 34, 21, 5, 10, 8, 3, 19, 2]

Expected Output:

Even numbers: [12, 34, 10, 8, 2]
Odd numbers: [7, 21, 5, 3, 19]
Hint
  • Create two empty lists at the start.
  • Use a for loop combined with an if-else statement.
  • Remember, a number is even if num % 2 == 0.
Solution
numbers = [12, 7, 34, 21, 5, 10, 8, 3, 19, 2]
evens = []
odds = []

for num in numbers:
    if num % 2 == 0:
        evens.append(num)
    else:
        odds.append(num)

print(f"Even numbers: {evens}")
print(f"Odd numbers: {odds}")Code language: Python (python)

Explanation to Solution:

  • % 2 == 0: The modulo operator checks for a remainder. If a number divided by 2 has no remainder, it is mathematically even.
  • .append(): This method dynamically grows our target lists as the loop finds matching candidates.
  • Logical Branching: The if-else structure ensures that every number is placed in exactly one category, maintaining the integrity of the original dataset.

Exercise 29. Word Length Analysis

Practice Problem: Create a list of 5 words. Write a loop that iterates through the list and prints each word alongside its character count.

Exercise Purpose: This exercise introduces “Metadata Extraction.” Often, you aren’t just interested in the data itself, but in its properties. In web development, this logic is used to validate if a user’s password or username meets specific length requirements.

Given Input: words = ["Apple", "Banana", "Cherry", "Date", "Elderberry"]

Expected Output:

Apple - 5 Banana - 6 Cherry - 6 Date - 4 Elderberry - 10
Hint

Use a for loop to access each word and the built-in len() function to calculate the number of letters.

Solution
words = ["Apple", "Banana", "Cherry", "Date", "Elderberry"]

for word in words:
    length = len(word)
    print(f"{word} - {length}")Code language: Python (python)

Explanation to Solution:

  • len(): This is a universal Python function that returns the number of items in a sequence (in this case, characters in a string).
  • String Interpolation (f-strings): We use f"{word} - {length}" to create a clean, readable output format that combines variables and static text.
  • Sequential Processing: The loop ensures that the operation is performed on every item in the list automatically, regardless of how many words are added later.

Exercise 30. Word Frequency Counter (The Histogram)

Practice Problem: Write a program that counts how many times each word appears in a given paragraph and stores these counts in a dictionary.

Exercise Purpose: This is a classic “Natural Language Processing” (NLP) task. It teaches you how to map data to occurrences, which is the logic used by search engines to index web pages or by social media platforms to identify trending hashtags.

Given Input: text = "apple banana apple cherry banana apple"

Expected Output: {'apple': 3, 'banana': 2, 'cherry': 1}

Hint
  • Split the text into a list of words.
  • Iterate through the list; if a word is already in the dictionary, increase its value by 1.
  • If it isn’t, add it with a starting value of
Solution
text = "apple banana apple cherry banana apple"
words = text.split()
frequency = {}

for word in words:
    if word in frequency:
        frequency[word] += 1
    else:
        frequency[word] = 1

print(frequency)Code language: Python (python)

Explanation to Solution:

  • .split(): This breaks the string into a list of individual strings, allowing us to process them one by one.
  • Dictionary Membership: if word in frequency checks if the word has already been “seen” by the script.
  • Incrementing Values: By using the word as a key and the count as a value, we create a high-speed lookup table of the paragraph’s content.

Exercise 31. Print Alternate Prime Numbers

Practice Problem: Write a program to find all prime numbers up to 20, but only print every second (alternate) prime number found.

Exercise Purpose: This exercise combines “Nested Loops” (to check for primality) with “Step Logic.” It requires the programmer to first identify a subset of data and then apply a secondary filter, a common task in data reporting.

Given Input: Limit = 20

Expected Output: 2, 5, 11, 17

Refer:

  • Python Programs to Check Prime Number
  • Python Programs to Print alternate Prime Numbers
Hint
  • First, create a list of all primes between 2 and 20.
  • Once the list is complete, use list slicing with a step of 2 (primes[::2]) to print the alternate values.
Solution
primes = []

for num in range(2, 21):
    # Check if number is prime
    for i in range(2, int(num**0.5) + 1):
        if num % i == 0:
            break
    else:
        primes.append(num)

# Print alternate primes
alternate_primes = primes[::2]
print(alternate_primes)Code language: Python (python)

Explanation to Solution:

  • for...else loop: A unique Python feature where the else block executes only if the for loop completes without hitting a break. This is perfect for prime checking.
  • num**0.5: Efficiency trick—you only need to check factors up to the square root of a number.
  • primes[::2]: The slicing engine skips every other element in the list, fulfilling the “alternate” requirement

Exercise 32. Dictionary of Squares (Mapping Logic)

Practice Problem: Create a dictionary where the keys are numbers from 1 to 10 and the values are the squares of those numbers (e.g., 2: 4, 3: 9).

Exercise Purpose: This exercise explores “Data Mapping.” It demonstrates how dictionaries can be used to store pre-calculated mathematical relationships, essentially acting as a “lookup table” that can replace expensive repetitive calculations.

Given Input: Range: 1 to 10

Expected Output:

{1: 1, 2: 4, 3: 9, 4: 16, 5: 25, 6: 36, 7: 49, 8: 64, 9: 81, 10: 100}
Hint
  • Use range(1, 11) and a loop to populate the dictionary.
  • You can assign values using the syntax dict[key] = value.
Solution
squares = {}

for i in range(1, 11):
    squares[i] = i * i

print(squares)Code language: Python (python)

Explanation to Solution:

  • range(1, 11): This provides the “keys” for our dictionary.
  • i * i: This calculates the square of the current number.
  • Key-Value Assignment: The line squares[i] = i * i creates a permanent link between the input number and its squared result within the dictionary structure.

Exercise 33. Character Replacer (Data Sanitization)

Practice Problem: Ask the user for a sentence. Replace every empty space in that sentence with an underscore (_) and print the final result.

Exercise Purpose: This exercise focuses on “String Sanitization.” In web development and file management, spaces are often problematic (especially in URLs or file paths). Learning to replace characters is a critical skill for preparing data for storage or transmission.

Given Input: "I love coding in Python"

Expected Output: I_love_coding_in_Python

Hint

Python strings have a built-in method called .replace(old, new) that scans the entire string and swaps characters for you.

Solution
user_sentence = input("Enter a sentence: ")

# Replace space with underscore
sanitized_sentence = user_sentence.replace(" ", "_")

print(sanitized_sentence)Code language: Python (python)

Explanation to Solution:

  • .replace(" ", "_"): This method is “Global,” meaning it doesn’t just find the first space; it finds every space in the string and replaces it.
  • Immutability: Remember that user_sentence itself isn’t changed; replace() creates a new string which we store in sanitized_sentence.
  • Input Handling: By using input(), the program can handle any sentence the user provides, making it a flexible utility script.

Exercise 34. Print Reverse Number Pattern

Practice Problem: Print a downward number pattern where each row starts with a decreasing value.

Exercise Purpose: In this exercise, you will learn about range control and practice using negative steps in loops to move backwards. This skill is important for algorithms that process data from the end of a file to the beginning.

Given Input: Rows = 5

Expected Output:

5 4 3 2 1 
4 3 2 1
3 2 1
2 1
1

Refer:

  • Print Pattern using for loop
  • Nested loops in Python
Hint
  • You need two loops. The outer loop should start at 5 and go down to 1.
  • The inner loop should start at the current value of the outer loop and go down to 1.
Solution
rows = 5
# Outer loop for number of rows
for i in range(rows, 0, -1):
    # Inner loop for printing numbers in each row
    for j in range(i, 0, -1):
        print(j, end=' ')
    print("") # New lineCode language: Python (python)

Explanation to Solution:

  • range(rows, 0, -1): The -1 argument is the step. It tells Python to count backwards.
  • print(j, end=' '): By overriding the default newline with a space, we keep the numbers on the same horizontal line.
  • print(""): This simple empty print statement acts as a “carriage return” to start the next row of the pattern.

Exercise 35. Digit Detection in Strings

Practice Problem: Write a program to check if a user-entered string contains any numeric digits. Use a for loop to examine each character.

Exercise Purpose: This exercise will help you learn about string traversal and character analysis. In software development, these skills are important for tasks like checking if a username has forbidden characters or if a password is complex enough.

Given Input: input_string = "Python3"

Expected Output: The string 'Python3' contains digits: True

Hint
  • Iterate through the string using a for loop.
  • For each character, use the built-in .isdigit() method.
  • If you find even one digit, you can set a flag to True and break the loop.
Solution
user_input = "Python3"
contains_digit = False

# Iterate through each character
for char in user_input:
    if char.isdigit():
        contains_digit = True
        break  # Exit early since we found one

print(f"The string '{user_input}' contains digits: {contains_digit}")Code language: Python (python)

Explanation to Solution:

  • Flag Pattern: We initialize contains_digit as False. This “flag” only flips if a specific condition is met.
  • .isdigit(): This character method returns True if the character is a numeric value (0-9) and False otherwise.
  • break: This keyword is an efficiency tool. Once a single digit is found, there is no need to check the remaining characters, saving processing time.

Exercise 36. Capitalize First Letter (Title Case)

Practice Problem: Write a program to capitalize the first letter of each word in a given string without using the built-in .title() method.

Exercise Purpose: In this exercise, you will learn about “Tokenization” and “String Re-assembly.” You will split a sentence into words, change them, and then put the sentence back together. This helps you practice working with complex data structures.

Given Input: text = "hello world from python"

Expected Output: Hello World From Python

Hint
  • Use the .split() method to turn the string into a list of words.
  • Loop through the list, use .capitalize() on each word, and then use " ".join() to merge them back into a single sentence.
Solution
text = "hello world from python"

# Split the string into a list of words
words = text.split()
capitalized_words = []

for word in words:
    # Capitalize each word and add to the new list
    capitalized_words.append(word.capitalize())

# Join the list back into a single string
result = " ".join(capitalized_words)
print(result)Code language: Python (python)

Explanation to Solution:

  • .split(): By default, this breaks a string into a list wherever there is a space. "hello world" becomes ["hello", "world"].
  • .capitalize(): This method turns the first character of a string to uppercase and the rest to lowercase.
  • " ".join(): This is the inverse of split. It takes a list and glues the items together using the string it is called on (in this case, a space) as the adhesive.

Exercise 37. Simple Countdown Timer

Practice Problem: Create a countdown timer that starts from a given number and counts down to zero using a while loop.

Exercise Purpose: In this exercise, you will learn about loop termination logic and time delay management. Knowing how to control the flow of your code in real time is important for making animations, game loops, or automated scripts.

Given Input: start_count = 5

Expected Output: 5 4 3 2 1 Blast off!

Hint
  • Use a while loop that continues as long as the counter is greater than 0.
  • Inside the loop, print the current value and then subtract 1 from the counter.
Solution
import time

count = 5

while count > 0:
    print(count)
    # Pause the program for 1 second
    time.sleep(1)
    # Decrement the counter
    count -= 1

print("Blast off!")Code language: Python (python)

Explanation to Solution:

  • while count > 0: This condition ensures the loop runs exactly as many times as specified. Once count hits 0, the condition becomes False and the loop stops.
  • time.sleep(1): This function from the time module pauses execution for one second, making the output feel like a real clock.
  • count -= 1: This is shorthand for count = count - 1. Without this line, the loop would be “infinite” because count would always stay at 5.

Exercise 38. File Creation and Basic I/O

Practice Problem: Write a program that creates a new text file named notes.txt, writes three separate lines of text to it, and then reads that file back to display the contents in the console.

Exercise Purpose: This exercise introduces “Persistent Storage.” Unlike variables that disappear when the program stops, files allow you to save data to the hard drive. Learning the open(), write(), and read() workflow is essential for building logging systems and saving user settings.

Given Input: Lines to write:

  1. “Hello, this is my first note.”
  2. “Python file handling is simple.”
  3. “End of file.”

Expected Output:

notes.txt

Hello, this is my first note.
Python file handling is simple.
End of file.
Hint
  • Use the with open("notes.txt", "w") statement to ensure the file is properly closed after writing.
  • Use the "w" mode for writing and the "r" mode for reading.
Solution
# Part 1: Writing to the file
with open("notes.txt", "w") as file:
    file.write("Hello, this is my first note.\n")
    file.write("Python file handling is simple.\n")
    file.write("End of file.\n")

# Part 2: Reading from the file
print("Reading file contents:")
with open("notes.txt", "r") as file:
    content = file.read()
    print(content)Code language: Python (python)

Explanation to Solution:

  • with open(...): Known as a “Context Manager,” this ensures that Python automatically closes the file even if an error occurs, preventing memory leaks or file corruption.
  • \n: This is the “newline” character. Without it, all three sentences would be squashed together on a single line in the text file.
  • "w" vs "r": The mode "w" (Write) will overwrite the file if it already exists, while "r" (Read) opens it for viewing only.

Exercise 39. External File Word Counter

Practice Problem: Write a script that opens an existing .txt file and counts the total number of words it contains.

Exercise Purpose: This exercise teaches “Data Parsing.” In professional environments, you rarely work with data you typed into the code yourself; you almost always pull data from external sources. This script simulates basic text-mining techniques used to analyze documents or logs.

Given Input:

An external file sample.txt containing: “Coding is the language of the future.”

Expected Output: The file contains 7 words.

Hint
  • Read the entire content of the file into a string, then use the .split() method to break that string into a list of words.
  • The length of that list is your word count.
Solution
# Assuming 'sample.txt' exists with some text
try:
    with open("sample.txt", "r") as file:
        data = file.read()
        words = data.split()
        word_count = len(words)
        print(f"The file contains {word_count} words.")
except FileNotFoundError:
    print("Error: The file 'sample.txt' was not found.")Code language: Python (python)

Explanation to Solution:

  • data.split(): By default, split() breaks a string at every space or newline. This effectively creates a list where every element is a single word.
  • len(words): Since words is now a list, the length of the list directly corresponds to the count of words in the document.
  • try-except: This is a bonus safety feature. If the file is missing, the program won’t “crash” with a scary error; instead, it will print a polite message explaining what happened.

Exercise 40. Introduction to Classes (OOP)

Practice Problem: Create a Car class with attributes for make, model, and year. Include a method called start_engine() that prints a formatted string describing the car starting up.

Exercise Purpose: This exercise introduces Object-Oriented Programming (OOP). Instead of just writing functions, you are creating a “Blueprint” (the Class) to generate “Objects” (the specific cars). This is how modern software is built, allowing you to organize code into logical, reusable components.

Given Input: Make: “Toyota”, Model: “Camry”, Year: 2022

Expected Output: The 2022 Toyota Camry's engine is now running!

Hint

Use the __init__ method to initialize your attributes and the self keyword to refer to the specific instance of the car being used.

Solution
class Car:
    def __init__(self, make, model, year):
        # Setting up attributes
        self.make = make
        self.model = model
        self.year = year

    def start_engine(self):
        # A method that uses the object's attributes
        print(f"The {self.year} {self.make} {self.model}'s engine is now running!")

# Creating an object (an instance of the class)
my_car = Car("Toyota", "Camry", 2022)

# Calling the method
my_car.start_engine()Code language: Python (python)

Explanation to Solution:

  • __init__: This is the “Constructor.” It runs automatically the moment you create a new car, setting its identity (Toyota, Camry, etc.).
  • self: This is a placeholder for the specific object. It tells Python, “use this car’s year” rather than just a generic variable named year.
  • Encapsulation: By grouping the data (attributes) and the actions (methods) together, your code becomes modular and much easier to manage as your program grows.

Filed Under: Python, Python Basics, Python Exercises

Did you find this page helpful? Let others know about it. Sharing helps me continue to create free Python resources.

TweetF  sharein  shareP  Pin

About Vishal

I’m Vishal Hule, the Founder of PYnative.com. As a Python developer, I enjoy assisting students, developers, and learners. Follow me on Twitter.

Related Tutorial Topics:

Python Python Basics Python Exercises

All Coding Exercises:

C Exercises
C++ Exercises
Python Exercises

Python Exercises and Quizzes

Free coding exercises and quizzes cover Python basics, data structure, data analytics, and more.

  • 15+ Topic-specific Exercises and Quizzes
  • Each Exercise contains 25+ questions
  • Each Quiz contains 25 MCQ
Exercises
Quizzes

Comments

  1. Abhinay Soni says

    March 1, 2026 at 1:04 pm

    Thank you so much Vishal Hule, for creating this amazing content, it help a lot.

    Reply
  2. frank carlsen says

    February 22, 2026 at 10:51 pm

    Exercise 39. It seems that the file sample.txt is no longer avaliable or was it meant to be created?

    Traceback (most recent call last):
    File “/home/repl961/main.py”, line 3, in
    with open(“sample.txt”, “r”) as file:
    ^^^^^^^^^^^^^^^^^^^^^^^
    FileNotFoundError: [Errno 2] No such file or directory: ‘sample.txt’

    Reply
    • Abhinay Soni says

      March 1, 2026 at 12:59 pm

      Yes, you need to create the sample.txt before you try to read from it

      Reply
  3. Octivius says

    January 29, 2026 at 11:38 am

    for number 16 i suggest this alternative
    def palindrome(num):
    numeral = num
    num_s = str(num)
    num_r = int(num_s[::-1])
    if numeral == num_r:
    print(f”The number {num} is a palindrome”)
    else:
    print(f”The number {num} is not a palindrome”)
    palindrome(525)
    palindrome(4554)
    palindrome(4543)

    Reply
  4. Prosper Ekhator says

    January 28, 2026 at 1:14 am

    for exercise 2.. i think this is the best way to do it,,,,

    def first_ten_num(num):
    print(f’Printing current and previous number sum in a range({num})’)
    previous_num = 0
    for i in range(num):
    current_num = i
    sum_num = current_num + previous_num
    print(f’Current Number {current_num} Previous Number {previous_num} Sum: {sum_num}’)
    previous_num = current_num

    Reply
  5. Suyash Mishra says

    December 19, 2025 at 12:51 pm

    this is my code for 3rd question:

    n = input()
    for i in n[::2]:
    print(i)

    I am new to code ,pls tell

    Reply
  6. Ufok says

    November 3, 2025 at 3:24 am

    Exercise 18. Don’t ask me how much time it took me to consider casting to bool xD

    def is_leap(y):
    return bool(not y % 4 and y % 100 or not y % 400)

    print(‘*** True’)
    print(is_leap(2400))
    print(is_leap(2404))
    print(‘*** False’)
    print(is_leap(2100))
    print(is_leap(2401))

    Reply
  7. Mehdi Parsa says

    October 21, 2025 at 6:32 pm

    Exercise 20 >>
    a=int(input(‘Enter Range :’))
    for i in range(a, 0, -1):
    print((str(i)+’ ‘)*i+’\n’)

    Reply
  8. Minhaj Shaikh says

    July 17, 2025 at 9:08 pm

    Hey Vishal there is an alternate method of ex.5

    list1 = [10, 20, 25, 30, 35]
    list2 = [40, 45, 60, 75, 90]
    l3=[]
    for i in range(len(list1)):
    if list1[i]%2!=0:
    l3.append(list1[i])
    if list2[i]%2==0:
    l3.append(list2[i])
    print(l3)

    list1 = [10, 20, 25, 30, 35]
    list2 = [40, 45, 60, 75, 90]
    l3=[]
    #print(list(l3))
    for a,b in zip(list1,list2):
    if a%2!=0:
    l3.append(a)
    if b%2==0:
    l3.append(b)
    print(l3)

    Reply
  9. Sai Ganesh J says

    June 26, 2025 at 11:05 pm

    this seems to be a much simple and generalised code, am i wrong vishal?
    a = int(input(“Enter the digit to be reversed : “))
    b = str(a)
    for i in range(len(b)) :
    print(b[len(b)-i-1],” “,end=”)

    Reply
  10. Sai Ganesh J says

    June 26, 2025 at 11:02 pm

    for the 11th question this seems to be a simple method and generalised one too, am i wrong ?
    a = int(input(“Enter the digit to be reversed : “))
    b = str(a)
    for i in range(len(b)) :
    print(b[len(b)-i-1],” “,end=”)

    Reply
  11. Gijs Wiersema says

    June 17, 2025 at 9:04 pm

    For excersise 8, I actually did it with a single for loop:

    def numPyramid(count):
    for i in range(count+1):
    print((str(i)+’ ‘)*i + ‘\n’)
    numPyramid(5)

    I love doing the excersises by the way. It’s a great way to refresh my python knowledge.

    Reply
  12. Yas says

    March 31, 2025 at 12:42 am

    Exercise 9

    number_string = input(“Enter the number : “)
    number_string_reversed = number_string [::-1]
    int(number_string_reversed)

    if number_string_reversed==number_string :
    print(“Yes. given number is palindrome number”)
    else :
    print(“No. given number is not palindrome number”)

    Reply
  13. Yas says

    March 31, 2025 at 12:07 am

    Exercise 3
    name = input(“Enter a string : “)
    x = len(name)
    for i in name :
    print(i)

    Reply
    • kp singh says

      April 9, 2025 at 4:17 pm

      you take a string and after then calculate the length when you use loop then one by one string character print on scrren

      Reply
  14. Srinivas says

    December 25, 2024 at 12:31 pm

    income=int(input(“Income: “))
    taxable_income = (income – 10000)

    if income<=10000:
    print("No Tax")
    elif (0<taxable_income10000:
    slab1 = 10000
    slab2 = taxable_income – 10000
    total_tax= (slab1*10/100)+(slab2*20/100)
    print(“Your tax amount is: “,total_tax)

    Reply
    • Virus says

      February 13, 2025 at 2:50 am

      income = int(input(“Income: “))
      taxable_income = income – 10000

      if income <= 10000:
      print("No Tax")
      elif 0 < taxable_income <= 10000:
      slab1 = 10000
      slab2 = taxable_income
      total_tax = slab1 * 10 / 100 + slab2 * 20 / 100
      print("Your tax amount is: ", total_tax)
      else:
      slab1 = 10000
      slab2 = 10000
      slab3 = taxable_income – 20000
      total_tax = (slab1 * 10 / 100) + (slab2 * 20 / 100) + (slab3 * 30 / 100)
      print("Your tax amount is: ", total_tax)

      Reply
  15. Malcolm says

    November 14, 2024 at 6:29 pm

    These exercises are so helpful! This is the way I solved #15:

    base = int(input(‘Raise ‘))
    power = int(input(‘to the power of ‘))
    print(‘{} raised to the power of {} is {}’.format(base, power, base**power))

    Reply
    • Sai says

      June 28, 2025 at 10:03 pm

      it clearly says create a function, you have created no such functions instead used something simple(not the point of solving the question, its just common sense at this point), stick to the question.

      Reply
  16. sara says

    October 18, 2024 at 11:31 pm

    base=2
    exponent=3
    result1=1
    for i in range(0,exponent):
    result1=base*result1

    print(result1)

    Reply
    • Carlos says

      October 29, 2024 at 12:29 am

      print (“\nExercise 15: power of the exponent”)

      base=2
      exponent=3

      print(base, “raises to the power of “, exponent, “:”, base**exponent, end=” “)

      print(” ( “, end=” “)
      print(base, end=” “)
      for i in range(exponent-1):
      print(” * “, base, end=” “)
      print(” = “, base**exponent, end=” “)
      print(” ) “, end=” “)

      OUTPUT

      Exercise 15: power of the exponent
      2 raises to the power of 3 : 8 ( 2 * 2 * 2 = 8 )

      Reply
    • Sai says

      June 28, 2025 at 10:03 pm

      it clearly says create a function, you have created no such functions instead used something simple(not the point of solving the question, its just common sense at this point), stick to the question.

      Reply
  17. SilentDeath_ says

    September 22, 2024 at 5:05 pm

    def is_palindrome(num):
    str_num = str(num)
    print(f”original number {str_num}”)
    reversed_num = str_num[::-1]
    if str_num == reversed_num:
    print(“Yes. given number is palindrome number”)
    else:
    print(“No. given number is not palindrome”)

    Reply
    • Amine says

      September 26, 2024 at 4:29 am

      we can directly do that:
      def is_palindrome(n):
      if str(n) == str(n)[::-1]:
      return True
      else:
      return False

      print(is_palindrome(121))

      Reply
      • amine says

        November 17, 2024 at 10:24 pm

        We should work this exercice without changing the type to string

        Reply
    • hacker says

      August 12, 2025 at 1:11 pm

      That’s too long use this

      list1 = [1, 2, 1]

      copy_list1 = list1.copy()

      copy_list1.reverse()

      if(copy_list1 == list1):
      print(“Palindrome”)
      else:
      print(“Not Palindrome”)

      Reply
  18. SilentDeath_ says

    September 22, 2024 at 4:20 pm

    #Solution on question number ( 8 ):

    for x in range(n):
    print(f”{x}” * x) #–> The (f”{x}”) will make it a string and multiply it by the number x in the range.

    #It’s move easier like this. What you all think?

    Reply
    • Henry says

      September 23, 2024 at 9:40 am

      for i in range(1, 6):
      print(str(i) * i)

      It’s all in 2 lines

      Reply
  19. yaser says

    August 19, 2024 at 2:42 pm

    solution to the exercise number 6:

    def divisable_numbers():
    numbers = [10,20,34,32,40,25,245]
    print(“Given list is”, numbers)
    print(“Divisable numbers to 5”)
    for numbers in numbers:
    if numbers % 5 == 0:
    print(“.”,numbers)

    divisable_numbers()

    Reply
  20. yaser says

    August 18, 2024 at 12:22 pm

    question number 3:

    word = input(“Enter your string: “)
    print(“The original word is”, word)

    result = word[0::2]
    for _ in result:
    print(_)

    Reply
  21. Hema Suresh says

    August 6, 2024 at 10:57 am

    Ex: 15

    base = int(input(“ENTER BASE”))
    exponent = int(input(“ENTER EXPONENT”))
    res=1
    for i in range(0,exponent,1):
    res=base*res
    print(res)

    Reply
    • Python says

      September 28, 2024 at 2:30 am

      def exponent(b,e):
      return print(pow(b,e))
      exponent(2,5)

      Reply
  22. amir goodarzi says

    July 30, 2024 at 7:17 pm

    the answer of the second exercise is wrong 🙁
    I think this answer is better than yours!
    #this is a program that solve the second exercise

    print(“printing current and pervious number sum in a range(10)”)

    pervious = 0

    for i in range(10):
    pervious = i – 1
    if i == 0 :
    print(“current number %i pervious number %i sum: %i” %(0, 0, 0))
    continue
    print(“current number %i pervious number %i sum: %i” %(i, i-1, i + pervious))

    Reply
  23. amir goodarzi says

    July 30, 2024 at 7:14 pm

    in third exercise , better use f string instead **print(“index[“, i, “]”, word[i])**

    Reply
    • yaser says

      August 18, 2024 at 12:25 pm

      what about this method?

      word = input(“Enter your string: “)
      print(“The original word is”, word)

      result = word[0::2]
      for _ in result:
      print(_)

      Reply
  24. Asher Sajid says

    July 13, 2024 at 9:16 pm

    For exercise 15 we can also do:

    def exponent(base, exp):
    x = pow(base, exp)
    print(x)

    exponent(2, 5)

    Reply
  25. Dariusz says

    June 6, 2024 at 5:11 pm

    task 8

    for x in range(5+1):
    print(f”{x} “*x)

    works for my, and looks cleaner

    Reply
  26. jose placencio says

    May 28, 2024 at 2:18 am

    my answer for the 15 one it is this:

    def exponential(base,exponen):
    print((base)**(exponen))

    the parenthesis if is for acepting both negative and positive numbers

    Reply
  27. Dhamo says

    April 28, 2024 at 1:37 pm

    Exercise 15

    def exponent(base,exp):
    if exp >= 1:
    exponent = base ** exp
    return exponent
    else:
    return f’You have entered a invalid value:{exp}, please enter a valid value’

    Reply
  28. Mayur says

    April 27, 2024 at 2:45 am

    Q.no : 15 in simple way .

    def exponent(base,exp):
    print(‘exponent of given numbers:’,base**exp)

    exponent(2,5)

    Reply
    • mvelo says

      May 23, 2024 at 6:27 pm

      this is a convenient way to accommodate any number from the user according to the instructions given.

      ”’exponent must be positive
      the base must be an integer”

      def integer_check():
      while True:
      base = input(“enter a base: “)
      try:
      value = int(base)
      return value

      except ValueError:
      pass

      def exponent_check():
      while True:
      exponent = input(“enter the exponent: “)
      if exponent.isdigit():
      if int(exponent) > 1:
      return int(exponent)
      else:
      pass
      else:
      pass

      def expression(value, exponent):
      return value ** exponent

      def output():
      base = integer_check()
      exponent = exponent_check()
      result = expression(base, exponent)
      print(f’Base: {base}’)
      print(f’Exponent: {exponent}’)
      print(f”{base} raised to the power of {exponent} is: {result}”)
      print(f”)

      # Run the output function

      Reply
  29. Kriyansh Sinha says

    April 16, 2024 at 4:17 am

    Ex: 14
    for i in range(5,0,-1):
    print(‘*’*i,sep=’ ‘, end=”\n”)

    better code

    Reply
  30. Kriyansh Sinha says

    April 16, 2024 at 4:09 am

    Ex: 14

    for i in range(5,0,-1):
    print(‘*’*i,sep=’ ‘, end=”\n”)

    Reply
  31. Adesayo says

    April 7, 2024 at 10:14 am

    EXERCISE 13 SOLUTION

    for i in range(1, 11):
    for j in range(1, 11):
    print((i * j), end=” “)
    print()

    Reply
  32. Adesayo says

    April 7, 2024 at 9:56 am

    EXECIRSE 12 SOLUTION

    income = int(input(“how much do you earn? “))
    tax_rate = 0

    if income <= 10000:
    tax_rate = 0
    elif income <= 20000:
    tax_rate = (income-10000) * 0.1
    else: # has to be over 20000
    tax_rate = (10000 * 0.1) + ((income-20000) * 0.2)

    print("THE TAX RATE 0N ${} IS ${}".format(income, tax_rate))

    Reply
  33. Sebas says

    April 3, 2024 at 1:27 am

    # Exercise 13: Print multiplication table from 1 to 10
    # the pythonic way
    [[print(x*y, end=” “) for x in range(1,11)] and print() for y in range(1,11)]

    Reply
  34. Narendran says

    March 18, 2024 at 12:34 pm

    print(“Printing current and previous number and their sum in a range(10)”)
    for i in range(10):
    cur = i
    if i == 0:
    pre = i+0
    sum = i+0
    else:
    pre = i-1
    sum = i+pre
    print(f”Current Number {cur} Previous Number {pre} Sum: {sum}”)

    Reply
  35. Fziez says

    February 24, 2024 at 2:31 pm

    why in exercise 3 :

    for i in range(0, size – 1, 2):
    print(“index[“, i, “]”, word[i])

    for loop end at size-1? when I append ‘h’ in pynative it never print

    Reply
    • Yaron says

      March 11, 2024 at 3:30 am

      Thanks man !
      Nice exercises

      Reply
    • Dexter Varquez says

      February 19, 2025 at 2:23 pm

      user_str = input(“Enter a string: “)

      print(“\nOriginal String is”, user_str)
      print(“Printing only even index chars\n”)

      for i in range(0, len(user_str), 2):
      print(user_str[i])

      Reply
  36. Vignesh says

    February 20, 2024 at 7:55 pm

    Excercise 15:
    def exponent(base, exp):
    return base ** exp

    print(exponent(5,4))

    Reply
    • Mukul Chauhan says

      March 11, 2024 at 6:18 pm

      you dont need to print it.
      just pass

      exponent(5,4)

      Reply
  37. Steven Shen says

    February 18, 2024 at 12:21 pm

    Here is my way to do Exercise 15 for matching Expected Output and as a reference to you:
    ————————————————————————————————–
    base,exponent=map(int,input(‘Please input your base & exponent with a “,”: ‘).split(‘,’))
    print(f'{base} raises to the power of {exponent} is: ‘,base**exponent)
    result_list=list(str(base)*exponent)
    for i in range(len(result_list)-1):
    result_list[i] += ‘ *’
    result_list[-1] += ‘ = ‘+str(base**exponent)
    result_str=”.join(result_list)
    print(‘i.e. (%s)’ %result_str)

    Reply
  38. Adam says

    February 15, 2024 at 3:08 pm

    My solutions were almost always different to authors’ suggestions.
    1.
    x = int(input(“What’s number 1 “))
    y = int(input(“What’s number 2 “))
    z = x*y
    if z <= 1000:
    print(z)
    else:
    print(x+y)
    2.
    print("Printing current and previous number sum in a range(10)")
    print("Current Number 0 Previous Number 0 Sum: 0")
    x = 1

    while x < 10:
    print("Current Number", x, "Previous Number ", x-1, " Sum: ", x+x-1)
    x = x+1
    3.
    x = input("Orginal String is ")
    print("Printing only even index chars")
    for i in range(0, len(x), 2):
    print(x[i])
    4.
    def remove_chars(x,y):
    if y <len(x):
    print(x[y:])
    x = input("Give me a phrase: ")
    y = int(input("Give me a length: "))
    remove_chars(x,y)
    5.
    numbers_x = [10, 20, 30, 40, 10]
    numbers_y = [75, 65, 35, 75, 30]
    def first_and_last_the_same(list):
    print("Given list:", list)
    if list[0] == list[len(list)-1]:
    print("Result is true")
    else:
    print("Result is false")

    first_and_last_the_same(numbers_x)
    first_and_last_the_same(numbers_y)
    6.
    list = [10, 20, 33, 46, 55]
    print("Given list is ", list)
    print("Divisible by 5")
    for i in list:
    if i%5 == 0:
    print(i)
    7.
    z=0
    x=0
    str_x = "Emma is good developer. Emma is a writer"
    try:
    while x<len(str_x):

    x = str_x.index("Emma",x)
    x=x+1
    z=z+1

    except ValueError:
    if z == 1:
    print("Emma appeared",z ,"time")
    else:
    print("Emma appeared",z ,"times")
    8.
    x=0
    y=" "
    while x<5:
    x=x+1
    print((str(x)+y)*(x))
    9.
    # check if it is a number
    def check_palindrome(x):
    i=0
    y=len(x)
    while i0:
    list.append(x % 10)
    x = x//10

    for i in list:
    print(i, “”, end=””)
    print(“”, end=”\n”)
    12.
    def cal_tax(income):
    print(“Income: “, income)

    if income <= 10000:
    y=0
    elif income <=20000:
    y = 0.1*(income-10000)
    else:
    y = (1000+(income-20000)*0.2)
    print("Tax:",'${:,.0f}'.format(y))
    x = int(input("Give me your income:"))

    cal_tax(x)

    13.
    x=1
    while x <11:
    y=1
    while y 0:
    print(“* “*x)
    x=x-1
    15.
    x = int(input(“base: “))
    y = int(input(“exponent: “))
    def exponent(base, exp):
    print(base, “raises to the power of”, exp,”is:”, base**exp,”i.e. (“, end=””)
    for i in range (0, exp-1):
    print(base, “*”, end=””)
    i+=1
    print(base,” = “,base**exp,”)”, sep=””)
    exponent(x, y)

    Thank you. it was fun 🙂

    Reply
    • sai says

      June 13, 2024 at 3:45 pm

      for exercise #9 :
      this is way better to understand:
      num=int(input(“enter the number :”))
      print(“original number”, num)
      num_str=str(num)
      if num_str==num_str[::-1]:
      print(“Yes.given number is palindrome number”)
      else:
      print(“No.given number is not palindrome number”)

      Reply
      • Sadegh says

        August 15, 2024 at 4:51 pm

        This is exactly what i did

        Reply
  39. Deepak G says

    February 13, 2024 at 1:10 pm

    Exercise 11:

    n = 7536
    l= ” ”
    for i in str(n):
    l = ” “+i + l
    print(l)

    Reply
  40. bhoomi says

    February 7, 2024 at 7:25 pm

    The alternate way that I found to do Ques. 9

    num = str(input(“Please enter the number: “))
    if num[: :] == num[len(num): :-1]:
    print(“True”,num,”is a palindrome number”)
    else:
    print(“False”,num,”is not a palindrome number”)

    Reply
  41. Manpreet says

    January 29, 2024 at 11:41 am

    Exercise 6: Display numbers divisible by 5 from a list
    l1=[10, 20, 33, 46, 55]
    for num in l1:
    if(num%5==0):
    print(“divisible by 5:”,num)

    Reply
  42. Manpreet says

    January 29, 2024 at 11:40 am

    #Exercise 6: Display numbers divisible by 5 from a list
    l1=[10, 20, 33, 46, 55]
    for num in l1:
    if(num%5==0):
    print(“divisible by 5:”,num)

    Reply
  43. Manpreet says

    January 29, 2024 at 11:20 am

    #Exercise 5: Check if the first and last number of a list is the same
    numbers_x = [10, 20, 30, 40, 10]
    numbers_y = [75, 65, 35, 75, 30]
    if(numbers_x[0]==numbers_x[-1]):
    print(“result is true for number_x”)
    else:
    print(“result is false for number_x”)

    if(numbers_y[0]==numbers_y[-1]):
    print(“result is true for numbers_y”)
    else:
    print(“result is false for numbers_y”)

    Reply
  44. Manpreet says

    January 29, 2024 at 10:41 am

    exercise4:Remove first n characters from a string
    str=”pynative”
    str1=str[4:]
    str2=str[2:]
    print(str1,str2)

    Reply
  45. Manpreet says

    January 29, 2024 at 10:28 am

    exercise3:
    #Print characters from a string that are present at an even index number
    str=”pynative”
    str1=str[0:7:2]
    for i in str1:
    print(i)

    Reply
  46. Al Foy says

    January 22, 2024 at 1:08 am

    This is cool, thank you!

    Exercise 2.

    —————— python code ——————————-
    numb_now = 0
    for each in range( 10 ):
    numb_now = each
    #numb_now = numb_now + 1
    numb_prev = numb_now – 1
    if numb_prev < 0:
    numb_prev = 0
    sum = numb_now + numb_prev
    print( 'Current Number = ', numb_now, 'Previous Number = ', numb_prev, 'Sum:', sum )

    ———————- Output —————————-
    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

    Executed in: 0.02 sec(s)
    Memory: 4236 kilobyte(s)

    Reply
  47. Osama Aftab says

    January 14, 2024 at 11:05 pm

    Exercise 9: Check Palindrome Number
    num1= int(input(‘> ‘))
    num2 = str(num1)[::-1]
    if num1 == int(num2):
    print(‘Yes. given number is palindrome number’)
    else:
    print(‘No. given number is not palindrome number’)

    Reply
  48. Dona Chaudhuri says

    January 7, 2024 at 2:14 am

    #Excercise 15:
    def exponent(base,exp):
    if exp == 0:
    return 1
    else:
    print(“Result: “,base**exp)
    base = int(input(“Enter base: “))
    exp = int(input(“Enter exp: “))

    exponent(base,exp)

    Reply
    • Nethra says

      February 17, 2024 at 9:20 am

      def exe_fifteen():
      base = int(input(“Enter the base num : “))
      exp = int(input(“Enter the exp num : “))
      print(pow(base,exp))
      exe_fifteen()

      Reply
  49. Dona Chaudhuri says

    January 6, 2024 at 12:52 am

    Exercise 9: Check Palindrome Number

    number = input(“Enter a 3 digit number: “)
    print(“Original number “,number)
    reverse_num = str(number[::-1])

    if int(number) == int(reverse_num):
    print(“Yes. given number is palindrome number”)
    else:
    print(“No. given number is not palindrome number”)

    Reply
  50. Pintu says

    January 2, 2024 at 10:06 pm

    ## Print multiplication table from 1 to 10

    def MultiTable(n):
    for i in range(1, n+1):
    for j in range(1, 11):
    print(i*j, end=” “)
    print(“”)

    num = int(input(“Please Enter a value :”))
    obj = MultiTable(num)

    Reply
  51. Talal says

    November 19, 2023 at 11:10 am

    Exercise 14: Print a downward Half-Pyramid Pattern of Star (asterisk)

    for i in range(5, 0, -1):
    print(“*” * i)

    Reply
  52. Talal says

    November 19, 2023 at 11:03 am

    list1 = [10, 20, 25, 30, 35]
    list2 = [40, 45, 60, 75, 90]

    odd = [x for x in list1 if x % 2 != 0]
    even= [x for x in list2 if x % 2 == 0]

    print(odd + even)

    Reply
    • Areena says

      March 16, 2024 at 10:23 pm

      Thanks🌸

      Reply
  53. Talal says

    November 19, 2023 at 10:56 am

    def exponent(base, exp):
    return base**exp
    print(f'{5} raises to the power of {4} is: {exponent(5, 4)}’)

    Reply
    • Pintu says

      January 2, 2024 at 10:03 pm

      def Exponent(base, exp):
      value = base
      for i in range (1, exp) :
      value = value*base
      print(f”The value of {base} to the power {exp} is {value}”)
      print(value)

      b = int(input(“Please enter a int value : “))
      e = int(input(“Please enter a exponent value: “))

      obj = Exponent(b,e)

      Reply
  54. ian says

    November 16, 2023 at 4:55 am

    1.

    number1 = int(input(“Enter value x: “)
    number2 = int(input(“Enter value y: “)

    print(x * y) if x * y <= 1000 else print(x + y)

    Reply
    • Chelly says

      December 9, 2023 at 3:42 pm

      👍👍

      Reply
  55. Clara M says

    October 25, 2023 at 2:13 am

    For Exercise 8, taking advantage of the properties of a string object:

    def number_pyramid(number):

    for i in range(1, number + 1):
    print(str(i)*i)

    Reply
  56. LucasM says

    October 5, 2023 at 3:11 pm

    Exercise 5

    from typing import List

    def is_same(my_list: List[int]) -> bool:
    print(f”Given list: {my_list}”)
    return my_list[0] == my_list[-1]

    def main():
    numbers_x = [10, 20, 30, 40, 10]
    numbers_y = [75, 65, 35, 75, 30]

    print(is_same(numbers_x))
    print(is_same(numbers_y))

    if __name__ == “__main__”:
    main()

    Reply
  57. RGBSupreme says

    September 30, 2023 at 3:38 am

    Exercise 15:

    #Exponent value from user.
    input_exp = input(“Enter a non negative integer for your exponent:”)
    print(“”,input_exp)

    #Base value from user.
    input_base = input(“Enter any integer for your base:”)
    print(“”,input_base)

    #Input value conversions from string to integer.
    exp = int(input_exp)
    base = int(input_base)

    print(” “)

    #Result
    print(“Base integer”, input_base , “to the power of base exp”, input_exp, “is equal to”,base ** exp,”.”)

    Takes input from a user instead.

    Reply
  58. michalx says

    September 8, 2023 at 1:04 am

    Exercise 9: Check Palindrome Number

    Pros: Readable, simple, and straightforward for anyone to understand.
    Cons: Involves converting numbers to strings, which might not be as efficient for very large numbers.

    def is_palindrome(number):
    number_str = str(number)
    palindrome = list(reversed(number_str))
    print(f”Orginal number is: {number}”)
    if list(number_str) == palindrome:
    print(“Yes. the given number is palindrome number”)
    else:
    print(“No. The given number is not palindrome number”)

    is_palindrome(125)

    Reply
    • Gol D. Roger says

      September 15, 2023 at 10:08 pm

      ori_num = input(‘input text or a number’)
      if ori_num == ori_num[::-1]:
      print(‘is a palindrome’)
      else:
      print(‘is not a palindrome’)

      I think this way is more easy

      Reply
      • Phindulo Ratshilumela says

        November 6, 2023 at 1:09 am

        yep agree

        Reply
  59. michal says

    September 8, 2023 at 1:02 am

    Exercise 9: Check Palindrome Number

    Pros: Readable, simple, and straightforward for anyone to understand.
    Cons: Involves converting numbers to strings, which might not be as efficient for very large numbers.

    def is_palindrome(number):
    number_str = str(number)
    palindrome = list(reversed(number_str))
    print(f”Orginal number is: {number}”)
    if list(number_str) == palindrome:
    print(“Yes. the given number is palindrome number”)
    else:
    print(“No. The given number is not palindrome number”)

    is_palindrome(125)

    Reply
    • vishnu pk says

      December 1, 2023 at 6:46 pm

      def paliandrome(number):
      print(“orginal number ” + str(number))
      if str(number)==str(number)[::-1]:
      print(“Yes. given number is palindrome number”)
      else:
      print(“No. given number is not palindrome number”)

      Reply
  60. pullamma says

    July 24, 2023 at 11:41 am

    thanks

    Reply
  61. pullamma says

    July 24, 2023 at 11:39 am

    string = "/*Jon is @developer & musician!!"
    special_symbols = "!@#$%^&*()_+-={}[]|\:;\"',.?/~`"
    for char in special_symbols:
    string = string.replace(char, "#")
    print(string)

    I don’t know this code

    Reply
  62. syb02 says

    July 20, 2023 at 10:31 pm

    Exercise 12:


    income = 25000
    tax = 0
    while income > 10000:
    if income > 20000:
    tax += (income - 20000) * 20/100
    income = 20000
    elif income > 10000:
    tax += (income - 10000) * 10/100
    income = 10000
    print(tax)

    Reply
    • ffrancisco says

      August 16, 2023 at 2:37 pm

      #Newbie ME!
      #for salary above 21K

      x = 10000

      entry = input(“enter salary here: ” )

      deduct1 = ((float(entry) – 10000))
      deduct2 = ((float(deduct1) – 10000 ))

      first_tax = (x * .0)
      second_tax = (x * .1)
      remaining = ((int(deduct2)*.2))
      total_tax = ((float(first_tax) + float(second_tax) + float(remaining)))

      print (x,”x”,”0%”,”+”, x,”x”,”10%”,”+”,remaining,”x”,”25%”, “=”, total_tax)

      Reply
    • Mehnaj Chowdhury says

      August 20, 2023 at 7:10 pm

      def tax_amount(income_amount):
      first=10000
      second=10000
      remains=income_amount-(first+second)
      tax=int(first*0.0+second*0.10+remains*0.20)
      print(tax)
      inp=int(input(“Enter the taxable income: “))
      tax_amount(inp)

      Reply
    • jonjon says

      January 6, 2024 at 12:10 am

      the easy solution for me is from the formula itself:
      print(tax_payable)
      income = 45000
      x = income – 35000
      taxpayable1 = x * 10/100
      b = income – 20000
      taxpayable2 = b *20/100

      total_tax = taxpayable1+ taxpayable2
      print (total_tax)

      Reply
  63. syb02 says

    July 20, 2023 at 10:17 pm

    Exercise 11:


    num = 7536
    reversed_num_str = str(num)[::-1]
    for c in reversed_num_str:
    print(c, end=" ")

    Reply
  64. syb02 says

    July 20, 2023 at 9:32 pm

    Exercise 8:


    row_count = 9
    for i in range(1, row_count + 1):
    print((str(i) + " ") * i)

    Reply
  65. syb02 says

    July 20, 2023 at 9:12 pm

    I think this is a more accurate solution for Exercise 7 -> Solution 2.

    1- There is no need to go through the entire str_x (For example, if the substring you are looking for is 4 characters long, it is pointless to search for it in the 3rd-to-last index of str_x because the largest substring you can get from the 3rd-last index will be 3 characters long.)

    2- There is no need to take all substrings of str_x and compare them. It is sufficient to look only for those whose first character matches the searched phrase’s first character. (I mean, it’s pointless to compare “good” with “Emma”)

    str_x = "Emma is good developer. Emma is a writer"
    substr = "Emma"
    count = 0

    for i in range(len(str_x) - (len(substr) - 1)):
    if str_x[i] == substr[0]:
    count += str_x[i : i + len(substr)] == substr

    print(count)

    Reply
    • syb02 says

      July 20, 2023 at 9:21 pm


      str_x = "Emma is good developer. Emma is a writer"
      substr = "Emma"
      count = 0

      for i in range(len(str_x) - (len(substr) - 1)):
      if str_x[i] == substr[0]:
      count += str_x[i : i + len(substr)] == substr

      print(count)

      Reply
  66. Amir says

    July 12, 2023 at 5:59 pm

    Exercise 15:

    def exp(b,e):
    y = b
    for i in range(1,e):
    b *= y
    return b

    print(exp(5,4))

    Reply
    • Ind01 says

      August 17, 2023 at 7:00 pm

      #newincoding
      we can do in simpliest way:

      def exponent(base,exp):
      new_int=base**exp
      return new_int

      print(exponent(2,5))

      Reply
  67. sfssadf says

    July 12, 2023 at 5:42 pm

    Exo 2 has difference between input code and output printing

    Reply
  68. LNT says

    June 2, 2023 at 3:45 am

    EXERCISE 9 Simpler method:

    def isPalindrome(number):
    if number[::-1] == number:
    return "This is a palindrome"
    else:
    return "This isnt a palindrome"

    Reply
    • Diwakar says

      September 7, 2023 at 12:26 pm

      You will get below error:

      —————————————————————————
      TypeError Traceback (most recent call last)
      Cell In[64], line 11
      7 else:
      9 return “This isnt a palindrome”
      —> 11 isPalindrome(545)

      Cell In[64], line 3, in isPalindrome(number)
      1 def isPalindrome(number):
      —-> 3 if number[::-1] == number:
      5 return “This is a palindrome”
      7 else:

      TypeError: ‘int’ object is not subscriptable

      Reply
  69. Sankar says

    May 25, 2023 at 11:37 am

    EXERCISES 15:–

    def exponent(base, exp):
    i = base
    j = exp
    if j > 0:
    print(f"{i} raises to the power of {j} is: {i**j} ")
    print()

    exponent(2, 5)

    Reply
    • Donald says

      July 4, 2023 at 2:02 pm

      def expo(base,exponent):
      return base**exponent

      expo(2,5)

      Reply
      • Danilo says

        September 28, 2023 at 11:23 am

        def exponent(base, exp):
        print(“base =”, base)
        print(“exponent =”, exp)
        result = 1
        for i in range(exp):
        result *= base
        print(base, “raises to the power of”, exp, “is:”, result)
        exponent(2,5)

        Reply
  70. Trotun says

    May 19, 2023 at 11:03 am

    I think these excercises are very funny. I have looked a lot for something like this. Thanks a lot.

    Reply
  71. Galambos says

    May 2, 2023 at 2:48 am

    Exercise 13 is weird. For some reason, the expected output shows the first column being separated from the second (maybe with tab? not sure), even though the rest of the columns are not aligned.
    On the other hand, the provided solution aligns none of the columns, and, for some reason, inserts 2 tabs at the end of each line.

    My solution:
    for i in range(1, 11):
    for j in range(1, 11):
    # insert tab after every number to keep the columns aligned:
    print(f"{i * j}\t", end=" ")
    # empty print statement breaks the line just fine, no need to insert tabs here:
    print("")

    Reply
    • Galambos says

      May 2, 2023 at 2:55 am

      for i in range(1, 11):
      for j in range(1, 11):
      # insert tab after every number to keep the columns aligned:
      print(f"{i * j}\t", end=" ")
      # empty print statement breaks the line just fine, no need to insert tabs here:
      print("")

      Reply
  72. shreeji patel says

    February 27, 2023 at 8:44 pm

    correction :

    def exponent(base, exp):
    return base**exp

    exponent(2, 5)

    Reply
    • 0xAH says

      March 2, 2023 at 12:10 am

      You did not count this remark:
      ‘Note here exp is a non-negative integer, and the base is an integer.’

      Reply
      • SAI PAVITRA VANGALA says

        April 11, 2023 at 4:51 pm

        Hi! Could you please explain me the question number 15 solution code

        Reply
      • what is this site? says

        June 12, 2023 at 7:50 pm

        ok…
        def exponent(base, exp):
        if exp>0:
        return base**exp
        else:
        return('exp needs to be positive integer')

        exponent(2, 5)

        still way easier than what he wrote

        Reply
    • Vinay Vishwakarma says

      April 27, 2023 at 4:36 pm

      def aaa(base, exponent):
      output = 0
      output = base ** exponent
      return output

      base = 5
      exponent = 4
      aaa(base, exponent)

      Reply
    • ANKUSH Saral says

      May 27, 2023 at 9:20 pm

      It’s good actually.

      Reply
  73. Med_Ka says

    February 26, 2023 at 8:15 pm

    # Exercise 7: Return the count of a given substring from a string

    text = input("Enter the text: ")
    search_word = input("Enter the word to search: ")

    text_lower = text.lower()
    search_word_lower = search_word.lower()

    count = text_lower.count(search_word_lower)

    if count == 0:
    print("The word is not present in the text.")
    else:
    print(f"The word '{search_word}' appears {count} times in the text.")

    Reply
  74. Med_Ka says

    February 26, 2023 at 6:45 pm

    #Exercise 6: Display numbers divisible by 5 from a list

    #Create a list as a global variable
    my_list=[]
    #Function to create a list
    def create_list(n):
    for i in range(n):
    value = int(input("Enter value {}: ".format(i+1)))
    my_list.append(value)
    return my_list
    #Function to divide a string by a number
    def div_by_number(m):
    for i in range(len(my_list)):
    if my_list[i] % m == 0:
    print(my_list[i])

    #Main program

    #insert the number of elements for the list
    x = int(input("How many elements the list must contain ? "))
    Given_list = create_list(x)
    print("Given list is : ", Given_list)

    #enter the divisor :
    y = int(input("The elements of the list are divisible by : "))
    #return the function by printing the elements which are divisible by the number you have chosen
    print("The elements of the Given list which are divisible by ",y ," are : ")
    div_by_number(y)

    Reply
  75. Med_Ka says

    February 26, 2023 at 3:24 am

    Exercise 5: Check if the first and last number of a list is the same

    # Function to create a list
    def create_list(n):
    my_list = []
    for i in range(n):
    value = input("Enter value {}: ".format(i+1))
    my_list.append(value)
    return my_list

    # Function to compare the first and the last element of a list
    def compare_first_last(lst):
    return lst[0] == lst[-1]

    # Insert number of elements and the elements of the list
    x = int(input("Enter the number of elements: "))
    This_List = create_list(x)
    print(This_List)
    Compare = compare_first_last(This_List)
    print(Compare)

    Reply
  76. Issam says

    February 24, 2023 at 5:53 am

    Ex 14
    solution

    for i in reversed(range(6)):
    for j in range(i):
    print('*',end=' ')
    print('\n')

    Reply
  77. steve k says

    February 7, 2023 at 11:54 pm

    I get what the second exercise is doing , new to posting comments or even reading tutorials on the web, but can someone fix the expected output to be what the code solution is or fix the code on exercise 2 to match output. Old QA guy learning python LOL. I iterated over a list instead of a range function but I assume if they change the range to 0,10 it would match expected output.

    Reply
    • Melvin J says

      March 21, 2023 at 5:05 am

      Hey Steve, this was my solution to match the output
      start_num = 10
      print("Printing current and previous number sum in a range(%d)" % (start_num))
      output_txt = "Current Number %d Previous Number %d Sum: %d"

      for count in range(start_num):
      curr_num = count
      prev_num = (curr_num - 1)

      if prev_num < 0:
      prev_num = 0

      total_sum = (curr_num + prev_num)

      print(output_txt % (curr_num,prev_num,total_sum))

      Reply
  78. Iván says

    February 4, 2023 at 5:06 am

    Is this solution right for exercise 8?

    n = 1
    while n <=5:
    print(" ".join((str(n)*n)))
    n+=1

    Reply
  79. Krishna Shyam says

    January 5, 2023 at 10:30 am

    #Write a program to extract each digit from an integer in the reverse order
    def extract(number):
    reverse _ list = []
    for i in number[::-1]:
    reverse _list = i
    print(reverse_ list, end = " ")
    extract(input("enter the digits >> "))

    Is this the right order for the given question?

    Reply
    • akash says

      January 16, 2023 at 1:21 am

      def rev_int(given_int):
      new_int = ""
      for i in range(1, len(given_int)+1):
      new_int += given_int[-i]
      new_int += " "
      return new_int

      print(rev_int("8687"))

      Reply
      • akash says

        January 16, 2023 at 1:22 am

        def rev_int(given_int):
        new_int = “”
        for i in range(1, len(given_int)+1):
        new_int += given_int[-i]
        new_int += ” ”
        return new_int

        print(rev_int(“8687”))

        Reply
        • akash says

          January 16, 2023 at 1:24 am

          def rev_int(given_int):
          new_int = ""
          for i in range(1, len(given_int)+1):
          new_int += given_int[-i]
          new_int += " "
          return new_int

          print(rev_int("8687"))

          Reply
      • Pooky says

        February 15, 2023 at 2:36 am

        Its way easier If you do that in this way:

        stw = (input("Enter your Integer: "))
        revstr = stw[::-1]
        for i in revstr:
        revint = int(i)
        print(i, end=" ")

        Reply
    • manish kumar says

      January 17, 2023 at 5:22 pm

      x=input("Enter the integer")
      for i in x:
      print(x[int(len(x))-int(i)])

      Reply
    • Shahzad Ahmad says

      February 1, 2023 at 5:41 pm

      def reverse_digit(num):
      print('Digit in reverse order: ', end=" ")
      while num > 0:
      remainder = num % 10
      num = num // 10
      print(remainder, end=' ')

      num = int(input('Number: '))
      reverse_digit(num)

      Reply
      • Arca says

        February 27, 2023 at 12:20 am

        a=str(input("original number "))
        for i in range(len(a)):
        if a[i] == a[-(i+1)]:
        reponse=("Yes. given number is palindrome number")
        else:
        reponse=("No. given number is not palindrome number")
        print(reponse)

        Reply
  80. Harlan Silva says

    October 27, 2022 at 7:06 am

    Hi, people!

    I made exercise 9 differently compared with most of the examples here. It’s not in English, but I think it’s possible to understand the logic. Is it worst than the suggested in the solutions?

    # Criar função para identificar palíndromo
    def identificar_palindromo (num: str) -> bool:
    # Criar identificação do primeiro e terceiro números
    num_1 = int(num[0])
    num_3 = int(num[2])
    if num_1 == num_3:
    resultado = True
    print(f"O número escolhido é um palíndromo.\nO primeiro é {num_1} e o terceiro é {num_3}")
    else:
    resultado = False
    print(f"O número escolhido não é um palíndromo.\nO primeiro é {num_1} e o terceiro é {num_3}")
    return resultado

    # Chamar a função através da variável
    num_palindromo = identificar_palindromo(input("Digite um número: "))

    Reply
    • Definitelynot200 says

      November 12, 2022 at 8:30 am

      I think it’s not flexible because you’re just comparing the index 0 and index 2 of the given input. If I just put a 4 digit input with a value of 4144 or a 5 digit input 53235 for example, it will throw true in the 4144 and false in the 53235 which is not. That’s what I think.

      Reply
    • sajib ahamed says

      November 16, 2022 at 1:35 am

      def cheack_palindrome(number):
      print('Original number ',number)
      if str(number) ==str(number)[::-1]:
      print('Yes. given number is palindrome number')
      else:
      print('No. given number is not palindrome number.')

      cheack_palindrome(121)
      cheack_palindrome(125)

      Reply
  81. Zsolt Remenyi says

    October 25, 2022 at 9:33 pm

    Hi,

    Love the site. I think ‘Exercise No. 13’ would look better aligned.

    for x in range(1, 11):
    for y in range(1, 11):
    print(f"{x*y:>4}", end = " ")
    print("\n")

    Reply
  82. Mustafa says

    September 26, 2022 at 4:54 pm

    I finish like this😅

    Exercise 10: Create a new list from a two list using the following condition
    
    list1 = [10, 20, 25, 30, 35]
    list2 = [40, 45, 60, 75, 90]
    list3 = []
    
    for i in list1:
        if i % 2 == 1:
            list3.append(i)
        else:
            continue
    
    for j in list2:
        if j % 10 == 0:
            list3.append(j)
        else:
            continue
    
    print(list3)
    Reply
    • Jig says

      October 9, 2022 at 7:02 pm

      #This will run quick and save your memory
      l1 = [10, 20, 25, 30, 35]
      l2 = [40, 45, 60, 75, 90]
      l3=[]
      for i in l1:
          l3.append(i) if i%2!=0 else l3
      for i in l2:
          l3.append(i) if i%2==0 else l3
      print(l3)
      Reply
    • pyboy says

      October 14, 2022 at 9:47 pm

      ex:15

      def exponent(base, exp):
      print("le numero introduit est ",base, "donc le resultat est", base**exp)

      numeri=exponent(float(input("mettre la base\n")),float(input("mettre l'exp\n")))

      Reply
      • Aman says

        October 15, 2022 at 2:41 pm

        how about this for a solution to question 10

        list1 = [10, 20, 25, 30, 35]
        list2 = [40, 45, 60, 75, 90]
        newlist1 = [i for i in list1 if i%2!=0]
        newlist2 = [i for i in list2 if i%2==0]
        newlist = newlist1 + newlist2
        print(newlist)

        Reply
  83. lily fullery says

    September 24, 2022 at 9:12 pm

    #print the sum of  current and previous number 
    def current_previous():
        cnum = 0
        pnum = 0
        for i in range (10):
            if(i == 0):
                print("currentnumber", 0 ,"and"," previousnum ", 0 , "sum :", 0)
            else:
                cnum = 0 + i 
                pnum = cnum-1
                allover = cnum + pnum
                print("currentnumber", cnum ,"and"," previousnum ", pnum , "sum :", allover)
    current_previous()
    #string from the user and display character that present at an even number 
    
    user = input("enter any word :")
    def evenstring(user):
        for i in range(len(user)):
            if(user.index(user[i])%2 == 0):
                print(user[i])
    evenstring(user)

    —————————————————————————-

    #remove first n characters from a string 
    def first_n(word , n):
        word2 = word[n: ]
        return word2
    word = 'pynative'
    n = 1
    value = first_n(word , n)
    print(value)

    ——————————————————————————

    #Printing stars
    #print the pattern
    n = 6
    a = None
    for i in range(1,n):
        a = (str(i)+" ") * i
        print(a)

    ———————————————————————————-

    #  create a new list from a two list using the following condition
    list1 = [10, 20, 25, 30, 35]
    list2 = [40, 45, 60, 75, 90]
    mylist = []
    for i in list1:
        if(i%2 == 1):
            mylist.append(i)
    for i in list2:
        if(i%2 == 0):
            mylist.append(i)
    
    print("result list : ",mylist)

    ————————————————————————————

    #Write a Program to extract each digit from an integer in the reverse order.
    num = 7536
    strnumber = str(num)
    for i in range(1,len(strnumber)+1):
        a = i-(i+i)
        print(strnumber[a], end='')

    ———————————————————————————-

    ##double nested loop
    for i in range(1,11):
        a = 1
        for i in range(1,11):
            b = a * i
            a = a +1
            print(b, end =' ')

    ——————————————————————————–

    # Print downward Half-Pyramid Pattern with Star
    a = ""
    n = 5
    t = n
    for i in range(n):
        a = '* ' * t 
        t = t - 1
        print(a)
    Reply
    • meera says

      June 8, 2023 at 4:10 pm

      you replied on my birthday

      Reply
  84. vini1955 says

    September 23, 2022 at 3:09 pm

    very helpful.

    Reply
    • Vishal says

      September 26, 2022 at 9:49 am

      I am glad it helped you.

      Reply
  85. Eli says

    September 8, 2022 at 5:47 am

    My solution for exercise 2:

    lst = range(10)
    previous = 0
    
    for value in lst:
        previous = max(value - 1, 0)
        print(f'Current: {value} | Previous: {previous} | Sum: {value + previous}')

    Not sure how that compares functionally with teach’s code

    Reply
    • sajib ahamed says

      November 16, 2022 at 1:38 am

      previous_number = 0
      for i in range(0,10):
      current_number = i
      print('Current Number %d Previous Number %d Sum: %d'%(current_number,previous_number,(current_number+previous_number)))
      previous_number = i

      Reply
  86. Eli says

    September 8, 2022 at 5:43 am

    Vishal, this is great. Thank you so much. It’s exactly what I needed.

    I think that you might have an error in the solution for Ex. 2.
    In the for loop, you define x_sum, but in the print statement, you reference previous_num + i, which is the left side of the equation. I think you meant to reference x_sum there. If I’m wrong about that, please let me know.

    It confused me at first, which was a good thing because I had to figure things out for myself.

    Reply
    • Vishal says

      September 26, 2022 at 9:56 am

      Hi Eli, the x_sum and previous_num + i produce the same result. But for simplicity, i have replaced x_sum with previous_num + i

      Reply
  87. Hardik Saggar says

    September 4, 2022 at 3:56 pm

    # Exercise 15
    base = 2
    exp = 4
    print(f"{base} raises to the power of {exp}: ",base**exp)
    Reply
  88. Taimoor AbdULLAH says

    August 17, 2022 at 1:36 pm

    # Exercise # 15
    
    base = int(input("Base: "))
    exponent = int(input("Exponent: "))
    po = str(base ** exponent)
    exp = ((str(base) + " * ") * exponent).strip()
    print(str(base), "raised to the power of", str(exponent), ":", po, "\ni.e (", exp[:len(exp) - 2], ") = ", po)
    Reply
    • deus says

      September 2, 2022 at 3:03 pm

      def exponent(base,power):
          x=base**power
          print(base, "raises to the power of", power, "is: ", x)
      exponent(5,2)

      valid??

      Reply
      • Hardik Saggar says

        September 4, 2022 at 3:59 pm

        exponent(2,5) which will give you 32 in output
        but here is a simpler way
        base = 2
        exp = 4
        print(f"{base} raises to the power of {exp}: ",base**exp)

        in this you can increase its functionality by taking input from user and code would of lesser lines

        Reply
  89. Taimoor AbdULLAH says

    August 17, 2022 at 12:57 pm

    Here is my 2 line solution for exercise # 14

    # Exercise # 14
    
    for i in range(5, 0, -1):
        print("* " * i)
    Reply
    • Chinuogu David Enweani says

      August 24, 2022 at 10:46 pm

      You a goat bruh

      Reply
      • noname says

        November 15, 2023 at 8:35 pm

        try contributing then

        Reply
    • Mehrdad says

      September 8, 2022 at 11:25 pm

      i = 50
      print('')
      while i > 0 :
          print('* '*i)
          i -= 1
      Reply
  90. Taimoor AbdULLAH says

    August 17, 2022 at 12:30 pm

    # Exercise 12
    i = int(input("Enter income: "))
    tax = 0
    if i <= 1000:
        tax += 0
    elif i <= 2000:
        tax += 1000
    else:
        tax += (i - 20000) * .2 + 1000
    print("Tax Collected:", tax)
    Reply
  91. Taimoor AbdULLAH says

    August 17, 2022 at 12:08 pm

    below is My 2 lines solution for exercise # 11

    i = str(input("Enter an integer:"))
    print("Reverse Integer is:", i[::-1])
    Reply
  92. Taimoor AbdULLAH says

    August 17, 2022 at 12:04 pm

    result = []
    for i in range(2):
        print("Enter List ", i + 1)
        for j in range(5):
            inp = int(input())
            if inp % 2 != 0 and i == 0:
                result.append(inp)
            elif inp % 2 == 0 and i == 1:
                result.append(inp)
    print("Result List", result)
    Reply
    • Taimoor AbdULLAH says

      August 17, 2022 at 12:09 pm

      Exercise # 10 with user input list

      Reply
  93. Shaun says

    August 17, 2022 at 2:27 am

    I was proud to get exercise 13 in one line. I don’t know if it’s the most efficient, but it is just one long line of code.

    
    def exponentExplained(base, exponent):
        print('{0} raised to the power of {1} : {2} i.e. ({3})'.format(base, exponent, base**exponent,'*'.join([x for x in [str(base)]*exponent])))
    
    exponentExplained(2, 5)
    Reply
    • Shaun says

      August 17, 2022 at 2:29 am

      Sorry. This was exercise 15.

      Reply
  94. Anon says

    August 15, 2022 at 4:19 pm

    Here is my solution to exercise 9, did it for any palindromes. Works with numbers too.

    
    word = input('was da word palidrom??: ')
    for check in range(len(word)):
        if word[check] == word[len(word)-check-1]:
            continue
        else:
            print('no')
            quit()
    print('yes')
    Reply
    • Sri says

      August 25, 2022 at 11:05 am

      Hello! Thanks for the insight.
      I am a beginner. I did the palindromes exercise like this

      a = str(input("Please enter the text: "))
      if a[:len(a)] == a[::-1]:
          print ("Palindrome")
      else:
          print ("Not a Palindrome")
      Reply
  95. Sophie says

    August 10, 2022 at 10:46 am

    This is my alternative solution for Exercise 11. I’m still a beginner in Python 😀

     number = 7536
    print("Given number:", number)
    
    str_x = str(number)
    
    for num in str_x[::-1]:
        print(num, end=" ")
    Reply
    • Matt says

      November 17, 2022 at 1:11 pm

      a = 7536
      for i in range(len(str((a)))-1,-1,-1):
      print(str(a)[i],end=" ")

      Reply
  96. Sophie says

    August 10, 2022 at 10:41 am

    This is my alternative solution for Exercise 9. I understood it better this way 🙂

     def palindrome(number):
        print("Original number:", number)
        
        str_x = str(number) 
        original_num = str_x
        reversed_num = str_x[::-1]
        
        if original_num == reversed_num:
            print("Given number is a palindrome,")
            
        else:
            print("Given number is not a palindrome.") 
    Reply
  97. Sahadad HT says

    August 1, 2022 at 8:45 pm

    I’m a beginner in python. I have tried exercise no 13 like this

    
    print("Table of 1-10 \t")
    for i in range(1,11):
        for j in range(1,11):
            print(i,"*",j,"=",i*j,end="\t\t")
        print("\t")

    result

    1 * 1 = 1		1 * 2 = 2		1 * 3 = 3		1 * 4 = 4		1 * 5 = 5		1 * 6 = 6		1 * 7 = 7		1 * 8 = 8		1 * 9 = 9		1 * 10 = 10			
    2 * 1 = 2		2 * 2 = 4		2 * 3 = 6		2 * 4 = 8		2 * 5 = 10		2 * 6 = 12		2 * 7 = 14		2 * 8 = 16		2 * 9 = 18		2 * 10 = 20			
    3 * 1 = 3		3 * 2 = 6		3 * 3 = 9		3 * 4 = 12		3 * 5 = 15		3 * 6 = 18		3 * 7 = 21		3 * 8 = 24		3 * 9 = 27		3 * 10 = 30			
    4 * 1 = 4		4 * 2 = 8		4 * 3 = 12		4 * 4 = 16		4 * 5 = 20		4 * 6 = 24		4 * 7 = 28		4 * 8 = 32		4 * 9 = 36		4 * 10 = 40			
    5 * 1 = 5		5 * 2 = 10		5 * 3 = 15		5 * 4 = 20		5 * 5 = 25		5 * 6 = 30		5 * 7 = 35		5 * 8 = 40		5 * 9 = 45		5 * 10 = 50			
    6 * 1 = 6		6 * 2 = 12		6 * 3 = 18		6 * 4 = 24		6 * 5 = 30		6 * 6 = 36		6 * 7 = 42		6 * 8 = 48		6 * 9 = 54		6 * 10 = 60			
    7 * 1 = 7		7 * 2 = 14		7 * 3 = 21		7 * 4 = 28		7 * 5 = 35		7 * 6 = 42		7 * 7 = 49		7 * 8 = 56		7 * 9 = 63		7 * 10 = 70			
    8 * 1 = 8		8 * 2 = 16		8 * 3 = 24		8 * 4 = 32		8 * 5 = 40		8 * 6 = 48		8 * 7 = 56		8 * 8 = 64		8 * 9 = 72		8 * 10 = 80			
    9 * 1 = 9		9 * 2 = 18		9 * 3 = 27		9 * 4 = 36		9 * 5 = 45		9 * 6 = 54		9 * 7 = 63		9 * 8 = 72		9 * 9 = 81		9 * 10 = 90			
    10 * 1 = 10		10 * 2 = 20		10 * 3 = 30		10 * 4 = 40		10 * 5 = 50		10 * 6 = 60		10 * 7 = 70		10 * 8 = 80		10 * 9 = 90		10 * 10 = 100
    Reply
  98. Ahmed says

    July 31, 2022 at 1:54 pm

    I try to solve exercise 13 in a different way which output looks good

    
    for i in range(1,11):
        for j in range(1,11):
            n = i*j
            if n // 10 == 0:
                print(n,end=' '*2)         
            else: 
                print(n,end=' ')
            
        print()

    the result

    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 
    
    Reply
    • Sri says

      August 25, 2022 at 11:10 am

      Hello. Thanks for the insight.

      I did exercise 13 like this.
      
      x = int(input("What is the number : "))
      y = int(input("Upto which number : "))
      a = range(1,x+1)
      b = range(1,y+1)
      for i in a:
          for v in b:
              lst = (i*v)
              frmt = f"{lst:4.0f}"
              print(frmt,end="")
          print("")
      Reply
    • harshul Patel says

      November 8, 2022 at 5:58 pm

      its look really good . Thank You..:)

      Reply
    • apers says

      June 10, 2024 at 11:17 pm

      “””
      Exercise 14: Print a downward Half-Pyramid Pattern of Star (asterisk)
      * * * * *
      * * * *
      * * *
      * *
      *
      “””

      for i in range(5, 0, -1):
      print(str(‘*’) * i)

      Reply
  99. luke says

    July 24, 2022 at 2:28 pm

    my solution for exercise number 6:

    listnum = [5,25,55,15544,33,1355]
    def fivenum(list):
        for x in list:
            c= x%5
            if c== 0:
                print(x)
    
            else:
                continue
    fivenum(listnum)
    Reply
  100. Zane Hewgley says

    July 13, 2022 at 3:58 pm

    As with a lot of people, I am very new to this.
    On question 1, I got the correct output but wrote it completely different than the solution.
    Could someone explain to me why it is recommended to write it out the solution way over my answer..

    
    number1 = 20
    number2 = 30
    
    sum = number1+number2
    product = number1*number2
    if product  1000:
        print("The result is " + str(sum))
    Reply
    • Zane Hewgley says

      July 13, 2022 at 3:59 pm

      
      number1 = 20
      number2 = 30
      
      sum = number1+number2
      product = number1*number2
      if product  1000:
          print("The result is " + str(sum))
      Reply
      • Zane Hewgley says

        July 13, 2022 at 4:01 pm

        for some reason its not printing the last part.

        
        elif product > 1000:
            print("The result is " + str(sum))
        Reply
        • Zane Hewgley says

          July 13, 2022 at 4:05 pm

          sorry for the multiple comments…
          I realize it is leaving out stuff.
          it says-
          if product 1000:
          print("The result is " + str(sum))

          Reply
          • D Whitt says

            July 28, 2022 at 8:50 pm

            I’m not sure if I’m reading it right or if something is missing. But your code says:

            if product 1000:

            I’m guessing you meant to put

            
            if product is > 1000:
                print("The result is " + str(sum))

            This says if you multiply and the answer is over 1000 the print the sum instead.
            and instead of elif, you can do "else" which should cover anything being <= 1000

  101. Sreehari m n says

    July 11, 2022 at 1:17 pm

    Anybody have another solution for question 13 for multiplication table with only increment of j in nested loop?

    Reply
    • Ben says

      July 12, 2022 at 12:32 am

      Like this?

      for j in range(1,11) :
          prev = j
          for j in range(1,11) :
              print(j*prev, end=" ")
          print("")
      Reply
      • Sreehari says

        July 12, 2022 at 12:33 pm

        no.for ex:
        for table of 2: 2, 2+2, 4+2, 6+2 like that. every number in a table will be incremented by the same number.

        Reply
        • Malrey says

          July 18, 2022 at 10:45 pm

          maybe like this? :

          
          for i in range (1,11) :
              number = 0
              for j in range(1,11) :
                  number += i
                  print(number, end=' ')
              print("\t\t")
          Reply
    • Sahadad HT says

      August 1, 2022 at 8:48 pm

      you can try this

      
      print("Table of 1-10 \t")
      for i in range(1,11):
          for j in range(1,11):
              print(i,"*",j,"=",i*j,end="\t\t")
          print("\t")
      Reply
  102. Ben says

    July 9, 2022 at 11:42 pm

    One Liners (I’m a beginner but really enjoying the one-line problems)

    number1 = int(input("Number1: ")); number2 = int(input("Number2: ")); sum = number1*number2; print(sum) if sum >= 1000 else print(number1+number2) #Exercise 1
    low = int(input("Input Starting Value: ")); [ print("Current Number %i Previous Number %i Sum: %i" % (i, 0 if i == low else i-1, low if i == low else i+i-1)) for i in range(low, low+10) ] #Exercise 2
    word = input("Enter String: "); strlen = len(word); print("Original String is %s\nPrinting only even index chars" % word);[ print(word[i]) for i in range(0,strlen,2) ] #Exercise 3
    word = input("Enter String: "); remove = int(input("Enter Number of Chars to Remove: ")); print(word[remove:]) #Exercise 4
    num_list = [10, 20, 30, 40, 10]; print("Given list %ls\nresult is %s" % (num_list, "True" if num_list[0] == num_list[-1] else "False")) #Exercise 5
    num_list = [10, 20, 33, 46, 55]; print("Given list is", num_list, "\nDivisible by 5"); [ print(value) if value % 5 == 0 else print("",end="") for index, value in enumerate(num_list) ] #Exercise 6
    input = "Emma is good developer. Emma is a writer"; print(input.count("Emma")) #Exercise 7
    [ print(("%i ")%(i)*i) for i in range(1,6) ]  #Exercise 8
    user_input = str(input("Enter String: ")); print("Is a valid Palindrome") if user_input == user_input[::-1] else print("Is not a valid Palindrome") #Exercise 9
    list1 = [10, 20, 25, 30, 35]; list2 = [40, 45, 60, 75, 90]; list3 = []; [ list3.append(list1[index]) if int(list1[index]) % 2 != 0 else print("",end="") for index in range(len(list1)) ]; [ list3.append(list2[index]) if int(list2[index]) % 2 == 0 else print("",end="") for index in range(len(list2)) ]; print(list3) #Exercise 10
    user_input = str(input("Input Integer: ")); print(user_input[::-1]); #Exercise 11
    [ print(' '.join([str(i*j) for i in range(1,11)])) for j in range(1,11) ] #Exercise 13
    [ print('* '*i) for i in range(5,0,-1)] #Exercise 14
    base = int(input("Enter Base Value: ")); exponent = int(input("Enter Exponent Value: ")); product = base ** exponent; [print(f'{base} raised to the power of {exponent} is {product}')] #Exercise 1
    Reply
  103. Rajat Singh says

    June 18, 2022 at 12:30 am

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

    #code:

    def exponent(base,ex):
        exponen = base ** ex
        return exponen
    
    A = exponent(5,4)
    print(A)
    Reply
    • John says

      July 5, 2022 at 7:29 pm

      Please I cannot understand the palindrome answer. I need explaination

      Reply
    • Dario says

      July 11, 2022 at 6:38 pm

      that´s correct, but you need to add a condition where it only makes the math when the exp is greater than 0 like it says on the problem statement
      I did it like this

      def exponent(base, exp):
          while exp > 0:
              result = base ** exp
              return result
      
      base = 2
      exp = 5
      
      print("{} raises to the power of {}:".format(base, exp), exponent(base, exp))
      Reply
  104. Chellammal says

    June 7, 2022 at 5:00 pm

    One line solutions to excercises 8,13 and 14 based on list comprehension.

    [ print(((str(i)+" ")*i).rstrip()) for i in range(1,6) ] # excercise 8
    [ print(" ".join([str(j) for j in range(i,((i*10)+1),i)])) for i in range(1,11) ] #excercise 13
    [ print((('*'+" ")*i).rstrip()) for i in range(5,0,-1) ] #excercise 14
    Reply
    • Pravin says

      June 23, 2022 at 10:55 am

      Why you used rstrip() in #exercise 8?
      Sorry, I’m new to Python and wondering about this usage on that code. Thank you!

      Reply
      • CODHOO says

        July 4, 2022 at 7:04 pm

        He forgot it was supposed to be for beginners

        Reply
    • Ben says

      July 9, 2022 at 8:45 pm

      I was trying to wrap my head around how the bracketed lines work, and I think this is a little clearer to read. Really glad I saw your comment, though, this seems like really useful stuff!

       [ print(' '.join([str(i*j) for i in range(1,11)])) for j in range(1,11) ]  #exercise 13 
      Reply
      • Ahmed says

        July 31, 2022 at 12:27 pm

        I do it with one for loop

        
        num = 0 
        for i in range(1,6):
            num += 10 ** (i-1)
            x = list(str(num*i))
            print(' '.join(x))
        Reply
  105. Chellammal says

    June 7, 2022 at 4:59 pm

    One-line solutions to exercises 8,13 and 14 based on list comprehension.

    [ print(((str(i)+" ")*i).rstrip()) for i in range(1,6) ] # excercise 8
    [ print(" ".join([str(j) for j in range(i,((i*10)+1),i)])) for i in range(1,11) ] #excercise 13
    [ print((('*'+" ")*i).rstrip()) for i in range(5,0,-1) ] #excercise 14 
    Reply
  106. Hero Zero says

    June 1, 2022 at 2:06 pm

    for exercise no. 15 with required output:

    
    def exponent(base, exp):
        result = base ** exp
        print(f'{base} raises to the power of {exp}: {result} i.e. ({base}', end="")
        for i in range(1, exp):
            print(f' * {base}', end="")
        else:
            print(f' = {result})')
    
    
    exponent(2, 5)

    output:

    C:\Users\BG-PC164a\PycharmProjects\pythonProject\venv\Scripts\python.exe C:/Users/BG-PC164a/PycharmProjects/pythonProject/main.py
    2 raises to the power of 5: 32 i.e. (2 * 2 * 2 * 2 * 2 = 32)
    
    Process finished with exit code 0
    Reply
    • Hero Zero says

      June 1, 2022 at 2:13 pm

      
      def exponent(base, exp):
          result = base ** exp
          print(f'{base} raises to the power of {exp}: {result} i.e. ({base}', end="")
          for i in range(1, exp):
              print(f' * {base}', end="")
          else:
              print(f' = {result})')
      
      
      exponent(5, 2)
      
      C:\Users\BG-PC164a\PycharmProjects\pythonProject\venv\Scripts\python.exe C:/Users/BG-PC164a/PycharmProjects/pythonProject/main.py
      5 raises to the power of 2: 25 i.e. (5 * 5 = 25)
      
      Process finished with exit code 0
      Reply
  107. Ash says

    May 30, 2022 at 2:45 am

    Using if for Exercise 3: Print characters from a string that are present at an even index number

    
     a=input('Write a word:-')
    
    l=len(a)
    
    
    for n in range(l):
        if n%2==0: # using if 
            print(a[n])
    Reply
  108. Tam says

    May 21, 2022 at 4:32 pm

    Answer to exercise 9: Check if the string is a palindrome

     I know this is more convenient answer:
    text = input("Enter string ")
    a= text[::-1]
    if a==text:
        print("This is palindrome")
    else: print("This is not palindrome") 

    But this is also good solution to understand the logic:

    str1 = input("Enter string")
    revlist = []
    last_index = -1
    for i in str1:
        revlist.append(str1[last_index])
        last_index -=1
        str2 = ""
        for i in revlist:
            str2+=i
    if str1==str2:
        print("This is palindrom")
    else:
        print("this is not palindrom")
    Reply
  109. aravindhan says

    May 11, 2022 at 9:08 pm

    solution to exercise 15:

    def exponentiation(base,exp):
        result = (base ** exp)
        print(exp, " is the exponentiation of ", base)
        print("The result is: ", result)
    
    exponentiation(2,5)
    Reply
  110. Techo says

    April 29, 2022 at 8:33 am

    A good place to start with problem-solving. Before I would read articles, and watch videos; but, after solving these problems I realized I had been wasting my precious time. Spent all night on them.
    Thank you very much!

    Reply
  111. carisa says

    April 5, 2022 at 2:46 am

    This site is extreamly usfull, totaly recomend.

    Reply
    • Hendi says

      April 25, 2022 at 3:19 pm

      There is a problem in question number one, the expected output is different from the question (contradicted). Anyway thanks for your sharing.

      Reply
      • ashwin says

        May 1, 2022 at 12:01 pm

        yes right

        Reply
  112. carisa says

    April 5, 2022 at 2:44 am

    this site is extreamly usfull,totaly recomend

    Reply
  113. deschreiber says

    March 24, 2022 at 6:50 pm

    Exercise 9. Palindrome numbers. Is it cheating to check for a palindrome number by converting the number to a string, checking with indexing, then converting it back to an int? It’s a much simpler solution.

    
    num = 123321
    num_str = str(num)
    if num_str == num_str[::-1]:
        print('Yes, given number is a palindrome number.')
    else:
        print('No, given number is not a palidrome number.')
    Reply
    • deschreiber says

      March 24, 2022 at 6:54 pm

      Actually, of course, there’s no need to convert the string back to a number.

      Reply
    • saurav says

      April 7, 2022 at 12:05 pm

      what if num is given user and the user give ‘mom’ as input.

      Reply
      • Mashood Iqbal Khan says

        April 23, 2022 at 1:01 pm

        x=input("Check Palindrome Number : ")
        
        if x==x[::-1]:
            print("Original Number: {0} \nYes. Given Number is palindrome number.".format(x))
        else:
            print("Original Number: {0} \nNo. Given Number is not palindrome number.".format(x))
        Reply
  114. ABD RRAHIM says

    March 14, 2022 at 3:31 pm

    Exercise 11 :

    
    a = 7536
    a = str(a)
    for i in range(len(a)-1,-1,-1):
        print(a[i],end=' ')
    Reply
    • ABD RRAHIM says

      March 14, 2022 at 3:34 pm

      or

      
      def renum(num):
        num = str(num)
        for i in range(len(num)-1,-1,-1):
          print(num[i],end=' ')
      renum(7536)
      Reply
      • sunil says

        August 26, 2022 at 4:29 pm

        n = 7536
        reversed = int(str(n)[::-1])
        print(reversed)
        Reply
  115. ABD RRAHIM says

    March 14, 2022 at 3:08 pm

    EX 15:

    
    def power(base,exponent):
      x = 1
      a = 1
      while x<= exponent:
       for x in range(1,6) :
        a = a*base
        x+=1
      print(base, "raises to the power of", exponent, "is: ", a)
    power(2,5)
    Reply
    • wayne says

      April 4, 2022 at 1:39 am

      def exponent(base, exp):
          calculate = base**exp
          return calculate
      
      base = int(input('Enter the base: '))
      exp = int(input('Enter the exponent: '))
      
      print('The answer is', exponent(base, exp))
      Reply
  116. foaad says

    March 8, 2022 at 1:45 am

    ex14:

    for i in range(1,6):
       print("* "*(6-i))
    Reply
    • Ram says

      March 29, 2022 at 8:15 am

      
      for i in range(10,0,-1):
          print('* ' * i)
      Reply
      • ashwin chavhan says

        May 5, 2022 at 7:27 pm

        i=5
        while i<=5:
            print(i*("*")
        i=i+1

        is that ok?//

        Reply
  117. Hamza Younsi says

    February 20, 2022 at 4:34 pm

    Exercise 10:

    list1 = [10, 20, 25, 30, 35]
    list2 = [40, 45, 60, 75, 90]
    c = list()
    g = list()
    for i in range(0, 5):
        if list1[i] % 2 != 0:
            c = list1[i]
            g.insert(i, c)
    line = len(g)
    cal = len(list2)
    for m in range(line, cal - 1):
        if list2[i] % 2 == 0:
            c = list2[i]
            g.insert(i, c)
    print("result list : ",g)
    Reply
    • DebTahir says

      February 28, 2022 at 12:48 am

      def CreateNewList(list1,list2):
          newList = []
          for i in list1:
              if(i%2) != 0:
                  newList.append(i)
          for j in list2:
              if(j%2) == 0:
                  newList.append(j)
          return newList
      
      list1 = [10, 20, 25, 30, 35]
      
      list2 = [40, 45, 60, 75, 90]
      print(CreateNewList(list1,list2))
      [25, 35, 40, 60, 90]
      Reply
  118. Laurits says

    January 31, 2022 at 7:59 pm

    Question number 15:

    a = int(input("Enter the base: "))
    b = int(input("Enter your ex: "))
    print ("Your answer is: ", a**b)

    Will do the same just way easier

    Reply
  119. Mohammed Faizan says

    January 26, 2022 at 10:48 pm

    EXCERCISE 15: I think we can directly calculate the power of using (**) function

    def exponent(base,exp):
        return(base**exp)
    
    exponent(5,4)
    Reply
    • tg says

      March 26, 2022 at 5:10 pm

      Yes, exactly. I really don’t get why using loops (while, for, etc.. here).

      
      def exponent(base, exp):
      	print(f"base = {base} \nexponent = {exp}\n")
      	print(f"{base} raises to the power {exp} : {base**exp} i.e. ({(exp-1)*(str(base)+' * ')+ str(base)} = {base**exp}) ")
      Reply
  120. Leon Reaplust says

    January 23, 2022 at 2:16 pm

    I did Exercise 9: Check Palindrome Number diffrently, using string for reversing number. It goes like this:

     x = int(input('Write number you think is palindrome: '))
    rev_x= str(x)[::-1]
    
    if str(x)==rev_x:
      print('Number ',x,' is palindrome')
    else:
      print('Number ',x,' is not palindrome')
    Reply
  121. Leon Reaplust says

    January 22, 2022 at 5:24 pm

    Exercise 6: Display numbers divisible by 5 from a list soo list is inputed by user, hope you like it 🙂

     def div_by_5(l):
      for i in l:
        if i%5==0:
          print('Number ',i,' is divisible with 5')
        else:
          print('Number ',i,' is not divisilbe with 5')
    
    lst = []
    n = int(input('Write number of elements for your list: '))
    
    for i in range(0,n):
      ele=int(input('Write number on your list: '))
      lst.append(ele)
    
    print('Your list is: ',lst)
    print(div_by_5(lst))
    Reply
  122. Leon Reaplust says

    January 22, 2022 at 4:05 pm

    s = str(input('Write your word: '))
    n = int(input('Write number of letters that you want to remove from word: '))
    
    if n < len(s):
      print('Word without first ',n,'letters is: ',s[n:])
    else:
      print('n is too big!')

    This is my solution for Exercise 4: Remove first n characters from a string if you maybe want to include it, It does something but a different way around.

    Reply
  123. _makhmud says

    January 17, 2022 at 3:46 pm

    14-exercise

    n = int(input("Enter number:"))
    
    while n > 0:
        for i in range(1, n+1):
            print("*", end = "")
        print("\t")
        n -= 1
    Reply
    • kandula nithin says

      February 8, 2022 at 7:13 pm

      num = int(input("please enter the number of lines needed: "))
      while num > 0:
        print('*' * num, end = '')
        num -= 1
        print(end = '\n')
      Reply
  124. Arnav(9 years old) says

    January 14, 2022 at 10:08 pm

    def exponent(b,e):
      b = b
      e = e
      a = 1
    
    
      for i in range(e):
        a = a*b
    
      print(b,'to the power of',e,'is',a)
    x = int(input('enter a base to caculate exponents: '))
    y = int(input('enter exponent(how many times you multiply): '))
    exponent(x,y)
    print(' ')
    print(' ')
    for i in range(5,0,-1):
      print('* '*i)
    Reply
  125. Arbaz Khan says

    January 12, 2022 at 5:24 pm

    Last Question We Can Also Do Like:

    def num(x, y):
      return x**y
    
    num_1 = int(input("ENTER THE BASE: "))
    num_2 = int(input("ENTER THE EXPONENT: "))
    RESULT = num(num_1, num_2)
    print("Result: ",num_1,"raises the power of ",num_2,"=",RESULT)
    Reply
  126. Arnav(9 years old) says

    January 12, 2022 at 8:53 am

    def exponent(b,e):
      b = b
      e = e
      a = 1
    
    
      for i in range(e):
        a = a*b
    
      print(b,'to the power of',e,'is',a)
    x = int(input('enter base(for exponents): '))
    y = int(input('enter exponent(how many times you multiply): '))
    exponent(x,y)

    #Exercise 15

    Reply
    • Arnav(9 years old) says

      January 12, 2022 at 8:55 am

      indents didn’t post when i copy pasted my code

      Reply
  127. Arnav(9 years old) says

    January 4, 2022 at 12:02 pm

    var = input('enter a word: ')
    #print(var)
    x = int(input('enter a number that is less than len of the word you typed: '))
    while x<=len(var)-1:
      print(var[x],end='')
      x += 1
    for i in range(2,5):
      print(' ')
    Reply
    • Arnav(9 years old) says

      January 4, 2022 at 12:06 pm

      this is for exercise 4, the one about removing index chars

      Reply
  128. David says

    December 21, 2021 at 1:56 am

    Please, someone, tell me why my solution for #12 doesn’t give me the correct result for 45000 income because it will always tell me that the tax is 3500 instead of 6000:

    def tax(income):
        if income  10000  20000:
            print("Tax to be payed: ", (income-20000)*0.2+1000)
    
    tax(5000)
    tax(15000)
    tax(45000)
    Reply
    • David says

      December 21, 2021 at 1:57 am

      sorry wrong code:

      
      def tax(income):
          if income  10000  20000:
              print("Tax to be payed: ", (income-20000)*0.2+1000)
      Reply
      • David says

        December 21, 2021 at 1:59 am

        Ok for some reason it won’t copy/paste the whole code correctly… FFS

        Reply
        • David says

          December 21, 2021 at 2:02 am

          Last try, very sorry for spamming:

           
          def tax(income):
              if income  10000  20000:
                  print("Tax to be payed: ", (income-20000)*0.2+1000)
          
          
          tax(5000)
          tax(15000)
          tax(45000)
          Reply
          • David says

            December 21, 2021 at 2:08 am

            Nevermind I figured it out. My comments can be deleted. Again very sorry for spamming, this was not my intention.

        • Vishal says

          January 2, 2022 at 11:12 am

          Please use ‘pre’ tag for posting code. For example,

          Your code here
          Reply
    • Irfan says

      May 15, 2023 at 12:14 pm

      first = 10000
      second = 10000
      remaining = tax - (first + second)

      x = (first * 0/100 + second * 10/100 + remaining * 20/100)
      print("The taxable amount is : ", x)

      Reply
  129. hakizimana frederick says

    December 15, 2021 at 5:19 pm

    
    def merge_list(list1, list2):
        empty_arr = []
    
        for el1, el2 in zip(list1, list2):
            if el1 % 2 == 0:
                empty_arr.append(el1)
            if el2 % 2 != 0:
                empty_arr.append(el2)
        return empty_arr
    
    
    print(merge_list(list1, list2))
    Reply
  130. hakizimana frederick says

    December 12, 2021 at 1:53 am

    
    input_str = str(input('Enter string: '))
    
    for i,  value, in enumerate(input_str):
        if i % 2 == 0:
            print(value)
    Reply
  131. Jakub Kolář says

    December 11, 2021 at 12:04 am

    Hello. The query for task 13. Why is print("\t\t") at the end? When does print("") work anyway?

    Reply
    • Rahul says

      January 16, 2022 at 11:35 pm

      print("\t") is used whenever a tab space has to be left in the output
      print("") is used to print a new line

      Reply
  132. Saeed Ahmed says

    November 25, 2021 at 11:04 pm

    original_str = input("Enter sTring : ? ")
    remove_chr = int(input("Enter number of chr to remove :? "))
    new_str = original_str[remove_chr:]
    print(new_str)
    
    # Method 2
    
    original_str = input(" Enter sTring : ? ")
    remove_chr = int(input("Enter number of chr to remove :? "))
    new_str = list(original_str[remove_chr:])
    print(new_str)
    
    # Method 3
    original_str = input(" Enter sTring : ? ")
    remove_chr = int(input("Enter number of chr to remove :? "))
    new_str = list(original_str)
    new_str = new_str[remove_chr:]
    print(new_str)
    Reply
  133. Aakash Thakur says

    November 24, 2021 at 2:36 pm

    for question number 15.

    base = 2
    exponent = 5
    for i in range(1,exponent+1):
        ans = base**exponent
        print("{} raises to the power of {}: {}".format(base,exponent,ans))
        break
    Reply
    • Ankit Mondal says

      December 14, 2021 at 7:36 am

      def power(base, exponent):
          exp = (base**exponent)
          print(f'{base} raises to the power of {exponent} is {exp}')
      
      
      new_power = power(3, 2)
      Reply
      • Ankit Mondal says

        December 14, 2021 at 7:37 am

        
        def power(base, exponent):
            exp = (base**exponent)
            print(f'{base} raises to the power of {exponent} is {exp}')
        
        new_power = power(3, 2)
        Reply
        • Test says

          January 6, 2022 at 8:50 pm

          Test

          Reply
  134. Michael says

    November 16, 2021 at 12:35 am

    Q3: An overly complex, but fun, answer

    string = 'abcdefghijklmnopqrstuvwxyz'
    def slicer(x):
        for i in range(len(x)):
            if i % 2 == 0:
                print(string[i])
    
    print(slicer(string))
    Reply
  135. Coder says

    November 1, 2021 at 5:31 pm

    #Exercise 14: Print downward Half-Pyramid Pattern with Star (asterisk)
    for i in range(1,6):
        print("* "*(6-i))
    Reply
  136. Mohammed Sadique Ansari says

    October 12, 2021 at 7:49 pm

    For Ex:15

    Reply
    • Mohammed Sadique Ansari says

      October 12, 2021 at 7:54 pm

      def exponent(base, exp):
                      output = base**exp
                      return output
      Reply
  137. Jim says

    September 7, 2021 at 1:39 am

    EX 1:
    “Given two integer numbers return their product only if the product is greater than 1000, else return their sum.”

    Hint:
    Next, use the if condition to check if the product >1000. If yes, return the product
    Otherwise, use the else block to calculate the sum of two numbers and return it.

    Your solution:

    if product <= 1000:
            return product
        else:
            # product is greater than 1000 calculate sum
            return num1 + num2

    Your solution is the opposite of what your problem statement and your hint state.

    Reply
    • mustafa says

      September 12, 2021 at 8:48 am

      yes nice catch

      Reply
    • John says

      November 4, 2021 at 12:11 pm

      Came here to say the same. Already unconfident beginners get even more confused with this mistake in the very first exercise.

      Reply
      • Quan says

        November 10, 2021 at 1:45 pm

        absolutely agree with you

        Reply
      • Jean says

        November 12, 2021 at 12:22 am

        Error still not corrected as of November 11. This is really a poor site, they don’t even read comments… Shame on them !

        Reply
    • JJ says

      January 1, 2022 at 2:56 pm

      Right, it is a bit amusing that is the first exercise. Just a side note: shouldn’t it be <, not <= because the question was: "if the product is greater"?

      Reply
  138. Houssem says

    September 6, 2021 at 5:31 pm

    Q 12:

    def stars(num):
        for i in range(num+1, 0, -1):
            print("* "*i)
        
    stars(5)
    Reply
  139. Houssem says

    September 6, 2021 at 4:15 pm

    Q 11:

    def number(num):
        string = str(num)[::-1]
        for i in string:
            print(i, end=" ")
    Reply
  140. Houssem says

    September 6, 2021 at 4:05 pm

    Q 10:

    def makeList(lst1, lst2):
        f_lst = list()
        for i,a in zip(lst1, lst2):
            if i%2 != 0: f_lst.append(i)
            if a%2 == 0: f_lst.append(a)
        return f_lst
    Reply
  141. Houssem says

    September 5, 2021 at 10:17 pm

    Q 09 in two lines:

    def reverse(num):
        a = int(str(num)[::-1])
        return True if a == num else False
    Reply
  142. Houssem says

    September 5, 2021 at 9:52 pm

    Q7 without using str class:

    def emma(string):
        lst = string.split(" ")
        count = 0
        for i in lst:
            if i == "Emma": count += 1
        retutn count
    Reply
  143. kanhaiya singh says

    August 24, 2021 at 6:44 pm

    solution for question no 5

    if list[0]==list[-1]:
        print('true')
    else:
        print('false')
    Reply
    • Houssem says

      September 5, 2021 at 9:22 pm

      This is more easy I think:

      def q5(lst):
           return True if lst[0] == lst[-1] else False
      Reply
      • badr says

        September 21, 2021 at 2:31 pm

        num1 = [10, 20, 30, 40, 10]
        num2 = [75, 65, 35, 75, 30]
        
        
        def detective(nums):
            if (nums[0]) == (nums[-1]):
                return True
            else : 
                return False
            
        print(detective(num1))
        print(detective(num2))
        Reply
  144. Meiti says

    August 20, 2021 at 7:06 am

    other way to coding ex 8:

    for i in range(num):
        print((str(i) + ' ') *i) 
    Reply
  145. Meiti says

    August 20, 2021 at 6:26 am

    Other way to solution Q5:

    def same(x):
        y=[]
        y.append(x.pop(0))
        y.append(x.pop(-1))
        k=set(y)
        if len(k)==1:
            return True
        else:
            return False

    a little bit complicated

    Reply
    • Aditya Sarkar says

      August 27, 2021 at 12:06 am

      Another way of Question 5:

      def alist(list):
          for i in list:
              if i[0] == i[-1]:
                  return True
              else:
                  return False
      
      print(alist([[10, 20, 30, 40, 10]]))
      Reply
      • Aditya Sarkar says

        August 27, 2021 at 12:08 am

        probably not the best looking code

        Reply
        • Houssem says

          September 5, 2021 at 9:24 pm

          what about this one?

          def muli(lst):
               return True if lst[0] == lst[-1] else False
          Reply
  146. Meiti says

    August 20, 2021 at 4:28 am

    Another answer to E3:

    def evenchr(str):
    	x=list(str)
    	for i in x[0::2]:
    		print(i)
    Reply
    • Collince says

      November 1, 2021 at 1:34 am

      def evenChar(text):
      	for i in text[0::2]:
      		print(i)
      Reply
  147. Viraj Sazzala says

    August 19, 2021 at 10:29 am

    Question no: 11 – Reverse a number
    this is an easier and less complicated way to do it.

    number = input('Enter a number: ')
    
    #reverse the string input
    reverse_num = number[::-1]
    
    #turns the reverse number into a list
    list_num = list(reverse_num)
    
    #print the list with spaces in the same line
    print(*list_num)
    Reply
  148. Hoang Thien Son says

    August 18, 2021 at 3:42 pm

    dear admin this is my shorter solution to question 8

    n = int(input("Your number of rows: "))         #call the rows
    for i in range(n+1):    #for i in 1 to n
        print(str(i)*i)     #print the number of i multiple by i which is the same point of this exercise
    Reply
  149. Viraj Sazzala says

    August 18, 2021 at 12:04 am

    Question 9: Reverse number.

    number = input('Enter a number: ')
    revnum = number[::-1]                            
    if number == revnum:
        print('True')
    else:
        print("False")

    this is simpler and also works well.

    Reply
    • Lynnz says

      September 19, 2021 at 2:07 pm

      The same with you!

      Reply
    • badr says

      September 21, 2021 at 3:03 pm

      x = list(input("your number :"))
      if x[0::] == x[-1::-1] :
          print("Yes. given number is palindrome number")
      else : 
          print("No. given number is not palindrome number")
      Reply
      • Andy says

        October 14, 2021 at 7:36 pm

        Assuming n is a number:

        def is_palindrome(n):
            return (list(str(n1)) == list(str(n1))[::-1])

        It’s, as mentioned before, a one-liner.
        Badr, [:] is enough to copy ([0::] is not needed, and moreover, you don’t need to copy the list). and x[::-1] is enough to return a reversed copy. Just to polish a bit the already efficient code 🙂

        Reply
        • Andy says

          October 14, 2021 at 7:37 pm

          Damn… forgot to update n1 to n in the body of the method…

          Reply
    • Andy says

      October 14, 2021 at 7:39 pm

      Hey, missed this one. Nice.

      Reply
  150. Adam says

    August 17, 2021 at 1:24 pm

    Hi Admin,
    thanks, I’m still very new to programming and these exercises improve my skills 🙂

    my answer for Q3 & Q10:

    def print_even_index(input_str):
        char_at_even_index = [(i, j) for i, j in enumerate(input_str) if i%2 == 0]
    
        for i, j in char_at_even_index:
            print("index[", i, "]", j)
    
    input_str = "pynativeZ"
    
    print_even_index(input_str)

    ————-

    def merge_list(list1, list2):
        list1_odd_nums = [i for i in list1 if i%2 == 1]
        list2_even_nums = [i for i in list2 if i%2 == 0]
        new_list = list1_odd_nums + list2_even_nums
        return new_list
    
    list1 =  [10, 20, 23, 11, 17]
    list2 = [13, 43, 24, 36, 12]
    
    print(merge_list(list1, list2))
    Reply
  151. Voided says

    August 5, 2021 at 12:59 am

    My solution to the very easy first problem but with less lines of code:

    
    # problem 1:
    def calculate(n1,n2):
        if n1 * n2 >= 1000:
            return n1 + n2
        else:
            return n1 * n2
    
    result = print(calculate(int(input("1st number: ")),int(input("2 number: "))))
    Reply
  152. Madhan hasee says

    July 31, 2021 at 2:23 pm

    You can use this code for 15 Exercise,

    def exponent(base, exp):
         return base ** exp
    print("6 raises to the power of 4:",exponent(4, 6))
    Reply
    • Madhan hasee says

      July 31, 2021 at 2:25 pm

      def exponent(base, exp):
             return base ** exp
      print(“6 raises to the power of 4:”,exponent(4, 6))
      Reply
    • angelo says

      August 4, 2021 at 6:26 am

      def exponent(base,exp):
          if base > 0:
              print(base**exp)
      exponent(2,5)
      Reply
    • Mazhar Khilji says

      August 4, 2021 at 2:23 pm

      def exponent(base, exp):
      
          power = base ** exp
          print(base, "raises to the power of", exp, "is: ", power)
      
      exponent(5, 4)
      Reply
  153. Madhan hasee says

    July 31, 2021 at 2:17 pm

    For 11 Exercise you can use this code,

    numbers = input("Enter your number :")
    for i in numbers[::-1]:
         print(i, end=' ')
    Reply
    • Madhan hasee says

      July 31, 2021 at 2:18 pm

      numbers = input(“Enter your number :”)
      for i in numbers[::-1]:
             print(i, end=’ ‘)
      Reply
  154. Mazhar says

    July 17, 2021 at 3:28 pm

    Exercise 15. will be easy like this

    def powerplay(base,exponent): 
    
        while True:
            return base ** exponent
    
    print("2 raises to the power of 5:",powerplay(2,5))
    Reply
    • ANKIT says

      July 26, 2021 at 4:28 pm

      def result(x,y):
          return x**y
      print(result(2,5))
      Reply
  155. Ritvik says

    June 12, 2021 at 2:55 am

    Another way to solve Q14 ->

    for i in range(5, 0, -1):
        print(' * '*i, end='')
        print('\t')
    Reply
    • Ritvik says

      June 12, 2021 at 2:56 am

      
      for i in range(5, 0, -1):
          print(' * '*i, end='')
          print('\t')
      Reply
    • Piyush says

      July 2, 2021 at 3:52 pm

      i=6
      while i>0:
        print("* " * i)
        i -= 1
      Reply
    • Shreyans Daga says

      July 14, 2021 at 7:58 am

      Another way could be:

      count = 4
      string = "* * * * *"
      list1 = string.split(" ")
      for i in range(1, 6):
          print("".join(list1))
          list1.pop(count)
          count -= 1
      Reply
  156. Stevie says

    June 6, 2021 at 12:47 am

    Exercise 8:
    The below will also return the same result.

    for i in range(6):
        print(str(i)*i)
    Reply
    • t says

      June 18, 2021 at 3:56 am

      pattern is wrong

      Reply
      • Gaurav Gautam says

        July 19, 2021 at 6:00 pm

        just having a 0
        it should be range(1,6)
        rest all is perfect

        Reply
  157. Reshma Rajan k says

    June 4, 2021 at 9:38 am

    Exercise :15

    def exponent(base,exp):
        print('Base=',base,'exponent=',exp)
        ans = base**exp
        print(exp,'raises to the power of',base,':',ans)
    exponent(5,4)
    Reply
  158. Subhraneel Paul says

    May 23, 2021 at 7:32 pm

    Exercise 14: Print downward Half-Pyramid Pattern with Star (asterisk)

    for i in range(5):
        for j in range(5-i):
            print("*", end="  ")
        print("\n")
    Reply
    • Subhraneel Paul says

      May 23, 2021 at 8:00 pm

      for x in range(5):
          for y in range(5-x):
              print("*",end="  ")
          print("\n")
      Reply
    • AndyLee says

      June 6, 2021 at 7:41 am

      Thank you! This one is easier for me to understand!

      Reply
      • Subin Jerin says

        July 15, 2021 at 6:01 pm

        Very easy to understanf for me this

        Reply
  159. Gulshat says

    May 14, 2021 at 12:22 pm

    Ex9: I prefer to treat entered number as a string. Way more simple code:

    s = input("Input a number: ")
    if s[::-1] == s:
        print("The original and reverse number is the same")
    else: 
        print("The original and reverse number is not the same")
    Reply
  160. Gulshat says

    May 14, 2021 at 12:12 pm

    Hi, I have a slightly shorter solution for Ex8:

    for i in range(1, 10):
        print (str(i)*i)
    Reply
  161. Tawhid says

    May 13, 2021 at 3:03 pm

    Hello vishal
    could you elabaorate this line of code for me ?
    reverseNum = (reverseNum * 10) + reminder

    It was in Q9. I am new in python so some easy things seems hard for me.The line is one of them.

    Reply
  162. Abhay MISHRA says

    May 9, 2021 at 11:13 pm

    Ans-1

    def pruduct_sum(num1,num2):
      if num1*num2 > 1000:
        return num1+num2
      return f'The result is {num1*num2}'
    print(pruduct_sum(40,30))

    Ans-2:

    for i in range(10):
      if i == 0:
        print(f'current number is {i} no previse number : sum{i}')
      else:
        print(f'current number is {i} previsios number is {i-1} : sum {i+(i-1)}')

    Ans_3:

    def reverse_num(intiger):
      new_num = str(intiger)
      if new_num == new_num[::-1]:
        print(f'Orignal number is {intiger}','\n''The original and reverse number is the same')
      else:
        print("The original and reverse number is not same")
    
    reverse_num(121)

    Ans-4:

    str = "pynative"
    for word in str[::2]:
      print( f'{str.index(word)} : {word}')

    Ans-5

    def removeChars(var,num):
      return var[num:]
    print(removeChars("pynative", 4))

    Ans-6

    def Emm_counter(string):
      total = 0
      new_list = string.split(' ')
      for item in new_list:
        if item == "Emma":
          total += 1
      return total
    print(f'Emma appeared  {Emm_counter("Emma is good developer. Emma is a writer")} time')

    Ans-7

    for i in range(1,6):
      for num in range(i):
        print(i , end=' ')
      print()

    Ans-8

    def even_odd_list(list1,list2):
      new_list = []
      for num in list1:
        if num%2!=0:
          new_list.append(num)
      for num in list2:
        if num%2 == 0:
          new_list.append(num)
      return new_list
    list1 =  [10, 20, 23, 11, 17]
    list2 = [13, 43, 24, 36, 12]
    print('new_list is ', even_odd_list(list1,list2))

    Ans-9

    def reverse_num(intiger):
      new_string = ''
      new_num = str(intiger)
      for num in new_num:
        new_string += num+' '
      return new_string[::-1]
    
    print(reverse_num(7536), end=" ")

    Ans-10

    def income_tax(income):
      tax_payble = 0
      if income = 10000:
        tax_payble += 10000*10/100
        first_year -= 10000
        tax_payble += first_year*20/100
      else:
        if  first_year < 10000:
          tax_payble += first_year*10/100
      return tax_payble
    print(income_tax(100000))

    Ans-11

    for i in range(1, 11):
        for j in range(1, 11):
            print(i * j,end=' ')
        print('\n')

    Ans-12

    for i in range(1,6):
      print('* '* (6-i))

    Ans-13

    def exponent(base, exp):
      var = base**exp
      str_bas = '('+str(base)+ (' *'+str(base))*(exp-1)+' = '+str(var)+')'
      power_vale = (f'{base} to power of {exp } : {var}')
      print(power_vale,'\n',str_bas)
    
    exponent(2,5)
    Reply
    • Sab3rson says

      February 12, 2022 at 8:45 am

      I got a similar answer:

      def exponent(base,exp):
          
          product = base ** exp
              
          answer_str = "("+ str(base) + (" * " + str(base)) * (exp -1) + " = " + str(product) +")"
              
          print(f"base = {base}\nexponent = {exp}\n\n{base} raises to the power of {exp}: {answer_str}")
          
      exponent(2, 5)
      Reply
  163. Coconut says

    May 8, 2021 at 6:23 am

    Ex 15 alt:

    def exponent(base,exp):
    	## Gives base to the power of exp using only multiplication
    	result = 1
    
    	print(base, 'to the power of', exp, 'is: ')
    
    	for i in range(exp):
    		result = result*base
    		if i<exp-1:
    			print(base,'x', end=' ')
    		else:
    			print(base, end=' ')
    
    	print('=',result,end =' ')
    
    
    
    exponent(2,3)
    Reply
    • Piyush says

      July 2, 2021 at 4:00 pm

      this is the sort version

      def exponent(base, exp):
        return(base**exp)
      
      print(exponent(5,4))
      Reply
  164. Coconut says

    May 8, 2021 at 6:21 am

    EX 15: alt

    def exponent(base,exp):
    	## Gives base to the power of exp using only multiplication
    	result = 1
    
    	print(base, 'to the power of', exp, 'is: ')
    
    	for i in range(exp):
    		result = result*base
    		if i<exp-1:
    			print(base,'x', end=' ')
    		else:
    			print(base, end=' ')
    
    	print('=',result,end =' ')
    
    exponent(2,8)
    Reply
  165. Dave Perez says

    May 4, 2021 at 7:34 pm

    Thank you for all these exercises. They were very helpful to practice coding in Python.

    Here are alternative solutions for Exercise 15:

    def exponent(base, exp):
        # built-in by python exponent function
        base = base**exp
        return base
    print(exponent(2, 5))
    def exponent(base, exp):
        # own logic
        old_base = base
        for index in range(exp-1):
            base = base * old_base
        return base
    print(exponent(2, 5))
    Reply
  166. Dave Perez says

    May 4, 2021 at 6:57 pm

    Alternative and shorter solution in Exercise 12.

    def exercise12(salary):
        tax = 0  # default tax is 0 for salary 10K and below
        if salary > 20000:  # salary more than 20K is 1000 + 20% of salary exceeding 20K
            tax = (salary-20000) * 0.2 + 1000  # 1000 is 10% of 10000
        elif salary > 10000:  # salary more than 10K is 10% of salary exceeding 10K
            tax = (salary-10000) * 0.1
        return tax
    
    # Remove comment to run exercise12
    #print(exercise12(45000))
    Reply
  167. Dave Perez says

    May 4, 2021 at 6:39 pm

    Alternative solution for Exercise 11.

    def exercise11(num):
        reverse = -1
        for index in range(len(str(num))):  # loop in range of string length
            print(str(num)[reverse], end=" ")  # print using negative index
            reverse -= 1  # decrement to next negative index
    # Remove comment below to run exercise11
    #exercise11(7536)
    Reply
  168. Dave Perez says

    May 3, 2021 at 2:18 pm

    Found a shorter solution for Exercise 9:
    Exercise 9: Reverse a given number and return true if it is the same as the original number

    def exercise9(num):
        if str(num) != str(num)[::-1]:
            return False
        return True
    # Remove comment below to run exercise9
    #print(exercise9(121))
    Reply
  169. Dave Perez says

    May 3, 2021 at 1:26 pm

    First of all, thank you for these exercises.

    The solution in Exercise 3 does not print the last character despite having an even index. Improved solution provided below:

    Exercise 3: Given a string, display only those characters which are present at an even index number.

    def exercise3(word):
        for index in range(0, len(word), 2):
            print(word[index])
    
    # Remove comment below to run exercise3
    # exercise3("pynative")
    Reply
  170. pramod padhye says

    April 25, 2021 at 11:36 am

    can we use below code for exc.8

    for i in range(6):
        i = str(i)*i
        print(i)
    Reply
  171. african bum disese says

    April 23, 2021 at 1:51 pm

    same i made roblox epic games and gta 5 im making gta 6 in pythons

    Reply
  172. subramani says

    April 22, 2021 at 9:33 am

    Hi Vishal,

    First of all, thank you for the exercises, it is easy to understand and refer relevant docs when needed.

    I have a question regarding exercise no 4, how do I print first 4 char only, with above code, it only displays in reverse order. My expected output would be pyna, how do I achieve it

    Reply
  173. Rishu says

    April 14, 2021 at 9:15 pm

    Solution 15 –

    
    a=int(input("Enter base : "))
    b=int(input("Enter exponent : "))
    
    def exponent(base,exp):
        return (f"{base} raises to the power of {exp} : {base**exp}")
    
    print(exponent(a,b))
    Reply
  174. Rafael says

    April 14, 2021 at 4:53 am

    Thank you!
    You may like this for the 15th exercise. I went a bit further.

    
    def exponent(base, exp):
        p = base**exp
        print(str(base) + " raises to the power of " + str(exp) + ": " + str(p) + " i.e. (", end = " ")
        for i in range(exp):
            print(base, end= " ")
            if i < exp - 1:
                print("*", end = " ")
        print("= " + str(p) + ")")
    exponent(5, 4)
    Reply
  175. jeevan kumar says

    March 31, 2021 at 7:05 pm

    Good work sir! basic questions but for a beginner, it is a good start. I have done all 15 questions and felt good. thank you. I am from CBIT, if you find any job for me, please let me know. I am a software developer.

    Reply
  176. Jasper Chima says

    March 22, 2021 at 5:52 pm

    Although i used the "".join(reversed('my_num" ) #if you noticed, my_num was a str and not an int so i need to understand your method.

    Reply
  177. jasper chima says

    March 22, 2021 at 5:47 pm

    Please, I do not understand the logic of your solution to Exercise number 9: Reverse a number and return True or False. Below is your code and by the side is how I understand it.
    I need assistance as I’m very new to programming.

    def reverseCheck(number):
        print("original number", number)  # let number = 121
        originalNum = number  # original number = 121.
        reverseNum = 0  # reverseNum  = 0
        while (number > 0):  # while 121 > 0:
            reminder = number % 10  # remainder = 121% 10, therefore remainder == 1.
            reverseNum = (reverseNum * 10) + reminder  # reverseNum = (0 * 10) + 1, therefore reverseNum == 1
            number = number // 10  # number = 121 // 10, therefore number == 12
        if (originalNum == reverseNum):  # if (121 == 1):
            return True  # return True . How does 121 equals 1? i'm confused
        else:
            return False
    
    
    print("The original and reverse number is the same:", reverseCheck(121))

    Thanks for your clarification in advance. I love your webpage. God bless and increase you.

    Reply
    • Jasper Chima says

      March 22, 2021 at 7:23 pm

      Dear founder o Pynative,
      Sorry for disturbing this comment section with questions.
      As regards my earlier question to exercise 9, I now fully understood the logic behind your solution.
      Exercise 11 helped me better. The comments (#) you included were very pivotal to my understanding.
      Thank you once again.

      Reply
  178. Cholavendhan says

    March 19, 2021 at 2:32 pm

    Wonderful set of examples.. Great Work dude…

    Reply
    • Vishal says

      March 21, 2021 at 11:24 am

      Thank you, Cholavendhan.

      Reply
  179. Avinash Reddy says

    March 16, 2021 at 1:51 am

    Must Appreciated .
    Nice excercises

    Reply
    • Vishal says

      March 16, 2021 at 11:36 am

      Thank you, Avinash.

      Reply
  180. **Andre : ) : ) says

    March 14, 2021 at 11:28 pm

    Thank u sir for the exercises….. : )

    * Andre*

    Reply
  181. Khan says

    March 14, 2021 at 11:23 pm

    Really helpful for PYTHON beginners… pls add more resources like this

    Reply
  182. Rashin says

    March 14, 2021 at 11:14 pm

    Exercise 14

    
    n = 5
    while n>=1 :
        print('* '*n,'\n')
        n -= 1
    
    Reply
  183. Rashin says

    March 14, 2021 at 11:08 pm

    #EX 4

    txt = 'pynative'
    n = 4
    print( txt [ n : ] )
    Reply
  184. Rashin says

    March 14, 2021 at 11:07 pm

    Thank u sir

    Reply
  185. Satheesh says

    March 13, 2021 at 8:33 am

    Q3:

    print(given_string[1::2])
    Reply
  186. Petr says

    March 11, 2021 at 6:57 pm

    Exercise 3
    If you have text with 7 letters (length=7) the index of last letter is [6].
    So in order to get it printed you need range from 0 to 7 (length) as the 7 is not included.
    Having the length – 1 as in the solution is not correct.

    If you would remove the “e” from Pynative – the “v” with index [6] wouldn’t get printed as the range would be from 0 to 6 and 6 wouldn’t be included.

    Just minor detail 🙂

    Reply
  187. simanta says

    February 23, 2021 at 8:40 pm

    great sir. really helpful for beginners

    Reply
    • Vishal says

      March 2, 2021 at 8:54 pm

      You’re Welcome.

      Reply
  188. Matt says

    February 17, 2021 at 12:41 am

    There is something wrong with your commenting system. I try to hit “reply” and it does nothing. Could it be a browser plugin or something?

    Reply
    • Vishal says

      February 19, 2021 at 7:55 am

      Hey Matt, It is working as expected. Can you please try again.

      Reply
  189. Matt says

    February 16, 2021 at 2:30 am

    Greetings,

    I have just started learning Python. However, I have experience in other OOL. I have a few issues with your examples.

    1. It’s difficult what you’re expecting to see as output. For instance, #12. The output you have there has two spaces between the initial integer and it’s product. So, I was trying to format that as such and it was starting to get messy. Your solution is what I would have done if I didn’t’ expect to have two spaces.

    The same applies to the tax rate problem. I thought that is what you wanted to see for output. But, obviously you just wanted the number.

    The examples with the reverse comparisons where easy to do with slicing, but you had this over complex way of taking an integer and using multiple loops to reverse the value. I just converted them to strings and used slicing. Then, back to integers.

    It’s been very helpful and I will continue to use it. However, I don’t think you should be presumptuous and expect someone to know exactly it is you’re looking for.

    Just my 2 cents.

    Reply
    • Iván says

      January 1, 2023 at 2:42 am

      agree

      Reply
  190. Vanishri says

    February 5, 2021 at 11:39 am

    2 and 3 ques “int object is not callable”

    Error is displaying

    Reply
  191. Gurpreet singh says

    January 30, 2021 at 2:09 pm

    
    li=[1, 45,3,55,1]
    if li[0]==li[4]:
         print("True") 
    else:
            print("False")
    Reply
  192. Iwanttolearn says

    January 28, 2021 at 1:56 pm

    Hi I’m also a Beginner, This is my second day of reviewing some Exercises.
    I can’t even type any single line code.

    Reply
  193. MJ says

    January 25, 2021 at 12:23 pm

    Please type the code for the following:-

    1)
    Input three city names from the user. Store these names in a list. Shift all the three names to a single variable and delete the list.
    2)
    Input three numbers from the user and create a list containing these numbers. Insert number 25 at the second position and finally calculate the product of all the elements of the list.

    Reply
  194. Prayas says

    January 21, 2021 at 8:20 pm

    Question no.15 has a better answer XD

    
    def exponenet (base, exp):
        x=base**exp
        print(str(base), "raised to the power", str(exp), "is : ", x)
    exponenet(6,2)
    Reply
  195. Prayas says

    January 21, 2021 at 8:18 pm

    Question no 15 has a better solution XD:

    def exponent (base, exp):
        x=base**exp
        print(str(base), "raised to the power", str(exp), "is : ", x)
    exponent(6,2)
    Reply
  196. yahia mahmoud says

    January 12, 2021 at 12:39 am

    The most helpful site ever learned a lot, thanks.
    ———————–

    The_most_helpful_site_ever = int(len(input("insert every word in pynative.com ")))
    for i in range ( The_most_helpful_site_ever) :
        print("thanks ", end = "")
    Reply
    • Vishal says

      January 12, 2021 at 8:37 am

      Thank you, Yahia. I am glad you liked it.

      Reply
  197. Amrita Mehta says

    December 27, 2020 at 5:01 pm

    Question 5

    
    l = [10, 20, 30, 40, 10]
    if l[0] == l[-1]:
        print("True")
    else:
        print('False')
    
    Reply
    • Akang_senju says

      August 5, 2021 at 6:13 pm

      l = [10, 20, 30, 40, 10]
      print( True if l[0] == l.pop() else False)
      Reply
  198. Amrita Mehta says

    December 27, 2020 at 4:45 pm

    Question 1

    def calc(n1,n2):
        product = n1 * n2
        
        if product > 1000:
            return n1 + n2
        else:
            return product
        
    print(calc(3000,2))
    Reply
    • Nidhi Mehta says

      December 27, 2020 at 4:56 pm

      Q3.

      
      str1 = input('enter string:')
      str1[::2]
      
      Reply
  199. Rajkumar says

    December 17, 2020 at 8:47 pm

    Question 14: Print downward Half-Pyramid Pattern with Star (asterisk)

    for i in range(5, 0,-1):
        print(' *' * i)
    Reply
  200. Noname says

    November 11, 2020 at 6:55 pm

    Hi! I am a beginner in Python, so thanks a lot for the exercises. I have got a question concerning exercise 3. I have written the following code:

     
    def thatsweird(a):
        for x in a :
            if a.index(x)%2==0:
                print (x)
                
    a= list(input("word: " ))
    thatsweird(a)
    

    It works fine as long as there are no identical letters in a row in which case it messes up. I would be very grateful if someone explained to me why or just referred me to an explanation online as I didn’t find one (yet):)

    Thanks!

    Reply
    • Z09 says

      November 14, 2020 at 7:50 pm

      
      string = input("Enter your word: ")
      print("Original string is " + string)
      print("Printing only even index chars")
      for i in range(len(string)):
          even = i%2
          if even == 0:
              print("index["+ str(i) + "] " + string[i])
      print("NOTE:THAT SPACE ALSO COUNTS AS A CHAR\n\tTHE COUNT STARTS FROM ZERO NOT ONE")
      Reply
    • Priyank Palshetkar says

      November 24, 2020 at 4:57 pm

      Easy solution for exercise 3

      
      str="pynative"
      for i in range(0,len(str)-1,2):
          print(str[i])
      
      Reply
    • ayush says

      December 14, 2020 at 10:10 am

      name='umbrella'
      for i in range(0,len(name)-1,2): 
          print(name[i])
      Reply
    • Multicast says

      January 10, 2021 at 3:21 am

      Hi Noname, Whenever you try to find an index for a character Python would return the index where ever it finds it first, so if your string has an identical char Python will just give you the index for the first occurring char. hope it helps.

      Below is how I approached this problem:

      def even_str(my_str):
          n = len(my_str)
          for i in range(0, n, 2):
              print(my_str[i])
      even_str("pynative")
      Reply
  201. suraj says

    November 11, 2020 at 4:47 pm

    # # Question 14: Print downward Half-Pyramid Pattern with Star (asterisk)

    n=5
    for i in range(6):
    #     print(i)
        z= "* " * n
        n= n-1
        print(z)
    Reply
  202. Rushikesh says

    November 2, 2020 at 3:07 pm

    Que 5:

    def isFirst_And_Last_Same(numberList):
        print("Given list is ", numberList)
        firstElement = numberList[0]
        lastElement = numberList[-1]
        if (firstElement == lastElement):
            return True
        else:
            return False
    
    My_list = []
    n = int(input('number of elements = '))
    for i in range(0,n):
        ele = int(input(f'ele {i+1} = '))
        My_list.append(ele)
    Reply
    • Sebz says

      November 27, 2020 at 4:59 am

      Easy solving for Q. 5

      list1 = [10, 20, 30, 40, 10]
      
      bool = list1[0] == list1[-1]
      
      print(f'The result is {bool}')
      Reply
  203. Rob says

    October 28, 2020 at 7:50 pm

    Question 13:

    Why is it print("\t\t") and not print("\n")?
    I thought \t creates a tab or indent. \n drops a line doesn’t it?
    Alos why \t\t and not just \t

    Thanks. I enjoyed the questions finding some pretty tricky!!!

    Reply
    • Lokesh says

      November 9, 2020 at 1:52 pm

      \t\t means is two tab

      Reply
  204. Attiya says

    October 23, 2020 at 5:14 am

    def asterisks(input):
         if input > 0:
             for y in range(input,0,-1):
                  print('*'*y)
    Reply
  205. jamar says

    October 21, 2020 at 8:28 pm

    rows=5
    for x in range(rows,0,-1):
        print('*'*x)
        print('\n')
    Reply
    • suraj says

      November 11, 2020 at 4:45 pm

      I have tried this way

      n=5
      for i in range(6):
      #     print(i)
          z= "* " * n
          n= n-1
          print(z)
      Reply
  206. Sindhu says

    October 21, 2020 at 7:53 pm

    For question 6,we can have like this,

    
    def CompareLists(givenList):
        return (givenList[0]== givenList[len(givenList)-1]) 
    list1 = [10, 20, 30, 40, 10]
    list2 = [10, 20, 30, 40, 50]
    print(CompareLists(list1))
    print(CompareLists(list2))
    Reply
  207. Supriya says

    October 19, 2020 at 7:56 pm

    Question 15 can have a simpler solution . Which is :

    def exponent(base, exp):
        return f'{base} raises to the power of {exp} is {base**exp}'
    
    print(exponent(5, 4))
    
    Reply
    • Sindhu says

      October 23, 2020 at 7:54 pm

      Yeah!!.. That’s what am going to say!!

      Reply
  208. Abdu says

    October 16, 2020 at 10:26 pm

    question 14

     for x in range(6,0,-1):
        print(x*" *")
    Reply
  209. Abdu says

    October 16, 2020 at 10:23 pm

    question 15

    def exponent (base,exp):
    
        return base**exp
    
    
    print(exponent(5,4))
    Reply
  210. Abdu says

    October 16, 2020 at 9:26 am

    question 11.

    num = int(input("Enter any number: "))
    reverse = 0
    lst = []
    while num > 0:
        reminder = num%10
        reverse = (reverse*10)+reminder
        num = num//10
        lst.append(reminder)
    
    
    print(*lst,sep=" ")
    Reply
    • Abdu says

      October 16, 2020 at 9:28 am

       num = int(input("Enter any number: "))
      reverse = 0
      lst = []
      while num > 0:
          reminder = num%10
          reverse = (reverse*10)+reminder
          num = num//10
          lst.append(reminder)
      
      
      print(*lst,sep=" ")
      Reply
      • corleone1986 says

        June 27, 2022 at 11:20 pm

        Use ‘pre’ tag for posting code. E.g.

         def checking(num):
            x = str(num)[::-1].replace("" , " ")
            print(x)
        
        checking(7658)
        Reply
  211. Attiya says

    October 10, 2020 at 5:05 am

    Simplified solution for question 14 without nested loop:

    rows=5
    for x in range(rows,0,-1):
        print('*'*x)
        print('\n')
    Reply
  212. Isaac says

    October 9, 2020 at 1:35 am

    Question 3

    
    cv=0
    
    str="pynative"
    for s in str:
        if cv %2==0:
            print(s)
        cv+=1
    Reply
  213. Isaac says

    October 9, 2020 at 1:31 am

    Question 1

    
        num1=20
        num2=30
        product=num1*num2
        if product > 1000:
            print(num1 + num2)
        else:
            print(product)
    Reply
  214. Isaac says

    October 9, 2020 at 1:25 am

    Question 12

    
        def exponent(base,exp):
            return base**exp
    a=exponent(2,5)
    print(a)
    Reply
  215. Emerson says

    September 22, 2020 at 12:14 pm

    The question to exercise 6:
    Why does a “None” appear at the end of my output?

    Here is my code:

    def onlyDivisible(numbersList):
        print("given list is", numbersList)
        print("Divisible of 5 in a list")
        for n in numbersList:
            if n % 5 == 0:
                print(n)
    
    
    myList = [10, 20, 33, 46, 55]
    print(onlyDivisible(myList))
    Reply
    • Sumanth says

      September 24, 2020 at 10:38 am

      Hello Emerson
      Instead of using use

      Reply
    • Sumanth says

      September 24, 2020 at 10:41 am

      instead of using use

      Reply
    • Sumanth says

      September 24, 2020 at 10:43 am

      Instead of using print(onlyDivisible(myList)) use onlyDivisible(myList)

      Reply
  216. Sumit says

    September 11, 2020 at 1:11 pm

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

    def exponential(base,exp):
        return(f"{base} raise to power {exp}: {base**exp}")
    
    base = int(input("Enter your base integer :"))
    exp = int(input("Enter your exponential integer: "))
    print(exponential(base,exp))
    Reply
  217. Youssef Hmini says

    September 7, 2020 at 2:24 am

    Love it! Especially for beginners like me!

    Reply
  218. el empotrador says

    September 2, 2020 at 12:08 am

    jhere I share my solutions with you, hope this helps.
    question 1:

    print("to play this game you have to introduce two numbers.")
    number1 = input("please introduce the first number: ")
    number2 = input("please introduce the second number: ")
    product = int(number1) * int(number2)
    if product >= 1000:
        sum = int(number1) + int(number2)
        print(sum)
    else:
        print(product)

    question 2:

    for elements in range(11):
        print("the current number is ", elements, "the previous number was: ", elements - 1 , "the sum is:  ", elements + elements - 1)
    

    question 3:

    letter = input("please introduce a word: ")
    print(letter[0: len(letter):2])
    

    question 4:

    string = str(input("please introduce a word: "))
    while True:
        n = input("please introduce a number shorter than the length of the shosen word: ")
        m = int(n)
        if n.isdigit() and int(n) > len(string):
            print("please introduce a shorter number than string`s length")
        elif n.isdigit() and int(n) < len(string):
            print(string[m:])
            break
    print("thanks for playing")

    question 5:

    listOfNumbers = input("please introduce five numbers separated by space: ")
    Numbers = listOfNumbers.split()#here i have leant how to accept a list as an input
    if (Numbers[0] == Numbers[4]):
        print("Given the list ", Numbers)
        print("the result is True")
    else:
        print("Given the list ", Numbers)
        print("the result is False")
    

    question 6:

     def divisibility(List):
        for elements in List:
            if elements % 5 == 0:
                print(elements)
    givenList = [10, 20, 33, 46, 55]
    divisibility(givenList) 

    question 7:

    string = input("please introduce a string in wich there is at least a repeated element: ")
    print("the shosen string is: ", string)
    elementToCount = input("please introduce the element you want to count: ")
    count = string.count(elementToCount)#to count how many time a element is repeated in a string I use the .count() mehtod. the estructure of this method is: namelist.count(the element we want to count)
    print(elementToCount, "appears ", count, "times in the string")

    question 8:

    for elements in range(1, 6):
        print(" ".join(str(elements) * elements))
    

    question 9:

    num1 = input("please introduce a number: ")
    if num1 == num1[-1::-1]:
        print("the original number ", num1, "is the same as its inverse")
    else:
        print("the original number is not equal to its inverse")
    

    question 10:

    list1 = [10, 20, 23, 11, 17] 
    list2 = [13, 43, 24, 36, 12]
    newlist1 = [ ] 
    newlist2 = [ ] 
    finallist = [ ]  
    for elements in list1:
        if elements % 2 == 0:
            newlist1.append(elements)#in this if statement I append the odd and even elements to two different list*
    for e in list2:
        if e % 2 != 0:
            newlist2.append(e)
    finallist = newlist1 + newlist2 #here I add the two different lists*
    print(finallist)
    

    question 11:

     number = input("please a list of numbers separated by space: ")
    givennumber = number.split()
    invertednumber = givennumber[-1::-1]
    separatednumber = " ".join(invertednumber)
    print(separatednumber) 

    question 12:

     totalIncome = int(input("please introduce your total income: "))
    first = int(10000) * float(0.0)#when writing floats i have to use a dot instead of a comma 
    second = int(10000) * float(0.1)
    remain = totalIncome - int(20000)
    final = remain * float(0.2)
    totalTax = first + second + final
    print("$1000 * 0 % + $1000 * 0,1 % + $ ",remain, " * 0,2 = $",totalTax)
    

    question 15:

    while True:
        base = input("please introduce the base of the power: ")
        if not base.isdigit():
            print("please introduce a number")
        else:
            break
    while True:
        exp = input("please introduce the exponent: ")
        if not exp.isdigit():
            print("please introduce a number")
        else:
            break
    def exponent(bs,ex):
        power = int(bs)**int(ex)
        return power
    print(exponent(base,exp))
    
    Reply
  219. bhavya says

    August 27, 2020 at 11:02 pm

    a = int(input("Input an integer : "))
    n1 = int( "%s" % a )
    n2 = int( "%s%s" % (a,a) )
    n3 = int( "%s%s%s" % (a,a,a) )
    print (n1+n2+n3)

    I saw this somewhere… I’m stuck here.. what is this % s
    In an earlier code, I saw %e and %i…
    please if anyone can explain, I’d be thankful

    Reply
    • Rakesh Singh Choudhary says

      August 31, 2020 at 9:00 pm

      1 .

      a = int(input("Input an integer: "))

      Input method converts the user input to a string and then returns it, hence ‘int’ is prefixed here so that we can perform addition operation at the end.

      2.

      n1 = int("%s" %a)

      The modulo % is referred to as a “string formatting operator”, here s stands for string representation. Here n1 = 4 if a is 4. You can run type(n1) and see it is str without int being prefixed.
      3.

      n2 = int( “%s%s” % (a,a) )

      Similarly, here n2 = 44 if a is 4
      4.

      n3 = int( “%s%s%s” % (a,a,a) )

      Again, n3 = 444 if a is 4

      Hence, n1 +n2 + n3 = 492
      Also, % e and % i are exponential and integer representations respectively. You can play around by putting these in print method.

      Reply
  220. el empotrador says

    August 26, 2020 at 6:14 pm

    I could not solve exercise two. However, now i found what i consider the easiest solution:

    for elements in range(11):
        print("the current number is ", elements, "the previous number was: ", elements - 1, "the sum is: ", elements + elements - 1)
    Reply
  221. serpilozdemir says

    August 22, 2020 at 5:34 pm

    Exercises are very excited for me thx
    question 15 :

    base=6
    exponent=2
    print('6 raises to power of 2 is', pow(base,exponent))
    Reply
    • El empotrador says

      August 25, 2020 at 11:19 am

      Hello everyone,. I am new at learning python and I’ve done the first exercise in a different way. Can someone please tell me if it is correct or not??

       print("please introduce two numbers")
      number1 = input("the first number you want to introduce is:  ")
      
      number2 = input("the second number you want to introduce is: ")
      
      product = int(number1) * int(number2)
      if product > 1000:
      	sum = int(number1) + int(number2)
      	print("the sum of number1 and number2 is: ", sum)
      else:
      	print("the product of numer1 and number2 is: ", product) 
      Reply
  222. Soumya says

    August 21, 2020 at 9:39 pm

    for question 15:

    b=int(input("enter base"))
     e=int(input("enter exp"))
    print(b,"raise to", e, "is",b**e)
    Reply
  223. DMS KARUNARATNE says

    August 17, 2020 at 4:36 pm

    Question No 9: another way to do it

    def rever(num):
        #print (str(num))
        revnum=("".join(reversed(str(num))))
        #print (revnum)
        if str(num)==str(revnum):
            return True
        else:
            return False
    Reply
    • Huirong Ai says

      October 13, 2020 at 9:46 am

      Mine is similar:

        def reverseCheck(number):
          print("original number:", number)
          new_number = int(str(number)[::-1])
          print("reversed number:", new_number)
          
          if number == new_number:
              print("The original and reverse number is the same")
          else:
              print("The original and reverse number is not the same") 
      Reply
    • corleone1986 says

      June 27, 2022 at 11:26 pm

      def checking(num):
          x = str(num)
          y = x [::-1]
          if x == y :
              print("yes")
          else:
              print("No")
      
      checking(7658)
      Reply
  224. Dev says

    August 14, 2020 at 11:49 pm

    hey guys!!! Here’s a program from which u can code a calculator:

    print("what operation do u want")
    operator = input("Enter either +, -, * or /: ")
    
    num1 = int(input("Enter first number: "))
    num2 = int(input("Enter second number: "))
    
    if operator == '+':
      print(num1, operator, num2, "=", num1+num2)
    elif operator == '-':
      print(num1, operator, num2, "=", num1-num2)
    elif operator == '*':
      print(num1, operator, num2, "=", num1*num2)
    elif operator == '/':
      print(num1, operator, num2, "=", num1/num2) 
    else:
      print("Invalid Operator")
    Reply
    • Kundan Chaudhari says

      August 20, 2020 at 11:10 pm

      what if I want more than 2 values operations

      Reply
  225. Dev says

    August 14, 2020 at 11:15 pm

    Ques. 15:

    def exponent(base, exp):
        result = base**exp
        print(base, "raises to the power ", exp, "is: ", result)
    
    (exponent(5, 4))
    Reply
    • Dev says

      August 14, 2020 at 11:16 pm

      I hope this would be helpful to others!!!!
      Stay Home!!
      Stay Safe!!!!

      Reply
    • Arkaprava Biswas says

      August 19, 2020 at 3:34 am

      best way

      Reply
  226. Anusha says

    August 6, 2020 at 10:53 am

    question 15:

    def exponent(base,exp):
        return base**exp
    print(exponent(5,4))
    Reply
  227. Kristofer Kangro says

    July 28, 2020 at 3:11 pm

    Was its purpose to make solutions as difficult as possible simply for learning new ways of writing a simple program?
    Some of the questions solutions were very challenging for me to understand as a beginner but I think it has a good and bad part to it. Bad side to it might be overcomplicating a simple question but on the other end it will teach you new ways to write a simple program.
    In conclusion, questions were great and on-the-level for a beginner. Thank you!

    Reply
    • Vishal says

      July 29, 2020 at 11:13 am

      Thank you Kristofer for your valuable feedback.

      Reply
    • Filippi says

      August 12, 2020 at 8:48 pm

      Your point is totally nonsense. The goal here is not to solve this problem and print an output, but study and learn python. The answares MUST be as difficult as possible, as this represents a guide were you can follow to learn a little bit, for free by the way.
      Vishal: Your job here was perfect, keep doing your best to put the most difficult answare you can get, thank you very much, best regarts

      Reply
  228. Harshit Rautela says

    July 26, 2020 at 1:00 pm

    Q15 simple solution

    def exponent(base, exp):
        result = base**exp
        print(result)
    
    
    print(exponent(5, 4))
    Reply
  229. HARSH says

    July 23, 2020 at 4:53 pm

    #SHORTEST WAY OR QUESTION 9
    
    number=input("ENTER THE NUMBER :")
    
    if number==number[::-1]:
        print("PALINDROME")
    else:
        print("NOT A PALINDROME")
    Reply
    • charlot fx says

      September 6, 2020 at 9:55 pm

      yeah i did the same way

      Reply
    • Dushyant says

      October 13, 2020 at 8:36 pm

      This code is reversing a string and hence is inaccurate since any input taken in python without other function is always a string. You need to write different code for reversing a number which will be type integer

      Reply
  230. Harshit Rautela says

    July 22, 2020 at 1:18 pm

    Q3 simple solution:

    
     def display_char(name):
        for i in range(0, len(name)):
            while i < len(name):
                print(name[i])
                i += 2
            break
    
    print(display_char("pynative"))
    Reply
    • Dev says

      August 14, 2020 at 11:27 pm

      here’s a solutio for Ques:3:

      list1 = ["p","y","n","a","t","i","v","e"]
      list2 = list1[0:8:2]
      
      for str in list2:
        print(str)
      Reply
  231. Er. Tushar says

    July 14, 2020 at 2:01 am

    #Q15 Simple Solution

    
    def exponent(base,exp):
        out=base**exp
        return print(out)
    
    print("2 raise to the power 5 is:")
    exponent(2,5)
    print("-------------------------------------------")
    print("5 raise to the power 4 is:")
    exponent(5,4)
    Reply
  232. Nilotpal Shanu says

    July 10, 2020 at 12:29 am

    Q no.4

    
    Str = "pynative"
    host = str[4: ]
    print(host)
    
    Reply
    • Rithesh says

      July 11, 2020 at 11:32 am

      tive
      Reply
  233. Aka code_teen says

    July 6, 2020 at 8:20 pm

    # Q2 Simple Solution :

    
    prev_num = 0
    for cur_num in range(10):
         print(f" current num is {cur_num} prev num is {prev_num} Sum: {cur_num+prev_num}")
         prev_num = cur_num

    Good Luck! 😉

    Reply
  234. Alex says

    July 5, 2020 at 7:18 am

    My daughter studying from your tutorials; it is great!
    please continue adding more exercises.

    Reply
    • Vishal says

      July 6, 2020 at 7:41 am

      Thank you, Alex.

      Reply
      • Tuur Six says

        July 6, 2020 at 7:47 pm

        oefening 3:

        
        Has a little mistake if you type in a word that is even you don't have the last letter:
        It should be:
        def letter(let):
            for index in range(0,len(let)-0,2):
                print("index[",index, "] " + let[index])
        inputStr = "can"
        letter(inputStr)
        Reply
  235. Alimul Nishat says

    July 4, 2020 at 11:01 pm

    Hello Vikash bro,
    I am a beginner of python programming language and found this platform best for solving problems for beginners.

    And i found an alternative, short and easiest way to solve the problem no 14 is :

    for i in range(5,0,-1):
        print(i*" *")
    
    Reply
  236. Khalid says

    June 30, 2020 at 9:33 pm

    My solution for number 9

    
    def reverse_check(original_num):
        """"Reverses a given number and compares it with the original"""
        original_nums = str(original_num)
        num_len = len(original_nums)
        reverse_num = ""
    
        for num in range(num_len):
            reverse_num += original_nums[num_len - num - 1]
    
        if int(original_num) == int(reverse_num):
            print(f"original number {original_num}\nThe original and reverse number are the same: True")
        else:
            print(f"original number {original_num}\nThe original and reverse number are the same: False")
    
    
    reverse_check(1221)
    
    Reply
  237. Khalid says

    June 30, 2020 at 9:31 pm

    My code for number9

    
    def reverse_check(original_num):
        """"Reverses a given number and compares it with the original"""
        original_nums = str(original_num)
        num_len = len(original_nums)
        reverse_num = ""
    
        for num in range(num_len):
            reverse_num += original_nums[num_len - num - 1]
    
        if int(original_num) == int(reverse_num):
            print(f"original number {original_num}\nThe original and reverse number are the same: True")
        else:
            print(f"original number {original_num}\nThe original and reverse number are the same: False")
    
    
    reverse_check(1221)
    Reply
  238. Houari_Aouinti says

    June 27, 2020 at 4:55 am

    Exercice 01:

    
    count = lambda a, b: a * b if a * b < 1000 else a + b
    print(count(25, 40))
    

    Exercice 02:

    
    def up(pNum, cNum, i):
        for n in range(i):
            print("Current Number:", cNum, "Previous Number:", pNum, "Sum:", cNum + pNum)
            pNum, cNum = cNum, cNum + 1
    up(0, 0, 10)
    

    Exercice 03:

    
    def pEven(string):
        for m in range(len(string)):
            if m % 2 == 0: print(f"index {m} {string[m]}")
    pEven("pynative")
    

    Exercice 04:

    
    split = lambda string, n: string[n:]
    print(split("pynative", 4))
    

    Exercice 05:

    
    arr = [10, 20, 30, 40, 10]
    firstLast = lambda arr: True if arr[0] == arr[-1] else False
    print(firstLast(arr))
    

    Exercice 06:

    
    array = [10, 20, 33, 46, 55]
    def arrayDvd(array):
        for i in array:
            if i % 5 == 0: print(i)
    arrayDvd(array)
    

    Exercice 07:

    
    string = "Emma is good developer. Emma is a writer"
    countString = lambda string: print(f"Emma appeared {string.count('Emma')} times")
    countString(string)
    

    Exercice 08:

    
    def pattern(n, i):
        while n > i:
            print(f"{str(i) * i}")
            i +=1
    pattern(10, 1)
    

    Exercice 09:

    
    rev = lambda number: True if number == number[::-1] else False
    print(rev(str(121)))
    

    Exercice 10:

    
    fList, sList, rList = [10, 20, 23, 11, 17], [13, 43, 24, 36, 12], []
    def oddEve(fl, sl):
        for i, j in zip(fList, sList):
            if i % 2 != 0 or j % 2 == 0: rList.append(i); rList.append(j)
        print(rList)
    oddEve(fList, sList)
    
    Reply
    • karan says

      August 30, 2020 at 6:45 pm

      wowww………………!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!1

      Reply
  239. Daniel says

    June 25, 2020 at 1:40 am

    Hello,

    I just started learning how to program. Well, just learning one program, Python. Now, I’m completely new to this stuff and I feel overwhelmed sometimes. Can anyone share some very easy easy problems that I can work on?

    Thank you guys!

    Reply
    • Vishal says

      June 25, 2020 at 3:13 pm

      you’re welcome, Daniel

      Reply
  240. Son_Volam says

    June 23, 2020 at 5:44 pm

    #Q9:

    num1 = input()
    
    if num1 == num1[-1::-1]:
        print("TRUE")
    else:
        print("FALSE")
    Reply
    • HASAN says

      July 21, 2020 at 10:56 am

      Q(9).

      
      x=input('Enter a number: ')
      if x[::-1]==x:
      	print(True)
      else:
      	print(False)
      Reply
    • el empotrador says

      August 31, 2020 at 6:23 pm

      thanks for publishing your answer, it was very helpful for me

      Reply
  241. Son_Volam says

    June 23, 2020 at 5:44 pm

    #Q9:

    
    num1 = input()
    
    if num1 == num1[-1::-1]:
        print("TRUE")
    else:
        print("FALSE")
    Reply
  242. Steph says

    June 17, 2020 at 7:43 pm

    Regarding problem 9, is it bad practice or something to convert an int to a string to reverse it and then convert it back? This process just seems more straight forward than the answer provided.

    Here is what I came up with(includes some of the answer):

    
    def reverseCheck(org_number):
      test_string = str(org_number)
      reverse_str = test_string[::-1]
      if int(reverse_str) == org_number:
        print("True")
      else: 
        print("False")
      print(int(reverse_str))
    
    print("Is the original and reverse number the same?", reverseCheck(121))
    
    Reply
  243. thet wai htut says

    June 17, 2020 at 11:55 am

    question 8

    
    for i in range(1,6):
        for j in range(1,i+1):
            print(i,end='')
        print()
    
    Reply
  244. Dhyan says

    June 13, 2020 at 4:04 pm

    Hey buddy doing a wonderful job by posting such useful exercise for practice 🙂 keep it up

    Reply
    • Vishal says

      June 15, 2020 at 5:08 pm

      Thank you, Dhyan.

      Reply
  245. Nikita says

    June 9, 2020 at 8:26 pm

    Please bring back the old code editor 🙁

    Reply
    • Vishal says

      June 10, 2020 at 12:21 am

      Hey Nikita, Please let us know if you are facing any problem. Thank you

      Reply
      • Dev says

        August 14, 2020 at 11:34 pm

        Sir, I only knew about the only theory about Python but when I explore on chrome for some exercises I selected this…. and this has improved my coding skills!! God Bless You
        Stay Home!!!!
        Stay Safe!!!!

        Reply
  246. narender says

    June 8, 2020 at 12:01 pm

    Question 3:
    solution :

    
    s = input(‘Enter your string : ‘)
    L = len(s)
    print(s[0:L:2])
    Reply
    • Jon Blackwell says

      June 24, 2020 at 3:51 am

      You don’t need line 2, and variable “L” in line 3 for your solution.

      Reply
  247. Ray says

    June 7, 2020 at 11:20 pm

    Thank you very much for the exercises. They are extremely helpful for a beginner.
    Keep up the good work

    Reply
    • Vishal says

      June 8, 2020 at 9:26 am

      You are welcome, Ray

      Reply
  248. Logan Peterson says

    June 7, 2020 at 11:28 am

    For the Emma question, I have a short solution that works very well.

    a = 'Emma is a good developer. Emma is a good writer'
    print(a.count('Emma'))
    Reply
  249. Angshumaan Basumatary says

    June 6, 2020 at 5:35 pm

    Question 10: Tried using user input

    def calculate(a, h):
        k = [z for z in a if z % 2 != 0]
        b = [y for y in h if y % 2 == 0]
        c = k + b
        return c
    
    
    a = int(input("Enter the size: "))
    angshu = [int(x) for x in input("Enter first list").strip().split()][:a]
    basu = [int(x) for x in input("Enter second list").strip().split()][:a]
    i = calculate(angshu, basu)
    print(i)
     
    Reply
  250. John says

    June 3, 2020 at 4:11 pm

    #Question 9 alt. solution

    def isrev(x):
      x1 = list(str(x))
      x2 = list(str(x))
      x2.reverse()
      print(x1)
      print(x2)
      print(x1==x2)
      
    isrev(121)
    
    Reply
  251. Steven-r says

    May 23, 2020 at 5:29 am

    Hi Vishal
    As a newbie, your exercises come in really helpful and useful. Thanks so much for posting! much appreciated.

    Reply
    • Vishal says

      May 26, 2020 at 7:48 pm

      You are welcome, Steven-r

      Reply
  252. jyotirmoy ghose says

    May 23, 2020 at 12:17 am

    Question 1:

    def mul_or_sum(num1,num2):
       
        output= num1*num2
        if(output>1000):
            value = num1 + num2
            print("the result is : ", value)
        else:
            print("the result is : ", output)
    
    num1= int(input("enter num1: "))
    num2=  int(input("enter num2: "))
    mul_or_sum(num1,num2)
    
    

    Question 2:

    def current_previous(number):
        for i in range(1,number):
             print("current number :", i,"previosu number: ", i-1,"sum: " ,i+ i-1)
    
    number= int(input("enter the numebr: " ))
    current_previous(number)
    

    Question 3:

    def display_even_number_string(st):
        lent=len(st)
    
        for i in range(0,lent,2):
            print("index[", i ,"]", st[i])
    
    
    st= str(input("enter string : "))
    print("original string:",st)
    display_even_number_string(st)
    

    Question 4:

    def remove_string_char(st):
        
        New_st= st[number ::]
        print("remaining strings are ---> :",str(New_st))
    
    st = str(input("enter string : ")) 
    st_len=len(st)
    print("length of the string is :",st_len)
    number= int(input("enter the number < string len : "))
    remove_string_char(st)
    

    Question 5:

    def list_check(list):
         if(list[0]==list[-1]):
             print("result is: ",bool(1))
         else:
             print("result is: ",bool(0))    
    
    list=[]
    number = int(input("enter number : "))
    for i in range(number):
        value=int(input("entered number to the list : "))
        list.append(value)
        print("after adding :",list)
    list_check(list)
    
    

    Question 6:

    list=[]
    number = int(input("enter number : "))
    for i in range(number):
        value=int(input("entered number to the list : "))
        list.append(value)
        print("after adding :",list)
    
    for i in range(number):
        if(list[i]%5==0):
            print(list[i],end=" ")
        else:
            print("nothing found") 
    
    

    Question 7:

    st=str(input("enter your string: "))
    def word_count(st):
        count = dict()
        words = st.split()
        print(words)
        for i in words:
            if i in count:
                count[i] += 1
            else:
                count[i] = 1
        return count
    print( word_count(st),end=" ")
    

    Question 8: Print the following pattern

    for i in range(1,6):
        for j in range(i):
            print(i,end=" ")
        print("\n")
    

    Question 9:

    number = 12
    reverse=0
    while(number>0):
         remainder = number%10
         print(remainder)
         reverse = (reverse*10)+remainder
        
         number=number//10
         
    print(reverse)
    

    Question 10:

    list1=[10, 20, 23, 11, 17]
    list2=[13, 43, 24, 36, 12]
    value1= len(list1)
    value2=len(list2)
    new_list1=[]
    new_list2=[]
    final_list=[]
    for i in list1:
        if(i%2!=0):
            new_list1.append(i)
    
    for j in list2:
        if(j%2==0):
            new_list2.append(j)    
    
    final_list=new_list1+new_list2
    print(new_list1)    
    print(new_list2)  
    print(final_list)    
    
    Reply
  253. jyotirmoy ghose says

    May 23, 2020 at 12:16 am

    list1=[10, 20, 23, 11, 17]
    list2=[13, 43, 24, 36, 12]
    value1= len(list1)
    value2=len(list2)
    new_list1=[]
    new_list2=[]
    final_list=[]
    for i in list1:
        if(i%2!=0):
            new_list1.append(i)
    
    for j in list2:
        if(j%2==0):
            new_list2.append(j)    
    
    final_list=new_list1+new_list2
    print(new_list1)    
    print(new_list2)  
    print(final_list)    
    
    Reply
  254. Sandeep says

    May 22, 2020 at 11:22 pm

    Alternative way for question 1: **please excuse for any mistakes

     
    def multiplication_or_sum(num1, num2):
        if (num1 * num2) > 1000:return('The result is %s' %(num1+num2))
        else:return('The result is %s' %(num1*num2))
    
    num1 = int(input('enter first number:\n'))
    num2 = int(input('enter second number:\n'))
    print(multiplication_or_sum(num1, num2))
     
    Reply
  255. keshav ranjithlall says

    May 7, 2020 at 10:06 pm

    hey bro for solution 2: what is the + 4 in the [i : 1 + 4] for?

    Reply
  256. Mr.HAZANI says

    April 20, 2020 at 7:46 pm

    One point to clear:
    I found that the comment section ignored the spaces that I put behind every line and changed a few marks.
    Paste this modified version in your Python to get it working:

    #Principal Variable
    number = 121
    
    #Function
    def ReverseNum (num):
        snum = str(num)
        reversed = snum [::-1]
        Reversed = int(reversed)
        return Reversed
    

    #Output :

    print("original number", number)
    if number == ReverseNum(number) :
        print("The original and reverse number is the same:", True)
    else:
        print("The original and reverse number is the same:", False)
    
    Reply
    • Oury says

      April 27, 2020 at 12:38 pm

      def same_backwards(num):
          '''returns true if num is the same when written backwards'''
          return str(num) == str(num)[::-1]
      
      Reply
  257. Santosh says

    April 19, 2020 at 10:29 am

    Last Question :

    list1 = [1,2,4,6,2,3]
    list2 = [3,432,433,22,442]
    
    list3 = [x for x in list1 if x % 2 != 0] + [x for x in list2 if x % 2 == 0]
    print(list3)
     
    Reply
    • Vishal says

      April 19, 2020 at 8:31 pm

      Thank you, Santosh for an alternative solution

      Reply
      • Ankana says

        April 25, 2020 at 8:26 am

        list1=[10,20,40,50,70]
        list2=[20,60,80,90]
        
        list3=list1[1::2]+list2[1::2]
        print(list3)
        
        
        Reply
  258. cyberhoax says

    April 15, 2020 at 5:13 pm

    A7. A very useful and short way to count the words in a string

    a = "Emma is good developer. Emma is a writer"
    c = a.count("Emma")
    print(c)
    
    Reply
    • Vishal says

      April 15, 2020 at 9:22 pm

      Hey cyberhoax, Thank you for an alternative solution.

      Reply
    • Nikhil K says

      April 27, 2020 at 10:18 pm

      a = "Emma is good developer. Emma is a writer"
      print(a.count("Emma"))
      
      Reply
    • mahesh says

      May 11, 2020 at 7:54 pm

      a = "Emma is good developer. Emma is a writer"
      c = a.count(input('enter the word: '))
      print(c)
      
      Reply
  259. saba nadiradze says

    April 3, 2020 at 12:22 am

    I am learning coding for 2 weeks and it totally impoved my skills. thank you for your exercises.

    Reply
    • Vishal says

      April 3, 2020 at 8:31 pm

      Hey Saba, Thank you for your kind words.

      Reply
      • Sidra says

        October 1, 2020 at 5:43 pm

        I need the answer of two questions can I plzz help me

        Reply
    • Nikhil muppidi says

      April 9, 2020 at 11:25 pm

      My code for question no 10:

      mylist1 =  [10, 20, 23, 11, 17]
      mylist2 =  [13, 43, 24, 36, 12]
      oddlist = [i for i in mylist1 if i%2!=0]
      evenlist = [i for i in mylist2 if i%2==0]
      print(oddlist+evenlist)
      
      Reply
      • Akbar says

        April 18, 2020 at 7:02 am

        best way

        Reply
  260. Anca says

    April 2, 2020 at 9:40 pm

    Hello! Can someone explain to me the solution for example 7?
    I dont understand what this line does:
    count += statement[i:i + 4] == ‘Emma’. I know about slicing but that +4 confuses me. thanx

    Reply
    • Vishal says

      April 3, 2020 at 8:44 pm

      Hi Anca,

      The statement is in the loop. Slicing starts with the start index (included) and ends at end index (excluded)

      For example, in the first iteration of a loop i =0

      Here statement[ 0 : 0 + 4] i.e., statement[0 : 4] and it will return “Emma” and if it is equal to “Emma”, then count will increment as statement become true and evaluate to value 1

      Reply
  261. Florian Fasmeyer says

    March 14, 2020 at 8:01 pm

    Alternative solutions to pynative.com – basic exercise for beginners.
    # Q1.

    a, b = int(input('Input a')), int(input('Input b'))
    prod = a*b
    print(prod if prod < 1000 else a+b)
    

    # Q2.

    nums = range(10)
    prev = 0
    for curr in nums:
      print(prev + curr)
      prev=curr
    

    # Q3.

    usr_str = input('Feed me a string!')
    print(usr_str[0::2], sep='\n')
    

    # Q4.

    str, n = 'pynative', 4
    print(str[n:])
    

    # Q5.

    nums = [1, 2, 3, 4, 5, 1]
    print(nums[0] == nums[-1])
    

    # Q6.

    nums = range(0, 60)
    print(*[num for num in nums if num%5 == 0], sep='\n')
    

    ''' Take-aways

    Q1 – When a condition is simple, use a ternary op.: x if (cond) else y.
    Q2 – If you are using indexers, you are doing it wrong!
    Q3 – Don't iterate lists, use accessors instead: [start: stop: step]
    Q4 – Please, use accessors instead! ref.Q3
    Q5 – DO NOT IF/ELSE a condition if you return booleans! YOU IMBECILE!
    Q6 – * operator is used to unpack: a, b, c = *[1, 2, 3]. You'll love it!

    Q+ – You gotta learn list comprehensions: [exp(item) for item in list].
    Q+ – List comprehensions with filters: [item for item in list if cond(item)]

    Reply
    • Florian Fasmeyer says

      March 14, 2020 at 8:05 pm

      As I can see you did not expect me to include tags!
      Too bad, I can’t change it now. 🙂

      Reply
      • Vishal says

        March 20, 2020 at 7:03 pm

        Thank you, Florian Fasmeyer. Now onwards Please add your code between <pre> </pre> tag for correct indentation.

        Reply
    • Vishal says

      March 20, 2020 at 6:58 pm

      Thank you Florian Fasmeyer for alternative solutions

      Reply
    • newbie noob says

      March 26, 2020 at 3:04 pm

      Hey. I have no idea about any of this. But on Q1 with the answer 1000?

      I’m so new to all of this I didn’t quite understand why the less than symbol is being used rather than the more than symbol. Thank you in advance

      Reply
      • Vishal says

        March 26, 2020 at 7:01 pm

        Hi newbie, I have updated the answer. In your case, the result should be 1000.

        Reply
    • jeena gurung says

      June 9, 2020 at 7:05 pm

      Thank you so much for the alternative solutions. Being a newbie to Python, I was struggling understand author’s solutions, you made it lot easier.
      Thank you so much again.

      Reply
  262. Junaid Ali says

    February 7, 2020 at 10:45 pm

    My Practice :

    #Question 1: Accept two int values from the user and return their product.
    # If the product is greater than 1000, then return their sum

    m=int(input("Enter Number: "))
    n=int(input("Enter Number: "))
    r=m*n
    if r>1000:
        print(m+n)
    else:
        print(r)
    

    #Question 2: Given a range of numbers.
    # Iterate from o^th number to the end number and print the sum of the current number and previous number.

    n=int(input("Enter Number for fibonnica series : "))
    a=0
    b=1
    for i in range(n):
        if i == 0:
            print("0")
        else:
            c=a+b
            a=b
            b=c
            print(c)
    

    #Question 3: Accept string from the user
    # and display only those characters which are present at an even index

    str = "pynative"
    for i in range(len(str)):
        if i%2==0:
            print(str[i])
    

    #Question 4: Given a string and an int n,
    # remove characters from a string starting from zero up to n and return a new string

    def remove(n):
        return str[n:]
    
    str=input("Enter string : ")
    n=int(input("Enter Index : "))
    print(remove(n))
    

    #Question 5: Given a list of ints, return True if first and last number of a list is same

    n=int(input("How many numbers you will enter into list : "))
    A=[]
    for i in range(n):
        a=int(input("Enter Number : "))
        A.append(a)
    
    if A[0]==A[-1]:
        print("First and last number is same")
    

    #Question 6: Given a list of numbers,
    # Iterate it and print only those numbers which are divisible of 5

    n=int(input("How many numbers you will enter into list : "))
    A=[]
    for i in range(n):
        a=int(input("Enter Number : "))
        A.append(a)
    
    for j in A:
        if j%5==0:
            print(j,end=" ")
    

    #Question 7: Return the number of times that the string appears anywhere in the given another string

    n=input("Enter phrase that repeats the words : ")
    r=input("Enter repeated word : ")
    c=0
    n=n.split()
    for i in n:
        if i in r:
            c+=1
    print(c)
    

    #Question 8: Print the following pattern

    n=int(input("Enter Number of rows :"))
    for i in range(1,n+1):
        for j in range(1,n+1):
            if i>j or i==j:
                print(i,end="")
            else:
                print(end="")
        print()
    
    

    #Question 9: Reverse a given number and return true
    # if it is the same as the original number

    n=input("ENter Number : ")
    if n==n[::-1]:
        print(n)
    

    #Question 10: Given a two list of ints create a third list
    # such that should contain only odd numbers from the first
    # list and even numbers from the second list
    #Merged List is [23, 11, 17, 24, 36, 12]

    A = [10, 20, 23, 11, 17]
    B = [13, 43, 24, 36, 12]
    C=[]
    for i in A:
        if i%2==1:
            C.append(i)
    for j in B:
        if j%2==0:
            C.append(j)
    print(C)
    
    Reply
    • AMEENGT3 says

      February 27, 2020 at 10:25 pm

      NICE WORK

      Reply
    • harpoon says

      February 28, 2020 at 9:21 am

      thank u this helped me a lot

      Reply
      • Vishal says

        March 26, 2020 at 7:02 pm

        I am glad it helped you.

        Reply
    • AMEENGT3 says

      March 6, 2020 at 11:26 am

      import turtle 
      import time 
      import random 
        
      print ("This program draws shapes based on the number you enter in a uniform pattern.") 
      num_str = input("Enter the side number of the shape you want to draw") 
      turtle.speed(999)
      if num_str.isdigit(): 
          squares = int(num_str) 
        
      angle = 180 - 180*(squares-2)/squares 
        
      turtle.up 
        
      x = 0 
      y = 0
      turtle.setpos(x, y) 
        
        
      numshapes = 9
      for x in range(numshapes): 
          turtle.color(random.random(), random.random(), random.random()) 
          x += 5
          y += 5
          turtle.forward(x) 
          turtle.left(y) 
          for i in range(squares): 
              turtle.begin_fill() 
              turtle.down() 
              turtle.forward(40) 
              turtle.left(angle) 
              turtle.forward(40) 
              print (turtle.pos()) 
              turtle.up() 
              turtle.end_fill() 
        
      time.sleep(11) 
      turtle.bye()
      
      Reply
      • AMEENGT3 says

        March 6, 2020 at 11:29 am

        Anyone can try this

        Reply
    • Vishal says

      March 9, 2020 at 6:55 pm

      Great Junaid Ali. Keep it up

      Reply
    • Houssem says

      September 6, 2021 at 4:04 pm

      Try this one:

      def makeList(lst1, lst2):
          f_lst = list()
          for i,a in zip(lst1, lst2):
              if i%2 != 0: f_lst.append(i)
              if a%2 == 0: f_lst.append(a)
          return f_lst
      Reply
  263. Cero says

    February 7, 2020 at 4:08 pm

    class Dijak:
      def_init_(self, imeInPriimek,odelek,stDosezenihTock,vrstaOcene):
        self.imeInPriimek=imeInPriimek
        self.odelek=odelek
        self.stDosezenihTock=stDosezenihTock
        self.vrstaOcene=vrstaOcene
      def vrniOceno(self):
        odstotek=self.stDosezenihTock/28*100
        if(odstotek>=88):
          return(5)
        elif(odstotek>=75):
          return(4)
        elif(odstotek>=63):
          return(3)
        elif(odstotek>=50):
          return(2)
        else:
          return(1)
      def vrniImeInPriimek(self):
        loci=self.imeInPriimek.split("")
        niz=loci[1]+","+loci[0]
        return(niz)
      def izpisObjekta(self):
        print(self.vrniImeInPriimek()+"("+self.odelek+")"+"ocena :"+str(self.vrniOceno)+","+self.vrstaOcene)
      def shraniPodatek(N):
        for i in range(N)
          objekt=Dijak(input("Dijak :")),input("Odelek :"),int(input("Tocke :")),input("Vrsta :"))
          seznam.append(objekt)
        return(seznam)
      def VrniOceneDijaka(seznamdijakov,imeInPriimek):
        for s in seznamdijakov:
          if(s.imeInPriimek==imeInPriimek):
            s.izpisObjekta()
      def povprečjeRazreda(seznamdijakov,odelek,vrstaOcene):
        vsota=0
        stevec=0
        for s in seznamdijakov:
          if(s.vrstaOcene==vrstaOcene and s.odelek==odelek):
            vsota+=s.vrniOceno()
              stevec+=1
        print(vsota/stevec)
    
    Reply
  264. Grant says

    February 2, 2020 at 8:45 am

    This is more simplistic code for #5:

    l = []
    question = str(input("Do you want to enter a number; enter yes or no: "))
    
    while question == 'yes':
        numbers = int(input("Enter a number here: "))
        question = str(input("Do you want to continue entering numbers; enter yes or no: "))
        l.append(numbers)
    
    if l[0] == l[-1]:
        print("The first and last numbers of", l , "are the same!")
    else:
        print("The first and last numbers of", l , "are not the same!")
    
    Reply
    • Vishal says

      February 3, 2020 at 11:05 pm

      Grant, Thank you for your solution

      Reply
  265. magesh says

    January 29, 2020 at 7:20 pm

    Question 9: Reverse a given number and return true if it is the same as the original number

    print(True) if(user_input == user_input[::-1]) else print(False)
    Reply
    • Vishal says

      March 26, 2020 at 7:04 pm

      Thank you for alternative solutions

      Reply
  266. magesh says

    January 29, 2020 at 7:04 pm

    Another easiest solution for Question 8

    for i in range(1,6):
        print(" ".join(str(i)*i),end="\n")
    
    Reply
  267. Eric says

    January 7, 2020 at 10:18 pm

    Hey,

    As a beginner Python programmer, these questions are extremely helpful. Even when I can’t solve them on my own and peek at the given solutions, I make sure that I 100% understand the solutions before moving on to the next question. Thanks for your hard work.

    Regards,
    Eric

    Reply
    • Vishal says

      January 8, 2020 at 7:34 pm

      Eric, Thank you for your appreciation

      Reply
  268. Kirich says

    November 25, 2019 at 8:02 pm

    Another solution for question 7:

    test_str = "Emma is a good developer. Emma is also a writer"
    counter = test_str.count('Emma')
    print("Emma appeared " + str(counter) + '  times')
    

    Does it count?

    Reply
    • Vishal says

      December 4, 2019 at 3:54 pm

      Yes. The output is Emma appeared 2 times

      Reply
  269. sreekanth says

    November 4, 2019 at 6:03 pm

    This is a very nice practice for the beginners who wanted to kick off their python programming .

    Reply
    • Vishal says

      November 5, 2019 at 8:56 am

      Sreekanth, I am glad it helped you.

      Reply
      • Kenneth Jay Paradiang says

        December 4, 2019 at 11:44 am

        example shows parenthesis on if statements, but pycharm pose it as a pep8 violation. is it python 2 if statement structure?

        Reply
        • Vishal says

          December 4, 2019 at 3:49 pm

          All codes are developed using Python 3. You can remove parentheses

          Reply
  270. Dwayne Lewis says

    October 5, 2019 at 10:36 am

    The admin of this site is doing a really good job and am really grateful for that. Also can the admin give suggestion of how to learn programming in python because i most of the basic stuff in Python but I’m still having problem putting the syntax together.

    Reply
    • Vishal says

      October 7, 2019 at 7:23 pm

      Thank you, Dwayne Lewis, Answer is practice. Try to solve as many examples as you can. or try to solve StackOverflow basic questions

      Reply
    • AKASH says

      October 19, 2019 at 3:45 pm

      all these codes are in 3.7 or 2.7 ???

      Reply
      • Vishal says

        October 20, 2019 at 11:04 pm

        Python 3.7

        Reply
  271. DevOps in Training says

    September 29, 2019 at 2:43 am

    For number 10 I used a list comprehension.

    def mergeLists(list1, list2):
        list3 = list1 + list2
        mergedList = [x for x in list3 if x%2 != 0]
        return mergedList
    
    mergeLists(listOne, listTwo)
    [23, 11, 17, 13, 43]
    
    Reply
    • Zlatko says

      November 23, 2019 at 6:57 pm

      yeah, but you have only odd numbers…

      Reply
  272. Mc Quest says

    September 11, 2019 at 11:37 pm

    Another possible solution for Q 1:

    # program to accept two inputs and return sum

    firstNo = int(input("Enter first number: "))
    secondNo = int(input("Enter second number: "))
    print(" ")
    product = (firstNo * secondNo)
    print(" ")
    
    if product > 1000:
        print("The result is ", firstNo + secondNo)
    else:
        print("The result is ", product)
    
    Reply
  273. Sumit says

    September 1, 2019 at 9:31 pm

    # Example 3

    def example():
        inp_str = input("Enter on string : ")
        print("Your input string is :",inp_str)
        for i in range(0, (len(inp_str)-1),2):
            print("Index ",[i],":",inp_str[i])
    example()
    
    Reply
  274. Ahmad says

    August 10, 2019 at 6:34 pm

    i think Answer to question 3 is as simple as this:

    word = input('Please enter a word: ')
    
    print(word[0 : : 2])
    
    Reply
    • Ahmad says

      August 10, 2019 at 6:37 pm

      in case of Even its:

      print(word[ 1 :  : 2])
      
      Reply
  275. Ahmad says

    August 10, 2019 at 2:06 pm

    The actual answer to the Question 1 should be:

    result = int()
    
    while result  1000:
            print('The result is: ', first_number + second_number)
            break
    
    Reply
  276. VIgnesh says

    July 17, 2019 at 3:05 pm

    My answer for question number 8

    str1 ='012345'
    for i in range(len(str1)):
        print(str1[i]*i)
    
    Reply
  277. Víctor says

    July 12, 2019 at 11:25 pm

    Hi, there is a small mistake in the solution of question 3. Specifically the error is in line 2:
    for i in range(0, len(str)-1, 2).
    As it is written, the last character of a word that has an odd number of characters, for example ‘tiger’ , will never be printed out, even if this last character is present at an even idex, like in this case the letter ‘r’. This is because the built-in function range() doesn’t include the last value of the specified range. For example, list(range(0,5)) will return [0, 1, 2, 3, 4], excluding the number 5.
    Therefore, the correct solution is:

    for i in range(0, len(str), 2) #remove the -1
    for i in range(0, len(str)-1, 2):
    
    Reply
  278. Barry Ford says

    July 4, 2019 at 5:06 am

    On Question 8, I made my solution accept user input as to the height of the pyramid. See below

    height = int(input("Height? "))
    for num in range(height):
        for j in range(num + 1):
            print(num + 1, end=" ")
        print()
    
    Reply
  279. Zhixiang says

    July 3, 2019 at 11:34 pm

    on exercise 1:

    a = int(input('Please enter the first integer: '))
    b = int(input('Please enter the second integer: '))
    
    c = a * b
    
    print ('a * b =', c)
    
    if c > 100: 
      d = a + b
      print('sum of a and b when d >100:', a + b)
    
    Reply
  280. Chris says

    June 11, 2019 at 3:19 am

    Here’s a shorter solution for question 3 🙂 It uses slicing with a step of 2.

    str = "pynative"
    "".join(str[::2])
    

    Output:
    ‘pntv’

    Reply
  281. maxime says

    June 7, 2019 at 5:49 pm

    There is a short way to attend question 9.

    # Reverse a given number and return true if it is the same as the original number
    original_number = input("Enter the number: ")
    reverse_number = original_number[::-1]
    if int(original_number) == int(reverse_number):
        print("The reversed number is the same as the original one.")
    else:
        print("They are not the same.")
    
    Reply
  282. Robert Carew says

    May 16, 2019 at 8:39 pm

    Hello Vishal.

    I really am grateful for the work you put in to make this resource. This comment is a token of my thanks. I am a beginner programmer and this is helping me increase my knowledge of Python.

    Cheers.

    Reply
    • Vishal says

      May 16, 2019 at 10:14 pm

      Hey Robert, I am glad you liked it

      Reply
      • Lucky says

        September 5, 2019 at 5:36 pm

        hi Vishal , i am from south africa i also need help

        Reply
        • Vishal says

          September 5, 2019 at 9:01 pm

          Hi Lucky, Please tell me

          Reply
  283. Bill Hardwick says

    May 16, 2019 at 3:41 pm

    Just a general comment on these Comment boxes. Like me, I suspect most respondents post the python code by pasting from an editor (such as the Trinket one provided here). Unfortunately the mark-up behind this Comment box does not appear to support tab characters, so the all-important pythonic indentation is lost. This could be very confusing for a beginner, particularly where multi-line code blocks are concerned. Any way you could rectify this please?

    (In the meanwhile, the workaround would appear to be to manually replace any tabs with 4 spaces, but that is prone to editing error or omissions.)

    Reply
    • Vishal says

      May 16, 2019 at 10:29 pm

      Hey, Bill

      You can paste your code in pre HTML tag so it can keep indentation as it is.

      Reply
  284. Bill Hardwick says

    May 16, 2019 at 3:30 pm

    My alternative solution to Q10:

    list1 = [1, 2, 3, 4, 5, 6, 7, 8, 9]
    list2 = [21, 22, 23, 24, 25, 26]
    list1_odd = [e for e in list1 if e%2 != 0]
    list2_even = [e for e in list2 if e%2 == 0]
    list3 = []
    list3.extend(list1_odd)
    list3.extend(list2_even)
    print(list1)
    print(list2)
    print(list3)
    
    Reply
  285. Bill Hardwick says

    May 16, 2019 at 3:27 pm

    May I suggest an alternative solution to Q7.

    txt = 'Emma is a good developer. Emma is also a writer.'
    count = 0
    lst = txt.split()
    for word in lst:
      if word == 'Emma':
        count += 1
    print(f'Emma appears {count} times in the string.')
    
    Reply
    • Neeraj Raut says

      July 13, 2019 at 9:35 pm

      Just a little different and shorter approach if i may suggest…

      def string(s):
          c=s.count("Emma")
          return f"Emma occurred {c} times"
      print(string('Emma stone is great actor. Emma is genius. Emma play sports'))
      
      Reply
    • Improve says

      May 15, 2020 at 10:11 am

      ? at first try I’ve solved by using this approach ?

      Reply
  286. Richard says

    April 23, 2019 at 9:44 pm

    Hi Vishal
    I think to help the beginners better, you should solve the problems without always using user defined functions, just Incase those that are not familiar with it.
    Don’t mind my frequent responses, am in love with PYTHON that’s why.
    Thanks

    Reply
    • Vishal says

      April 24, 2019 at 6:50 am

      Hey, Richard Thank You for your suggestions.

      Reply
  287. Richard says

    April 23, 2019 at 3:00 pm

    Vishal I think your solution to question1 is a little verbose, a straight if and else statement does the job just well, it Will be much easier for beginners. I.e

    if product>1000:
        print('sum is: ', sum)
    else:
        print('product is: ', product)
    
    Reply
  288. Mdsambo says

    March 30, 2019 at 7:39 pm

    user_input = input("input any string") 
    for a,  j in enumerate(range(0, len(user_input), 2)):
             print(user_name)
    

    # means square bracket

    Reply
    • Mdsambo says

      March 30, 2019 at 7:42 pm

      Print(username(j))
      

      its a square bracket

      Reply
  289. Toby Robert says

    March 14, 2019 at 12:35 pm

    May I suggest a more concise solution to question no. 9?

    orignum= 234565432
    revnum=(str(orignum)[::-1])
    print(revnum)
    if str(orignum) == revnum:
       print('True: The number is the same when reversed')
    
    Reply
    • Vishal says

      March 14, 2019 at 12:50 pm

      Thank you Toby for your valuable suggestion. It will help others also.

      Reply
    • Jasmine_a says

      October 24, 2020 at 6:10 pm

      hi sorry, but can you check this code, please?
      I want to write a program in which you get multi-digit numbers from the user without any restrictions on repetition and digits. It can be up to n digits and I want to add those digits in order so that I have only one digit in my output, like this example :
      input = 123874 solving = 1+2+3+8+7+4 =25 , 25 = 7 output = 7
      or , input = 14 output = 5

      and this is my code but it doesn’t work. can you debug this in a way that it works and be able to give any input from user?

      def sumdigits_nonrecursive(number):
          result = number
          while result > 10:
              ac = 0         # initialize a temporary accumulator
              for c in str(result):
                  # for each character of the "result" string, add to accumulator the digit value
                  ac = ac + int(c)
              result = ac
          return result
      Reply
      • Richard_K says

        February 15, 2022 at 7:35 pm

        Hello Jasmine_a.
        A little late, but this may help someone:

        
        def sumdigits_nonrecursive(number):
            result = number
            while result > 10:
                ac = 0         # initialize a temporary accumulator
                for c in str(result):
                    # for each character of the "result" string, add to accumulator the digit value
                    ac = ac + int(c)
                result = ac
            return result
        
        #use input() to allow user to enter the number
        number = input("Enter number to evaluate: ")
        #convert user input to int
        number = int(number)
        #call your function inside print() to display result returned
        print( sumdigits_nonrecursive(number) )
        Reply
      • seraph776 says

        April 30, 2022 at 7:40 am

        
        
        def sumdigits_nonrecursive(n: int) -> int:
            """sum digits non-recursively"""
            while True:
                n = sum([int(i) for i in str(n)])
                if len(str(n)) == 1:
                    break
            return n
        
        print(sumdigits_nonrecursive(123874)) # 7
        print(sumdigits_nonrecursive(14)) # 5
        Reply
  290. Joseph says

    March 8, 2019 at 11:35 am

    Dear Vishal,
    I tried Question 1 and failed as compare to your solution. I think your question was wrongly phrased.
    My solution is
    #It is assumed user will enter integers only, no check on input

    first = int(input("Enter first integer "))
    second = int(input("Enter second integer "))
    
    product = first * second
    print ("Product is ", product)
    
    if product > 1000:
        print("Sum as product > 1000 : ", first + second)
    

    Your Question should have been
    Question 1: Accept two integer values from user.
    Calculate their product and if the product is greater than 1000
    then return their sum otherwise return their product.

    Regards,
    Joseph

    Reply
    • Ahmad says

      August 10, 2019 at 2:02 pm

      You are right, according to the question the solution should be:

      result = int()
      while result  1000:
              print('The result is: ', first_number + second_number)
              break
      

      In this way, It will keep asking you the numbers until the product is not greater than 1000 and If the Product is greater than 1000 then it will show you the result by adding both numbers

      Reply
    • Ahmad says

      August 10, 2019 at 2:04 pm

      sorry the actual solution: some how skipped to copy some lines

      result = int()
      
      while result  1000:
              print('The result is: ', first_number + second_number)
              break
      
      Reply

Leave a Reply Cancel reply

your email address will NOT be published. all comments are moderated according to our comment policy.

Use <pre> tag for posting code. E.g. <pre> Your entire code </pre>

In: Python Python Basics Python Exercises
TweetF  sharein  shareP  Pin

  Python Exercises

  • All Python Exercises
  • Basic Exercise for Beginners
  • Intermediate Python Exercises
  • Input and Output Exercise
  • Loop Exercise
  • Functions Exercise
  • String Exercise
  • Data Structure Exercise
  • List Exercise
  • Dictionary Exercise
  • Set Exercise
  • Tuple Exercise
  • Date and Time Exercise
  • OOP Exercise
  • File Handling Exercise
  • Python JSON Exercise
  • Random Data Generation Exercise
  • NumPy Exercise
  • Pandas Exercise
  • Matplotlib Exercise
  • Python Database Exercise

 Explore Python

  • Python Tutorials
  • Python Exercises
  • Python Quizzes
  • Python Interview Q&A
  • Python Programs

All Python Topics

Python Basics Python Exercises Python Quizzes Python Interview Python File Handling Python OOP Python Date and Time Python Random Python Regex Python Pandas Python Databases Python MySQL Python PostgreSQL Python SQLite Python JSON

About PYnative

PYnative.com is for Python lovers. Here, You can get Tutorials, Exercises, and Quizzes to practice and improve your Python skills.

Follow Us

To get New Python Tutorials, Exercises, and Quizzes

  • Twitter
  • Facebook
  • Sitemap

Explore Python

  • Learn Python
  • Python Basics
  • Python Databases
  • Python Exercises
  • Python Quizzes
  • Online Python Code Editor
  • Python Tricks

Coding Exercises

  • C Exercises
  • C++ Exercises
  • Python Exercises

Legal Stuff

  • About Us
  • Contact Us

We use cookies to improve your experience. While using PYnative, you agree to have read and accepted our:

  • Terms Of Use
  • Privacy Policy
  • Cookie Policy

Copyright © 2018–2026 pynative.com