In Python, input and output are fundamental concepts. The input()
function allows us to collect data from the user, and the print()
function allows us to display information on the screen.
The input()
function allows us to get input from the user. It takes an optional string argument, which is displayed as a prompt to the user:
name = input("What is your name? ")
print("Hello, " + name + "!")
input()
function waits for the user to type something and press Enter.print()
function.The input provided by the user through the input()
function is always a string. If you need to work with numbers, you must convert the input using functions like int()
or float()
.
If you need to convert the input to another data type, such as an integer or a floating-point number, you can use type conversion:
age = int(input("Enter your age: "))
print("Your age is", age)
If the user enters a non-numeric value, a ValueError
will be raised.
Always validate user input to prevent unexpected behavior or crashes, especially when expecting numeric data.
To display information on the screen, we use the print()
function. Here's a basic example:
print("Hello, world!")
This will output:
Hello, world!
You can also print multiple items in a single print()
statement. Python will automatically separate them with a space:
name = "Alice"
age = 30
print("Name:", name, "Age:", age)
Output:
Name: Alice Age: 30
The print()
function can take multiple arguments and automatically separates them with spaces. You can customize the separator using the sep
parameter.
Objective: Write a program that asks the user for their name and age, then outputs a message with their name and age formatted in a sentence.
Create a Python File:
Create a file named name_age.py
.
Get User Input:
Use the input()
function to ask for the user's name and age.
Example:
name = input("What is your name? ")
age = int(input("Enter your age: "))
Print Output:
Print a message using the print()
function that includes the user's name and age.
Example:
print(f"Hello, {name}! You are {age} years old.")
Objective: Extend the program to calculate the year the user was born by subtracting their age from the current year.
Import the datetime
Module:
Import the datetime
module to get the current year.
Example:
import datetime
Get User Input:
Use the input()
function to ask for the user's name and age.
Example:
name = input("What is your name? ")
age = int(input("Enter your age: "))
Calculate Year of Birth: Subtract the user's age from the current year to calculate the year of birth.
Example:
current_year = datetime.datetime.now().year
birth_year = current_year - age
Print Output: Print a message telling the user the year they were born.
Example:
print(f"Hello, {name}! You were born in {birth_year}.")