Write a program that takes the input and prints the number of words in it. Example…
- User
Write a program that takes the input and prints the number of words in it.
Example input: Python is a programming language. Corresponding output: 5
- Assistant
Here is a simple Python program that takes input from the user and counts the number of words in it:
input_str = input("Enter a string: ") # Splitting the input string by spaces to get a list of words words = input_str.split() # Counting the number of words in the input string num_words = len(words) print("Number of words:", num_words)When you run this program, it will prompt you to enter a string. Once you provide the input string, it will split the string into individual words using the
split()method, and then count the number of words using thelen()function. Finally, it will print the number of words to the console. - User
Write a program that takes the input and prints the number of words in it.
Example input: Python is a programming language. Corresponding output: 5
Don't use input function
- Assistant
Certainly! Here's an updated version of the program that doesn't use the
input()function. Instead, the input string is directly assigned to a variable.input_str = "Python is a programming language." # Splitting the input string by spaces to get a list of words words = input_str.split() # Counting the number of words in the input string num_words = len(words) print("Number of words:", num_words)In this program, the input string is directly assigned to the
input_strvariable. The rest of the code remains the same, splitting the input string into individual words and counting the number of words, before finally printing the result.