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:
Hint
- Define a function that calculates the product two given numbers.
- Use an
ifstatement to compare that product against 1000 to decide whether to return the product or the sum.
Solution
Explanation to Solution:
- Function Definition: The code uses
defto 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 <= 1000line acts as a gatekeeper, routing the program’s logic based on the calculated value. - Return Values: Instead of just printing, the function
returnsthe 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:
Hint
- Initialize a variable
previous_numto 0 outside the loop. - At the end of each loop iteration, update
previous_numwith the value of thecurrent_num.
Solution
Explanation to Solution:
- Initialization:
previous_num = 0is set outside the loop so it persists across iterations. - for loop Iteration: The
for i in range(10)loop automatically incrementsifrom 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 = iis 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
forloop with arangethat steps by 2. Iterate through the characters of the string using a loop and therange()function. - Use
start = 0,stop = len(s) - 1, andstep = 2. The step is 2 because we want only even index numbers. - Or by using Python’s built-in string slicing syntax
[::2].
Solution
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_charsloop processes the resulting subset of characters individually.
Solution 2: Using loop
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:
tivenative
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
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
nas 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
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
afrom being overwritten bybbefore 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
factorialvariable to 1. - Loop through a range from 1 to the given number, multiplying the
factorialvariable by the current loop index at each step.
Solution
Explanation to Solution:
- Identity Element: We start
factorialat 1 because multiplying by zero would ruin the entire calculation. range(1, num + 1): Since the end of a range is exclusive, we use+ 1to 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)ordelto remove the item at the specific index.
Solution
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
stepto -1 tells Python to move through the sequence backwards.
Solution
Explanation to Solution:
[::-1]: The first two colons imply “start at the very beginning” and “go to the very end.” The-1indicates the direction of travel.- Immutability: This operation doesn’t change the original
textvariable; 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
Explanation to Solution:
.lower(): This is essential for robust code. It ensures that “A” and “a” are both counted without needing to write a massiveifstatement for both cases.- The
inKeyword: 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 toTrue.
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()andmin()functions which iterate through a collection and return the extreme values in O(n) time.
Solution
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 tomax, 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
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
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 calculatinglen(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
forloop 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
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
ifcondition evaluates toTruedoes theprintfunction 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
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
countare 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:
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
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
numsets the “context” for the row. The inner loopiperforms 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
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
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 % 10to get the last digit. - Then, use
number // 10to “chop off” that last digit and repeat the process in a loop until the number becomes zero.
Solution
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
Explanation to Solution:
- Cumulative Logic: The code doesn’t just check one condition; it accounts for every bracket the income “passes through.”
elifchain: 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:
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
Explanation to Solution:
range(1, 11): Remember that Python’srangeis 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:
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
Explanation to Solution:
range(5, 0, -1): The third argument-1is the “step.” It tells the loop to decrement the value ofiin 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
exptimes, and in each iteration, multiply the result by thebase.
Solution
Explanation to Solution:
- Base Case:
resultstarts at 1 because 1 is the identity element for multiplication (anything multiplied by 1 remains itself). - The
whileLoop: This controls the number of multiplications. Each cycle represents one “power.” - Function Reusability: By passing
baseandexpas 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:
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
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 = 0andnum2 = 1. - In each iteration of a loop, the next number is
num1 + num2. - Then, update
num1to benum2, andnum2to be the new sum.
Solution
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 = num2andnum2 = 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
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
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
dict1anddict2while 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
Explanation to Solution:
set_a & set_b: The ampersand represents the “Intersection” operation. It returns a set containing only items that are present in bothset_aANDset_b.- Performance: Doing this with sets is significantly faster than using nested
forloops, 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
forloop combined with anif-elsestatement. - Remember, a number is even if
num % 2 == 0.
Solution
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-elsestructure 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
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
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 frequencychecks 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:
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
Explanation to Solution:
for...elseloop: A unique Python feature where theelseblock executes only if theforloop completes without hitting abreak. 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
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 * icreates 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
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_sentenceitself isn’t changed;replace()creates a new string which we store insanitized_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:
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
Explanation to Solution:
range(rows, 0, -1): The-1argument 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
forloop. - For each character, use the built-in
.isdigit()method. - If you find even one digit, you can set a flag to
Trueand break the loop.
Solution
Explanation to Solution:
- Flag Pattern: We initialize
contains_digitasFalse. This “flag” only flips if a specific condition is met. .isdigit(): This character method returnsTrueif the character is a numeric value (0-9) andFalseotherwise.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
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
whileloop 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
Explanation to Solution:
while count > 0: This condition ensures the loop runs exactly as many times as specified. Oncecounthits 0, the condition becomesFalseand the loop stops.time.sleep(1): This function from thetimemodule pauses execution for one second, making the output feel like a real clock.count -= 1: This is shorthand forcount = count - 1. Without this line, the loop would be “infinite” becausecountwould 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:
- “Hello, this is my first note.”
- “Python file handling is simple.”
- “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
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
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): Sincewordsis 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
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.

Thank you so much Vishal Hule, for creating this amazing content, it help a lot.
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’
Yes, you need to create the sample.txt before you try to read from it
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)
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
this is my code for 3rd question:
n = input()
for i in n[::2]:
print(i)
I am new to code ,pls tell
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))
Exercise 20 >>
a=int(input(‘Enter Range :’))
for i in range(a, 0, -1):
print((str(i)+’ ‘)*i+’\n’)
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)
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=”)
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=”)
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.
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”)
Exercise 3
name = input(“Enter a string : “)
x = len(name)
for i in name :
print(i)
you take a string and after then calculate the length when you use loop then one by one string character print on scrren
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)
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)
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))
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.
base=2
exponent=3
result1=1
for i in range(0,exponent):
result1=base*result1
print(result1)
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 )
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.
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”)
we can directly do that:
def is_palindrome(n):
if str(n) == str(n)[::-1]:
return True
else:
return False
print(is_palindrome(121))
We should work this exercice without changing the type to string
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”)
#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?
for i in range(1, 6):
print(str(i) * i)
It’s all in 2 lines
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()
question number 3:
word = input(“Enter your string: “)
print(“The original word is”, word)
result = word[0::2]
for _ in result:
print(_)
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)
def exponent(b,e):
return print(pow(b,e))
exponent(2,5)
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))
in third exercise , better use f string instead **print(“index[“, i, “]”, word[i])**
what about this method?
word = input(“Enter your string: “)
print(“The original word is”, word)
result = word[0::2]
for _ in result:
print(_)
For exercise 15 we can also do:
def exponent(base, exp):
x = pow(base, exp)
print(x)
exponent(2, 5)
task 8
for x in range(5+1):
print(f”{x} “*x)
works for my, and looks cleaner
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
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’
Q.no : 15 in simple way .
def exponent(base,exp):
print(‘exponent of given numbers:’,base**exp)
exponent(2,5)
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
Ex: 14for i in range(5,0,-1):
print(‘*’*i,sep=’ ‘, end=”\n”)
better codeEx: 14
for i in range(5,0,-1):
print(‘*’*i,sep=’ ‘, end=”\n”)
EXERCISE 13 SOLUTION
for i in range(1, 11):
for j in range(1, 11):
print((i * j), end=” “)
print()
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))
# 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)]
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}”)
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
Thanks man !
Nice exercises
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])
Excercise 15:
def exponent(base, exp):
return base ** exp
print(exponent(5,4))
you dont need to print it.
just pass
exponent(5,4)
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)
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 🙂
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”)
This is exactly what i did
Exercise 11:
n = 7536
l= ” ”
for i in str(n):
l = ” “+i + l
print(l)
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”)
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)
#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)
#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”)
exercise4:Remove first n characters from a string
str=”pynative”
str1=str[4:]
str2=str[2:]
print(str1,str2)
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)
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)
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’)
#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)
def exe_fifteen():
base = int(input(“Enter the base num : “))
exp = int(input(“Enter the exp num : “))
print(pow(base,exp))
exe_fifteen()
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”)
## 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)
Exercise 14: Print a downward Half-Pyramid Pattern of Star (asterisk)
for i in range(5, 0, -1):
print(“*” * i)
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)
Thanks🌸
def exponent(base, exp):
return base**exp
print(f'{5} raises to the power of {4} is: {exponent(5, 4)}’)
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)
1.
number1 = int(input(“Enter value x: “)
number2 = int(input(“Enter value y: “)
print(x * y) if x * y <= 1000 else print(x + y)
👍👍
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)
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()
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.
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)
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
yep agree
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)
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”)
thanks
string = "/*Jon is @developer & musician!!"special_symbols = "!@#$%^&*()_+-={}[]|\:;\"',.?/~`"
for char in special_symbols:
string = string.replace(char, "#")
print(string)
I don’t know this code
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)
#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)
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)
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)
Exercise 11:
num = 7536
reversed_num_str = str(num)[::-1]
for c in reversed_num_str:
print(c, end=" ")
Exercise 8:
row_count = 9
for i in range(1, row_count + 1):
print((str(i) + " ") * i)
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)
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)
Exercise 15:
def exp(b,e):y = b
for i in range(1,e):
b *= y
return b
print(exp(5,4))
#newincoding
we can do in simpliest way:
def exponent(base,exp):
new_int=base**exp
return new_int
print(exponent(2,5))
Exo 2 has difference between input code and output printing
EXERCISE 9 Simpler method:
def isPalindrome(number):if number[::-1] == number:
return "This is a palindrome"
else:
return "This isnt a palindrome"
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
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)
def expo(base,exponent):return base**exponent
expo(2,5)
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)
I think these excercises are very funny. I have looked a lot for something like this. Thanks a lot.
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("")
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("")
correction :
def exponent(base, exp):return base**exp
exponent(2, 5)
You did not count this remark:
‘Note here exp is a non-negative integer, and the base is an integer.’
Hi! Could you please explain me the question number 15 solution code
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
def aaa(base, exponent):output = 0
output = base ** exponent
return output
base = 5
exponent = 4
aaa(base, exponent)
It’s good actually.
# 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.")
#Exercise 6: Display numbers divisible by 5 from a list
#Create a list as a global variablemy_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)
Exercise 5: Check if the first and last number of a list is the same
# Function to create a listdef 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)
Ex 14
solution
for i in reversed(range(6)):for j in range(i):
print('*',end=' ')
print('\n')
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.
Hey Steve, this was my solution to match the output
start_num = 10print("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))
Is this solution right for exercise 8?
n = 1while n <=5:
print(" ".join((str(n)*n)))
n+=1
#Write a program to extract each digit from an integer in the reverse orderdef 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?
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"))
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”))
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"))
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=" ")
x=input("Enter the integer")for i in x:
print(x[int(len(x))-int(i)])
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)
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)
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índromodef 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: "))
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.
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)
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")
I finish like this😅
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")))
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)
—————————————————————————-
——————————————————————————
———————————————————————————-
————————————————————————————
———————————————————————————-
——————————————————————————–
you replied on my birthday
very helpful.
I am glad it helped you.
My solution for exercise 2:
Not sure how that compares functionally with teach’s code
previous_number = 0for 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
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 referenceprevious_num + i, which is the left side of the equation. I think you meant to referencex_sumthere. 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.
Hi Eli, the
x_sumandprevious_num + iproduce the same result. But for simplicity, i have replacedx_sumwithprevious_num + ivalid??
in this you can increase its functionality by taking input from user and code would of lesser lines
Here is my 2 line solution for exercise # 14
You a goat bruh
try contributing then
below is My 2 lines solution for exercise # 11
Exercise # 10 with user input list
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.
Sorry. This was exercise 15.
Here is my solution to exercise 9, did it for any palindromes. Works with numbers too.
Hello! Thanks for the insight.
I am a beginner. I did the palindromes exercise like this
This is my alternative solution for Exercise 11. I’m still a beginner in Python 😀
a = 7536for i in range(len(str((a)))-1,-1,-1):
print(str(a)[i],end=" ")
This is my alternative solution for Exercise 9. I understood it better this way 🙂
I’m a beginner in python. I have tried exercise no 13 like this
result
I try to solve exercise 13 in a different way which output looks good
the result
Hello. Thanks for the insight.
its look really good . Thank You..:)
“””
Exercise 14: Print a downward Half-Pyramid Pattern of Star (asterisk)
* * * * *
* * * *
* * *
* *
*
“””
for i in range(5, 0, -1):
print(str(‘*’) * i)
my solution for exercise number 6:
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..
for some reason its not printing the last part.
sorry for the multiple comments…
I realize it is leaving out stuff.
it says-
if product 1000:
print("The result is " + str(sum))I’m not sure if I’m reading it right or if something is missing. But your code says:
I’m guessing you meant to put
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
Anybody have another solution for question 13 for multiplication table with only increment of j in nested loop?
Like this?
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.
maybe like this? :
you can try this
One Liners (I’m a beginner but really enjoying the one-line problems)
Exercise 15: Write a function called exponent(base, exp) that returns an int value of base raises to the power of exp.
#code:
Please I cannot understand the palindrome answer. I need explaination
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
One line solutions to excercises 8,13 and 14 based on list comprehension.
Why you used
rstrip()in #exercise 8?Sorry, I’m new to Python and wondering about this usage on that code. Thank you!
He forgot it was supposed to be for beginners
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!
I do it with one for loop
One-line solutions to exercises 8,13 and 14 based on list comprehension.
for exercise no. 15 with required output:
output:
Using if for Exercise 3: Print characters from a string that are present at an even index number
Answer to exercise 9: Check if the string is a 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")solution to exercise 15:
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!
This site is extreamly usfull, totaly recomend.
There is a problem in question number one, the expected output is different from the question (contradicted). Anyway thanks for your sharing.
yes right
this site is extreamly usfull,totaly recomend
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.
Actually, of course, there’s no need to convert the string back to a number.
what if num is given user and the user give ‘mom’ as input.
Exercise 11 :
or
EX 15:
ex14:
is that ok?//
Exercise 10:
Question number 15:
Will do the same just way easier
EXCERCISE 15: I think we can directly calculate the power of using (
**) functionYes, exactly. I really don’t get why using loops (while, for, etc.. here).
I did Exercise 9: Check Palindrome Number diffrently, using string for reversing number. It goes like this:
Exercise 6: Display numbers divisible by 5 from a list soo list is inputed by user, hope you like it 🙂
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.
14-exercise
Last Question We Can Also Do Like:
#Exercise 15
indents didn’t post when i copy pasted my code
this is for exercise 4, the one about removing index chars
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)sorry wrong code:
Ok for some reason it won’t copy/paste the whole code correctly… FFS
Last try, very sorry for spamming:
Nevermind I figured it out. My comments can be deleted. Again very sorry for spamming, this was not my intention.
Please use ‘pre’ tag for posting code. For example,
first = 10000second = 10000
remaining = tax - (first + second)
x = (first * 0/100 + second * 10/100 + remaining * 20/100)
print("The taxable amount is : ", x)
Hello. The query for task 13. Why is
print("\t\t")at the end? When doesprint("")work anyway?print("\t")is used whenever a tab space has to be left in the outputprint("")is used to print a new linefor question number 15.
Test
Q3: An overly complex, but fun, answer
For Ex:15
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:
Your solution is the opposite of what your problem statement and your hint state.
yes nice catch
Came here to say the same. Already unconfident beginners get even more confused with this mistake in the very first exercise.
absolutely agree with you
Error still not corrected as of November 11. This is really a poor site, they don’t even read comments… Shame on them !
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"?
Q 12:
Q 11:
Q 10:
Q 09 in two lines:
Q7 without using str class:
solution for question no 5
This is more easy I think:
other way to coding ex 8:
Other way to solution Q5:
a little bit complicated
Another way of Question 5:
probably not the best looking code
what about this one?
Another answer to E3:
Question no: 11 – Reverse a number
this is an easier and less complicated way to do it.
dear admin this is my shorter solution to question 8
Question 9: Reverse number.
this is simpler and also works well.
The same with you!
Assuming n is a number:
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). andx[::-1]is enough to return a reversed copy. Just to polish a bit the already efficient code 🙂Damn… forgot to update n1 to n in the body of the method…
Hey, missed this one. Nice.
Hi Admin,
thanks, I’m still very new to programming and these exercises improve my skills 🙂
my answer for Q3 & Q10:
————-
My solution to the very easy first problem but with less lines of code:
You can use this code for 15 Exercise,
For 11 Exercise you can use this code,
Exercise 15. will be easy like this
Another way to solve Q14 ->
Another way could be:
Exercise 8:
The below will also return the same result.
pattern is wrong
just having a 0
it should be
range(1,6)rest all is perfect
Exercise :15
Exercise 14: Print downward Half-Pyramid Pattern with Star (asterisk)
Thank you! This one is easier for me to understand!
Very easy to understanf for me this
Ex9: I prefer to treat entered number as a string. Way more simple code:
Hi, I have a slightly shorter solution for Ex8:
Hello vishal
could you elabaorate this line of code for me ?
reverseNum = (reverseNum * 10) + reminderIt was in Q9. I am new in python so some easy things seems hard for me.The line is one of them.
Ans-1
Ans-2:
Ans_3:
Ans-4:
Ans-5
Ans-6
Ans-7
Ans-8
Ans-9
Ans-10
Ans-11
Ans-12
Ans-13
I got a similar answer:
Ex 15 alt:
this is the sort version
EX 15: alt
Thank you for all these exercises. They were very helpful to practice coding in Python.
Here are alternative solutions for Exercise 15:
Alternative and shorter solution in Exercise 12.
Alternative solution for Exercise 11.
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
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.
can we use below code for exc.8
same i made roblox epic games and gta 5 im making gta 6 in pythons
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
Solution 15 –
Thank you!
You may like this for the 15th exercise. I went a bit further.
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.
Although i used the
"".join(reversed('my_num" )#if you noticed,my_numwas astrand not anintso i need to understand your method.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.
Thanks for your clarification in advance. I love your webpage. God bless and increase you.
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.
Wonderful set of examples.. Great Work dude…
Thank you, Cholavendhan.
Must Appreciated .
Nice excercises
Thank you, Avinash.
Thank u sir for the exercises….. : )
* Andre*
Really helpful for PYTHON beginners… pls add more resources like this
Exercise 14
#EX 4
Thank u sir
Q3:
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 🙂
great sir. really helpful for beginners
You’re Welcome.
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?
Hey Matt, It is working as expected. Can you please try again.
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.
agree
2 and 3 ques “int object is not callable”
Error is displaying
Hi I’m also a Beginner, This is my second day of reviewing some Exercises.
I can’t even type any single line code.
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.
Question no.15 has a better answer XD
Question no 15 has a better solution XD:
The most helpful site ever learned a lot, thanks.
———————–
Thank you, Yahia. I am glad you liked it.
Question 5
Question 1
Q3.
Question 14: Print downward Half-Pyramid Pattern with Star (asterisk)
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:
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!
Easy solution for exercise 3
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:
# # Question 14: Print downward Half-Pyramid Pattern with Star (asterisk)
Que 5:
Easy solving for Q. 5
Question 13:
Why is it
print("\t\t")and notprint("\n")?I thought
\tcreates a tab or indent.\ndrops a line doesn’t it?Alos why
\t\tand not just\tThanks. I enjoyed the questions finding some pretty tricky!!!
\t\t means is two tab
I have tried this way
For question 6,we can have like this,
Question 15 can have a simpler solution . Which is :
Yeah!!.. That’s what am going to say!!
question 14
question 15
question 11.
Use ‘pre’ tag for posting code. E.g.
Simplified solution for question 14 without nested loop:
Question 3
Question 1
Question 12
The question to exercise 6:
Why does a “None” appear at the end of my output?
Here is my code:
Hello Emerson
Instead of using use
instead of using use
Instead of using
print(onlyDivisible(myList))useonlyDivisible(myList)Question 15: Write a function called exponent(base, exp) that returns an int value of base raises to the power of exp.
Love it! Especially for beginners like me!
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))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
1 .
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.
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.
Similarly, here n2 = 44 if a is 4
4.
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.
I could not solve exercise two. However, now i found what i consider the easiest solution:
Exercises are very excited for me thx
question 15 :
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??
for question 15:
Question No 9: another way to do it
Mine is similar:
hey guys!!! Here’s a program from which u can code a calculator:
what if I want more than 2 values operations
Ques. 15:
I hope this would be helpful to others!!!!
Stay Home!!
Stay Safe!!!!
best way
question 15:
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!
Thank you Kristofer for your valuable feedback.
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
Q15 simple solution
yeah i did the same way
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
Q3 simple solution:
here’s a solutio for Ques:3:
#Q15 Simple Solution
Q no.4
# Q2 Simple Solution :
Good Luck! 😉
My daughter studying from your tutorials; it is great!
please continue adding more exercises.
Thank you, Alex.
oefening 3:
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*" *")My solution for number 9
My code for number9
Exercice 01:
Exercice 02:
Exercice 03:
Exercice 04:
Exercice 05:
Exercice 06:
Exercice 07:
Exercice 08:
Exercice 09:
Exercice 10:
wowww………………!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!1
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!
you’re welcome, Daniel
#Q9:
Q(9).
thanks for publishing your answer, it was very helpful for me
#Q9:
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):
question 8
Hey buddy doing a wonderful job by posting such useful exercise for practice 🙂 keep it up
Thank you, Dhyan.
Please bring back the old code editor 🙁
Hey Nikita, Please let us know if you are facing any problem. Thank you
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!!!!
Question 3:
solution :
You don’t need line 2, and variable “L” in line 3 for your solution.
Thank you very much for the exercises. They are extremely helpful for a beginner.
Keep up the good work
You are welcome, Ray
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'))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)#Question 9 alt. solution
Hi Vishal
As a newbie, your exercises come in really helpful and useful. Thanks so much for posting! much appreciated.
You are welcome, Steven-r
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)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)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))hey bro for solution 2: what is the + 4 in the [i : 1 + 4] for?
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)def same_backwards(num): '''returns true if num is the same when written backwards''' return str(num) == str(num)[::-1]Last Question :
Thank you, Santosh for an alternative solution
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)Hey cyberhoax, Thank you for an alternative solution.
a = "Emma is good developer. Emma is a writer" print(a.count("Emma"))a = "Emma is good developer. Emma is a writer" c = a.count(input('enter the word: ')) print(c)I am learning coding for 2 weeks and it totally impoved my skills. thank you for your exercises.
Hey Saba, Thank you for your kind words.
I need the answer of two questions can I plzz help me
My code for question no 10:
best way
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. thanxHi 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 =0Here
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 1Alternative 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.
# Q3.
usr_str = input('Feed me a string!') print(usr_str[0::2], sep='\n')# Q4.
# Q5.
# Q6.
''' 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)]As I can see you did not expect me to include tags!
Too bad, I can’t change it now. 🙂
Thank you, Florian Fasmeyer. Now onwards Please add your code between <pre> </pre> tag for correct indentation.
Thank you Florian Fasmeyer for alternative solutions
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
Hi newbie, I have updated the answer. In your case, the result should be 1000.
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.
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)NICE WORK
thank u this helped me a lot
I am glad it helped you.
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()Anyone can try this
Great Junaid Ali. Keep it up
Try this one:
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)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!")Grant, Thank you for your solution
Question 9: Reverse a given number and return true if it is the same as the original number
Thank you for alternative solutions
Another easiest solution for Question 8
for i in range(1,6): print(" ".join(str(i)*i),end="\n")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
Eric, Thank you for your appreciation
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?
Yes. The output is Emma appeared 2 times
This is a very nice practice for the beginners who wanted to kick off their python programming .
Sreekanth, I am glad it helped you.
example shows parenthesis on if statements, but pycharm pose it as a pep8 violation. is it python 2 if statement structure?
All codes are developed using Python 3. You can remove parentheses
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.
Thank you, Dwayne Lewis, Answer is practice. Try to solve as many examples as you can. or try to solve StackOverflow basic questions
all these codes are in 3.7 or 2.7 ???
Python 3.7
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]yeah, but you have only odd numbers…
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)# 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()i think Answer to question 3 is as simple as this:
word = input('Please enter a word: ') print(word[0 : : 2])in case of Even its:
The actual answer to the Question 1 should be:
result = int() while result 1000: print('The result is: ', first_number + second_number) breakMy answer for question number 8
str1 ='012345' for i in range(len(str1)): print(str1[i]*i)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:
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()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)Here’s a shorter solution for question 3 🙂 It uses slicing with a step of 2.
Output:
‘pntv’
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.")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.
Hey Robert, I am glad you liked it
hi Vishal , i am from south africa i also need help
Hi Lucky, Please tell me
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.)
Hey, Bill
You can paste your code in pre HTML tag so it can keep indentation as it is.
My alternative solution to Q10:
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.')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'))? at first try I’ve solved by using this approach ?
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
Hey, Richard Thank You for your suggestions.
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)user_input = input("input any string") for a, j in enumerate(range(0, len(user_input), 2)): print(user_name)# means square bracket
its a square bracket
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')Thank you Toby for your valuable suggestion. It will help others also.
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?
Hello Jasmine_a.
A little late, but this may help someone:
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
You are right, according to the question the solution should be:
result = int() while result 1000: print('The result is: ', first_number + second_number) breakIn 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
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