Skip to main content

Reading & Printing Values

Description

Write a program that reads values from the user through standard input, processes them, and displays the results using standard output.

Specifically, you need to:

  1. Read a person's name (a string) from the user.
  2. Read their age (an integer) from the user.
  3. Read their height in meters (a floating-point number) from the user.
  4. Print a formatted greeting that includes all three values.

This problem teaches the fundamentals of input and output in Python — how input() reads data as strings, how to convert types with int() and float(), and how print() displays results with various formatting options.

Examples

Example 1

Input:

Alice
25
1.65

Output:

Hello, Alice! You are 25 years old and 1.65 meters tall.

Explanation: The program reads the name "Alice" as a string, converts "25" to an integer for the age, and converts "1.65" to a float for the height. It then constructs a single sentence combining all three values using print(). Notice that input() always returns a string, so we must explicitly convert the age and height to their numeric types before using them.

Example 2

Input:

Bob
30
1.80

Output:

Hello, Bob! You are 30 years old and 1.80 meters tall.

Explanation: Same logic applies. The name remains a string, the age is cast to int, and the height is cast to float. When we print 1.80, Python's float representation preserves the trailing zero because we format it explicitly to two decimal places.

Example 3

Input:

Charlie
abc
1.75

Output:

ValueError: invalid literal for int() with base 10: 'abc'

Explanation: When the user enters a non-numeric string like "abc" for the age, int("abc") raises a ValueError. This is because int() expects a string that represents a valid integer. This edge case shows why input validation is important in real programs — you should always handle the possibility that the user provides unexpected data.

Constraints

  • The name is a non-empty string (1 ≤ length ≤ 100)
  • The age is a valid integer (0 ≤ age ≤ 150)
  • The height is a valid floating-point number (0.1 ≤ height ≤ 3.0)
  • Input is read from standard input (stdin)
  • Output is written to standard output (stdout)
  • Each input value is on a separate line

Editorial

Brute Force

Intuition

The simplest way to read and print values in any programming language is to use the built-in I/O functions one at a time, with minimal formatting. In Python, input() reads a line from the user as a raw string, and print() writes values to the screen.

Think of it like a telephone conversation: input() is listening to what someone says (always hearing words — i.e., strings), and print() is you speaking back. If someone tells you a number over the phone, you hear the word "twenty-five", and you have to mentally convert it into the number 25 before doing math with it.

In this brute force approach, we read each value separately, convert types manually, and then print each piece of information on its own line using basic string concatenation with the + operator.

Step-by-Step Explanation

Let's trace through with the input: name = "Alice", age = "25", height = "1.65"

Step 1: Call input() to read the name. The user types "Alice" and presses Enter. input() returns the string "Alice" and stores it in the variable name.

Step 2: Call input() to read the age. The user types "25" and presses Enter. input() returns the string "25". This is still a string at this point — not a number.

Step 3: Convert the age string to an integer by calling int("25"). This parses the string and returns the integer 25. Store it in the variable age.

Step 4: Call input() to read the height. The user types "1.65". input() returns the string "1.65".

Step 5: Convert the height string to a float by calling float("1.65"). This returns 1.65 as a floating-point number. Store it in height.

Step 6: Print the name using print("Name: " + name). The + operator concatenates two strings together. Output: Name: Alice.

Step 7: Print the age using print("Age: " + str(age)). Since age is an integer, we must convert it back to a string with str() before concatenation. Output: Age: 25.

Step 8: Print the height using print("Height: " + str(height)). Similarly convert the float to a string. Output: Height: 1.65.

Reading & Printing — Basic String Concatenation — Watch how input() always returns a string, type conversions transform the string into numeric types, and print() outputs the final result using concatenation.

Algorithm

  1. Read the name using input() — it returns a string directly
  2. Read the age using input(), then convert to integer using int()
  3. Read the height using input(), then convert to float using float()
  4. Print each value on a separate line using string concatenation (+)
  5. For non-string values, convert back to string with str() before concatenating

Code

#include <iostream>
#include <string>
using namespace std;

int main() {
    string name;
    int age;
    double height;
    
    // Read values from standard input
    getline(cin, name);  // Read full line for name
    cin >> age;          // Read integer
    cin >> height;       // Read floating-point number
    
    // Print each value using string concatenation
    cout << "Name: " << name << endl;
    cout << "Age: " << age << endl;
    cout << "Height: " << height << endl;
    
    return 0;
}
# Read values from standard input
name = input()          # Returns a string
age = int(input())      # Convert string to integer
height = float(input()) # Convert string to float

# Print using basic string concatenation
print("Name: " + name)
print("Age: " + str(age))       # Must convert int to str
print("Height: " + str(height)) # Must convert float to str
import java.util.Scanner;

public class Solution {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        
        // Read values from standard input
        String name = scanner.nextLine();   // Read string
        int age = scanner.nextInt();        // Read integer
        double height = scanner.nextDouble(); // Read double
        
        // Print each value separately
        System.out.println("Name: " + name);
        System.out.println("Age: " + age);
        System.out.println("Height: " + height);
        
        scanner.close();
    }
}

Complexity Analysis

Time Complexity: O(n)

Where n is the total length of all input strings. Reading each input line takes time proportional to the length of that line. Type conversion (int(), float()) takes O(k) where k is the number of digits. Printing also takes O(m) where m is the length of the output string. Overall, the time is linear in the size of the input/output.

Space Complexity: O(n)

We store each input value in a variable. The space used is proportional to the total size of the input data. For this problem with 3 fixed inputs, it is effectively O(1) in practice.

Why This Approach Is Not Efficient

The brute force approach using string concatenation with + has several drawbacks:

  1. Verbose type conversion: Every non-string value must be wrapped in str() before concatenating. Forget one str() call and Python raises a TypeError. This is a common bug for beginners.

  2. Poor readability: Expressions like "Age: " + str(age) + " years" become hard to read as the number of variables grows. The output template is broken into fragments separated by + signs.

  3. No formatting control: You cannot easily control decimal places (e.g., showing 1.65 instead of 1.6499999999999999), padding, or alignment with plain concatenation.

  4. Performance for many concatenations: Each + creates a new string object in memory. For many concatenations in a loop, this leads to O(n²) behavior because strings are immutable in Python.

A better approach would let us embed variables directly into a template string without manual str() calls, and give us control over formatting.

Better Approach - Comma-Separated print() Arguments

Intuition

Python's print() function can accept multiple arguments separated by commas. When you pass several values, print() automatically converts each one to a string and joins them with a space (by default). This means you never need to call str() manually.

Think of print() like a friendly assistant: you hand it a bunch of items — a word, a number, another word — and it arranges them neatly in a row with spaces between them. You can even change the separator from a space to anything you want using the sep parameter, and control what goes at the end of the line with the end parameter.

This approach eliminates the str() boilerplate entirely and is the standard way beginners are taught to print in Python.

Step-by-Step Explanation

Let's trace through with the input: name = "Alice", age = 25, height = 1.65

Step 1: Read all three inputs the same way as before: name = input(), age = int(input()), height = float(input()).

Step 2: Call print("Hello,", name). Python's print() takes two arguments: the string "Hello," and the variable name. It converts both to strings (name is already a string), joins them with a space, and outputs: Hello, Alice.

Step 3: Call print("You are", age, "years old"). Here print() receives three arguments. It converts age (integer 25) to the string "25" automatically, joins all three with spaces, and outputs: You are 25 years old.

Step 4: Call print("Height:", height, "meters"). Again, print() handles float-to-string conversion automatically. Output: Height: 1.65 meters.

Step 5: To combine everything on one line, we can use: print("Hello,", name + "!", "You are", age, "years old and", height, "meters tall."). The + on name + "!" is fine because both are strings. Everything else is comma-separated, so print() handles the conversions.

Step 6: We can customize the separator: print(name, age, height, sep=" | ") outputs Alice | 25 | 1.65. The sep parameter replaces the default space between arguments.

Step 7: We can suppress the trailing newline: print("Hello", end="") followed by print(" World") outputs Hello World on a single line. The end parameter controls what is printed after all arguments.

print() with Comma-Separated Arguments — Watch how print() automatically converts each argument to a string and joins them with the separator (default: space), eliminating the need for manual str() calls.

Algorithm

  1. Read the name, age, and height using input() with appropriate type conversions
  2. Pass all values as separate arguments to print(), separated by commas
  3. print() automatically converts each argument to a string
  4. print() joins all arguments with the sep character (default: space)
  5. print() appends the end character (default: newline)
  6. Optionally customize sep and end for different formatting

Code

#include <iostream>
#include <string>
using namespace std;

int main() {
    string name;
    int age;
    double height;
    
    getline(cin, name);
    cin >> age;
    cin >> height;
    
    // C++ cout handles type conversion automatically with <<
    cout << "Hello, " << name << "! You are " 
         << age << " years old and " 
         << height << " meters tall." << endl;
    
    return 0;
}
# Read values
name = input()
age = int(input())
height = float(input())

# print() with comma-separated arguments
# Automatically converts int and float to strings
print("Hello,", name + "!", "You are", age, "years old and", height, "meters tall.")

# Customize separator
print(name, age, height, sep=" | ")  # Output: Alice | 25 | 1.65

# Suppress newline with end parameter
print("Hello", end=" ")
print("World")  # Output: Hello World (on one line)
import java.util.Scanner;

public class Solution {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        
        String name = scanner.nextLine();
        int age = scanner.nextInt();
        double height = scanner.nextDouble();
        
        // Java's println handles type conversion with + operator
        System.out.println("Hello, " + name + "! You are " 
            + age + " years old and " 
            + height + " meters tall.");
        
        scanner.close();
    }
}

Complexity Analysis

Time Complexity: O(n)

Same as the brute force — reading and printing are linear in the size of input/output. The print() function internally converts each argument to a string and joins them, which is O(n) where n is the total length of the output.

Space Complexity: O(n)

The print() function builds an internal buffer to hold all the converted and joined strings before writing to stdout. This buffer is proportional to the total output length.

Why This Approach Is Not Efficient

The comma-separated print() approach solves the manual str() problem, but it still has limitations:

  1. Limited formatting control: You cannot easily specify decimal places (e.g., show exactly 2 decimal places for height), pad numbers with zeros, or align columns. The separator is the same between ALL arguments — you cannot have different spacing between different values.

  2. Awkward punctuation: To get "Hello, Alice!" (no space before the exclamation mark), we had to use name + "!" — mixing concatenation and comma-separation. This becomes messy for complex output formats.

  3. Template inflexibility: The output format is dictated by argument order. Rearranging the message means reordering all the arguments and their surrounding literal strings.

A truly modern approach would let us write a single template string with placeholders that get replaced by variable values, with full control over formatting.

Optimal Approach - f-strings (Formatted String Literals)

Intuition

Python 3.6 introduced f-strings (formatted string literals), the most elegant and powerful way to embed expressions inside strings. An f-string starts with the letter f before the opening quote, and you place variables or expressions inside curly braces {} directly within the string.

Think of an f-string as a fill-in-the-blank template: you write your sentence with blanks marked by {}, and Python fills in each blank with the value of the expression inside it. No manual conversion needed, no worrying about separators — just write your message naturally.

f-strings also support format specifiers after a colon inside the braces: {height:.2f} means "show height as a float with exactly 2 decimal places". This gives you full control over how numbers, strings, and dates are displayed.

This is the recommended, modern way to handle output in Python and is what professional developers use in production code.

Step-by-Step Explanation

Let's trace through with the input: name = "Alice", age = 25, height = 1.65

Step 1: Read all inputs: name = input()"Alice", age = int(input())25, height = float(input())1.65.

Step 2: Construct the f-string template: f"Hello, {name}! You are {age} years old and {height:.2f} meters tall."

Step 3: Python encounters {name} — it evaluates the variable name, which holds "Alice", and inserts the string "Alice" directly into the template at that position.

Step 4: Python encounters {age} — it evaluates the variable age, which holds the integer 25. Python automatically converts it to "25" and inserts it. No str() needed.

Step 5: Python encounters {height:.2f} — it evaluates height (which is 1.65), then applies the format specifier :.2f. The .2f means "fixed-point notation with exactly 2 decimal places". So 1.65 becomes "1.65". If height were 1.6, it would become "1.60" — the format specifier ensures consistent decimal places.

Step 6: The complete string is assembled: "Hello, Alice! You are 25 years old and 1.65 meters tall."

Step 7: print() outputs this single string. Since it is one argument (already a complete string), there is no separator logic involved.

Step 8: We can also use f-strings for more advanced formatting: f"{age:>10d}" right-aligns the age in a 10-character field, f"{name:*^20}" centers the name in a 20-character field padded with asterisks.

f-string Template Processing — Watch how Python evaluates each {placeholder} in an f-string, substitutes the value, and assembles the final string — all in a single expression with no manual conversion.

Algorithm

  1. Read the name, age, and height using input() with appropriate type conversions
  2. Construct an f-string with f"..." prefix
  3. Place variables or expressions inside {} placeholders within the string
  4. Optionally add format specifiers after a colon: {value:format_spec}
    • :.2f — float with 2 decimal places
    • :>10 — right-align in 10-character field
    • :05d — integer padded with zeros to 5 digits
  5. Pass the f-string to print() — it is already a complete, formatted string
  6. For input validation, wrap int() or float() in a try/except ValueError block

Code

#include <iostream>
#include <string>
#include <iomanip>
using namespace std;

int main() {
    string name;
    int age;
    double height;
    
    getline(cin, name);
    cin >> age;
    cin >> height;
    
    // C++20 std::format or printf-style formatting
    // Using cout with manipulators for formatting
    cout << "Hello, " << name << "! You are " 
         << age << " years old and " 
         << fixed << setprecision(2) << height 
         << " meters tall." << endl;
    
    // Alternative: printf-style (works in all C++ versions)
    printf("Hello, %s! You are %d years old and %.2f meters tall.\n",
           name.c_str(), age, height);
    
    return 0;
}
# Read values
name = input()
age = int(input())
height = float(input())

# f-string: clean, readable, powerful
print(f"Hello, {name}! You are {age} years old and {height:.2f} meters tall.")

# Format specifier examples:
print(f"Name: {name:>20}")       # Right-align in 20 chars
print(f"Age: {age:05d}")          # Zero-padded to 5 digits: 00025
print(f"Height: {height:.4f}")    # 4 decimal places: 1.6500
print(f"Pi is approximately {3.14159:.2f}")  # Inline expression: 3.14

# Expressions inside f-strings
print(f"Next year you will be {age + 1} years old.")
print(f"Name in uppercase: {name.upper()}")

# Input validation with try/except
try:
    user_age = int(input())
except ValueError:
    print("Invalid input: please enter a whole number for age.")
import java.util.Scanner;

public class Solution {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        
        String name = scanner.nextLine();
        int age = scanner.nextInt();
        double height = scanner.nextDouble();
        
        // Java's String.format or System.out.printf
        // Similar to f-strings but uses %s, %d, %f placeholders
        System.out.printf("Hello, %s! You are %d years old and %.2f meters tall.%n",
                          name, age, height);
        
        // Alternative: String.format returns a String
        String message = String.format("Name: %-20s Age: %05d Height: %.2f",
                                       name, age, height);
        System.out.println(message);
        
        scanner.close();
    }
}

Complexity Analysis

Time Complexity: O(n)

The f-string is evaluated in a single pass. Each placeholder is resolved by looking up the variable and converting it to a string, which takes O(k) where k is the length of the string representation. The total time is O(n) where n is the length of the resulting output string.

Space Complexity: O(n)

The f-string creates a single new string object containing the fully formatted output. This string's length is proportional to the total output, so space is O(n). Compared to concatenation (which creates intermediate string objects for each + operation), f-strings are more memory-efficient because they build the result in a single allocation.