Today’s task is to create a program that takes user input and prints a customized greeting. This will help you understand how to interact with users by accepting data from them and using it in your program. Taking user input is essential for making your programs interactive and dynamic, as it allows your program to react to the data entered by the user.
The goal is to ask the user for their name and then display a greeting message like: “Hello, [name]!”
Python: Use the input()
function to get input from the user. The input()
function always returns a string, so there’s no need to convert it if you’re just working with text.
name = input("Enter your name: ")
print("Hello, " + name + "!")
Java: In Java, you’ll need to use the Scanner
class to capture user input. You can use the nextLine()
method to capture a string.
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter your name: ");
String name = scanner.nextLine();
System.out.println("Hello, " + name + "!");
}
}
JavaScript: In JavaScript, you can use prompt()
to get input from the user in a web browser. The input will automatically be treated as a string.
let name = prompt("Enter your name:");
console.log("Hello, " + name + "!");
Once you have the user’s input (the name), you can combine it with a greeting message. This is called string concatenation.
In Python, use the +
operator to join strings:
print("Hello, " + name + "!")
In Java and JavaScript, you also use the +
operator to concatenate strings:
System.out.println("Hello, " + name + "!");
console.log("Hello, " + name + "!");
If the user enters special characters or spaces in their name, the program will handle it as any other text input. However, you might want to trim leading or trailing spaces using functions like strip()
in Python, or trim()
in Java.
Python Example:
name = input("Enter your name: ").strip()
JavaScript Example:
let name = prompt("Enter your name:").trim();
Once you’ve completed this task, try experimenting further with user input:
Understanding how to work with user input will be a key building block as you move forward in your coding journey, allowing you to create more interactive and complex applications.