Python Tutorial: Print Output and Work with Variables
This tutorial will guide you through the fundamentals of printing output and working with variables in Python. We’ll build up our understanding through a series of examples, focusing on clear, concise code and explanations.
Example 1: Basic Printing and String Concatenation
The first step is to learn how to print text to the console. We’ll also explore how to combine strings using concatenation.
# This program prints a greeting message and calculates the area of a rectangle.
# Define variables
name = "Alice"
length = 5
width = 3
# Print the greeting
print("Hello, " + name + "!")
# Calculate the area
area = length width
# Print the area
print("The area of the rectangle is: " + str(area))
In this example:
- We define variables `name`, `length`, and `width` with different values.
- We use the `print()` function to display text and the calculated area.
- The `str()` function is used to convert the numerical `area` value to a string before concatenating it with the other string parts. This is necessary because you cannot directly concatenate a number with a string in Python.
Let’s trace the execution:
- `name` is assigned “Alice”.
- `length` is assigned 5.
- `width` is assigned 3.
- `print(“Hello, ” + name + “!”)` prints “Hello, Alice!”.
- `area = length width` calculates 5 3 = 15 and stores it in `area`.
- `print(“The area of the rectangle is: ” + str(area))` prints “The area of the rectangle is: 15.”.
# This program demonstrates different ways to print output.
# Using f-strings (formatted string literals) - Recommended
print(f"My name is {name} and I am {age} years old.")
# Using the .format() method
print("My name is {} and I am {} years old.".format(name, age))
# Using the % operator (older style)
print("My name is %s and I am %d years old." % (name, age))
In this example, we show three ways to print output with formatted strings. F-strings are the most modern and readable, while the other two have their uses as well.
Let’s trace the execution:
- We are using the f-string to print a personalized greeting.
- We are using the .format() method to print a personalized greeting.
- We are using the % operator to print a personalized greeting.
Example 2: Working with Numbers and Calculations
Now, let’s explore basic arithmetic operations and how to handle different data types like integers and floats. We’ll calculate the square of a number and perform addition and subtraction.
# This program calculates the square of a number and performs basic arithmetic operations.
# Define variables
number = 7
# Calculate the square
square = number number
# Perform addition and subtraction
sum_result = 10 + 5
difference_result = 20 - 8
# Print the results
print("The square of", number, "is:", square)
print("10 + 5 =", sum_result)
print("20 - 8 =", difference_result)
# Experiment with floats
float_number = 3.14
float_sum = 2.5 + float_number
print("Sum of 2.5 and", float_number, "is:", float_sum)
Here, we demonstrate:
- Basic arithmetic operations (multiplication, addition, subtraction).
- How to handle integer and float data types.
- String formatting for clear output.
Let’s trace the execution:
- `number` is assigned 7.
- `square` is calculated as 7 7 = 49.
- `sum_result` is calculated as 10 + 5 = 15.
- `difference_result` is calculated as 20 – 8 = 12.
- We print the results of the calculations.
- We demonstrate the addition of a float (3.14) with a float (2.5).
Example 3: Input from the User (Simple Prompt)
Finally, let’s take input from the user using the `input()` function. We’ll ask the user for their name and print a personalized greeting.
# This program takes user input and prints a personalized greeting.
# Prompt the user to enter their name
name = input("Enter your name: ")
# Print a greeting
print("Hello, " + name + "!")
In this example:
- We use the `input()` function to prompt the user to enter their name.
- The `input()` function returns a string.
- We concatenate this string with “Hello, ” and “!” to create a personalized greeting.
Let’s trace the execution:
- The program pauses and waits for the user to type their name and press Enter.
- The user enters “Bob”.
- `print(“Hello, ” + name + “!”)` prints “Hello, Bob!”.
# This program demonstrates input validation (basic example)
# Prompt the user for a number
try:
number = int(input("Enter a positive integer: "))
if number > 0:
print("You entered:", number)
else:
print("Please enter a positive integer.")
except ValueError:
print("Invalid input. Please enter a valid integer.")
This example demonstrates basic input validation. This checks to see that the input entered by the user is a positive integer. If not, it throws an error. The try/except block allows the user to try to enter an integer, and the program doesn’t crash.
Output:
Output for Example 1:
Hello, Alice!
The area of the rectangle is: 15.
Output for Example 2:
The square of 7 is: 49
10 + 5 = 15
20 - 8 = 12
Sum of 2.5 and 3.14 is: 5.64
Output for Example 3:
Enter your name: Bob
Hello, Bob!
Output for Example 3 (with input validation):
Output for Example 3:
Enter a positive integer: 10
You entered: 10
Output for Example 3:
Enter a positive integer: -5
Please enter a positive integer.
Output for Example 3:
Enter a positive integer: abc
Invalid input. Please enter a valid integer.



Leave a Reply