Exercise: Variables and Data Types

Exercise 1: Greeting Message

Task: Create a greeting message using a name.

Instructions:

  • Define a variable called name and assign it your name as a string.
  • Create a variable called greeting that combines “Hello,” with the name.
  • Print the greeting message.
Show solution
name = "Alice"

# Combine to create a greeting message
greeting = "Hello, " + name

# Print the greeting
print(greeting)  # Output: Hello, Alice
Hello, Alice

Exercise 2: Word Count

Task: Count the number of words in a sentence.

Instructions:

  • Define a variable called sentence and assign it a string value (e.g., “Natural Language Processing is fun”).
  • Use the split() method to create a list of words from the sentence.
  • Calculate the number of words and print the result.
Show solution
sentence = "Natural Language Processing is fun"

# Split the sentence into words
words = sentence.split()

# Count the number of words
word_count = len(words)

# Print the word count
print("Number of words:", word_count)  # Output: Number of words: 5
Number of words: 5

Exercise 3: Create a Simple List

Task: Make a list of your favorite fruits.

Instructions:

  • Define a variable called fruits and assign it a list of your three favorite fruits.
  • Print the list.
Show solution
# Create a list of favorite fruits
fruits = ["apple", "banana", "cherry"]

# Print the list of fruits
print("My favorite fruits are:", fruits)  # Output: My favorite fruits are: ['apple', 'banana', 'cherry']
My favorite fruits are: ['apple', 'banana', 'cherry']

Exercise 4: Check if Word is Present

Task: Check if a specific word is in a list.

Instructions:

  • Define a list of common NLP words (e.g., nlp_words = ["token", "entity", "vector", "model"]).
  • Define a variable called search_word with a value to check (e.g., "entity").
  • Create a boolean variable word_found that checks if search_word is in the nlp_words list.
  • Print the result.
Show solution
nlp_words = ["token", "entity", "vector", "model"]
search_word = "entity"

# Check if the word is in the list
word_found = search_word in nlp_words

# Print the result
print(f"Is '{search_word}' in the list? {word_found}")  # Output: Is 'entity' in the list? True
Is 'entity' in the list? True
Back to top