Task: Write a code snippet that checks if a specific word is present in a given text.
Instructions:
Use the in operator to check if the word “language” is in the text.
Print a message indicating whether the word was found or not.
Show solution
text ="Natural language processing is fascinating."if"language"in text:print("The word 'language' is present in the text.")else:print("The word 'language' is not present in the text.")
The word 'language' is present in the text.
Exercise 2: Classify Text Length
Task: Write a code snippet that classifies the length of the text as “short”, “medium”, or “long”.
Instructions:
Use conditional statements to classify the text based on its length:
Short: less than 20 characters
Medium: between 20 and 100 characters
Long: more than 100 characters
Print a message indicating the classification.
Show solution
text ="Natural language processing."length =len(text)if length <20:print("The text is short.")elif20<= length <=100:print("The text is medium.")else:print("The text is long.")
The text is medium.
Exercise 3: Check for Uppercase
Task: Write a code snippet that checks if the first character of a sentence is uppercase.
Instructions:
Use an if statement to check if the first character of the sentence is uppercase.
Print a message indicating whether it is uppercase or not.
Show solution
sentence ="Hello, world!"if sentence[0].isupper():print("The sentence starts with an uppercase letter.")else:print("The sentence does not start with an uppercase letter.")
The sentence starts with an uppercase letter.
Exercise 4: Check Palindrome
Task: Write a function that checks if a given word is a palindrome.
Instructions:
Define a function called is_palindrome(word) that takes a string parameter word.
Inside the function, use conditional statements to check if the word is the same when reversed.
Return True if it is a palindrome and False otherwise.
Call the function with a sample word (e.g., “radar”) and print the result.
Show solution
def is_palindrome(word):return word == word[::-1]# Sample usageresult = is_palindrome("radar")print("Is 'radar' a palindrome?", result)
Is 'radar' a palindrome? True
Exercise 5: Categorize Word Length
Task: Create a function that categorizes a word as short, medium, or long based on its length.
Instructions:
Define a function called categorize_word_length(word) that takes a string parameter word.
Inside the function, use conditional statements to categorize the word based on the following criteria:
Short: 1-3 letters
Medium: 4-6 letters
Long: More than 6 letters
Return the category as a string.
Call the function with a sample word (e.g., “NLP”) and print the result.