Practical Exercises
To practice conditions, loops, and string manipulation, here are some practical exercises to do:
Exercise 1: Counting Characters in a String (Easy)
easyObjective: Work on string manipulation and loops.
- Write a program that asks the user to enter a string.
- The program must display the number of characters present in the string, excluding spaces.
Instructions:
- Use a
for
loop to traverse the string. - Use an
if
condition to ignore spaces.
Example:
- Input: "Hello world"
- Output: "Number of characters (without spaces): 10"
Exercise 2: Determine Number Parity
mediumObjective: Use loops and conditions.
- Write a program that asks the user to enter a positive integer.
- Then, the program must display all numbers from 0 to this number with an indication if they are even or odd.
Instructions:
- Use a
for
loop to traverse the range of numbers. - Use an
if...else
condition to determine the parity of each number.
Example:
- Input: 5
- Output: "0 is even" "1 is odd" "2 is even" "3 is odd" "4 is even" "5 is odd"
Exercise 3: Strong Password
mediumObjective: Work on conditions and string manipulation.
- Write a program that asks the user to enter a password.
- The program must check if the password is strong according to the following criteria:
- At least 8 characters.
- Contains at least one uppercase letter, one lowercase letter, one digit and one special character (for example,
!
,@
,#
,$
, etc.).
- Display a message indicating if the password is strong or weak.
Instructions:
- Use string methods like
isupper()
,islower()
,isdigit()
. - Use
if...elif...else
conditions to check the criteria.
Example:
- Input: "Passw0rd!"
- Output: "Strong password"
Exercise 4: Calculate the GCD of Two Numbers
difficultObjective: Use loops and conditions to implement a classic algorithm.
- Write a program that asks the user to enter two positive integers.
- Calculate the greatest common divisor (GCD) of these two numbers using Euclid's algorithm.
- Display the result.
Instructions:
- Use a
while
loop to implement Euclid's algorithm:- While the two numbers are not equal, replace the larger of the two with the difference between the two.
- Use conditions to compare the numbers.
Example:
- Input: 48, 18
- Output: "The GCD of 48 and 18 is 6"
Exercise 5: Analyze Word Frequency in a Sentence
difficultObjective: Advanced string manipulation, loops and conditions.
- Write a program that asks the user to enter a sentence.
- The program must count and display the frequency of each word in the sentence.
- Ignore case (uppercase/lowercase) and punctuation marks.
Instructions:
- Use
split()
to divide the sentence into words. - Use a dictionary to store the frequency of each word.
- Use loops and conditions to clean words of all punctuation and count their occurrence.
Example:
- Input: "Hello, hello the world! The world is vast."
- Output: "hello: 2" "the: 2" "world: 2" "is: 1" "vast: 1"