Lesson 3: Basic Input and Output

In this lesson, we will learn how to handle basic input and output operations in Python. We will cover how to receive user input using the input() function, how to display output using the print() function, and how to format strings for better display and readability.

1. Using input() Function

The input() function in Python is used to accept input from the user during the execution of the program. The input is always returned as a string, and you can then process or convert the data as required.

Basic Syntax:
python
user_input = input(prompt)

 

  • prompt(optional): A string that is displayed to the user before the input is received.
Example:
python
name = input(“Enter your name: “)

print(“Hello, ” + name)

 

In this example, when the program runs, the user will see the message “Enter your name: ” and will be able to type in their name. After input is provided, the program will greet the user with their name.

Note: The input() function always returns the input as a string. If you need to convert it to a different type (e.g., integer or float), you need to explicitly convert it.

Example of Type Conversion:
python

age = input(“Enter your age: “)  # This will return a string

age = int(age)  # Convert the string to an integer

print(“Your age is:”, age)

 

In this case, the input from the user is converted into an integer using the int() function, and it is then printed as part of the output.

2. Displaying Outputs with print()

The print() function in Python is used to display information or output to the console. It can be used to print strings, variables, or any expressions in Python.

Basic Syntax:
python
print(object, …, sep=’ ‘, end=’\n’, file=sys.stdout, flush=False)

 

  • object: The value or expression you want to print.
  • sep: The separator between multiple objects (optional, default is a space).
  • end: The string appended at the end of the printed line (optional, default is a newline).
  • file: A file object where the output will be sent (optional).
  • flush: Whether to forcibly flush the stream (optional).
Example:
python
print(“Hello, World!”)

 

This will output:

output
Hello, World!

 

Multiple Arguments:

You can pass multiple arguments to the print() function. By default, these will be separated by a space:

python

name = “John”

age = 25

print(“Name:”, name, “Age:”, age)

 

This will output:

output
makefile
output

Name: John Age: 25

 

Custom Separator:

You can customize the separator between multiple arguments by using the sep parameter:

python
print(“apple”, “banana”, “cherry”, sep=”, “)

 

This will output:

output
apple, banana, cherry

 

Custom End Character:

You can also customize the end of the print statement by using the end parameter. By default, it ends with a newline character, but you can change it:

python
print(“Hello”, end=” “)

print(“World!”)

 

This will output:

output
nginx
output
Hello World!

 

The end=” ” parameter ensures that the output is not followed by a new line, but instead continues on the same line.

3. String Formatting

String formatting allows you to insert values into strings dynamically. This can make your code more readable and concise, especially when displaying complex outputs. Python provides several ways to format strings.

3.1. Using + for Concatenation

You can concatenate (combine) strings using the + operator:

python
name = “Alice”

age = 30

print(“My name is ” + name + ” and I am ” + str(age) + ” years old.”)

 

Output:

Output
pgsql
Output
My name is Alice and I am 30 years old.

 

Note: When using concatenation with the + operator, you need to explicitly convert non-string values to strings (e.g., str(age)).

3.2. Using str.format() Method

The str.format() method provides a more flexible way of formatting strings. You can use placeholders {} to define where the values should be inserted, and then pass the values as arguments to the format() method.

Example:

python
name = “Alice”

age = 30

print(“My name is {} and I am {} years old.”.format(name, age))

 

Output:

Output
pgsql
python

My name is Alice and I am 30 years old.

 

You can also refer to the arguments by their index or use named placeholders:

python
print(“My name is {0} and I am {1} years old.”.format(name, age))

# Output: My name is Alice and I am 30 years old.

 

# Using named placeholders

print(“My name is {name} and I am {age} years old.”.format(name=”Alice”, age=30))

# Output: My name is Alice and I am 30 years old.

 

3.3. Using f-strings (Formatted String Literals)

f-strings are a more modern and concise way to format strings, introduced in Python 3.6. You can embed expressions inside string literals using curly braces {} and prefix the string with the letter f.

Example:

python
name = “Alice”

age = 30

print(f”My name is {name} and I am {age} years old.”)

 

Output:

Output
pgsql
python
My name is Alice and I am 30 years old.

 

f-strings are particularly useful because they evaluate expressions directly inside the curly braces. For example:

python
x = 5

y = 10

print(f”The sum of {x} and {y} is {x + y}.”)

 

Output:

python
The sum of 5 and 10 is 15.

 

3.4. Formatting Numbers

You can also use string formatting to control the appearance of numbers, such as limiting the number of decimal places or formatting large numbers with commas.

Example (rounding decimals):

python

pi = 3.141592653589793

print(f”Value of pi: {pi:.2f}”)

 

Output:

Output
lua
python
Value of pi: 3.14

 

Here, :.2f rounds the number to two decimal places.

Example (adding commas to large numbers):

python
large_number = 1000000

print(f”Large number: {large_number:,}”)

 

Output:

Output
sql
python
Large number: 1,000,000

Comments

Leave a Reply

Your email address will not be published. Required fields are marked *