Python Tutorial: Print Output and Variables
This tutorial will guide you through the fundamental concepts of printing output and working with variables in Python. We’ll build up our understanding through practical examples, focusing on clear explanations and executable code.
Example 1: Basic Printing
The first step is to learn how to display output to the console. Python’s `print()` function is your primary tool for this. It can take any number of arguments, which will be converted to strings and printed with a space between each. Let’s start with a simple example.
# This program demonstrates the basic print() function.
# It prints "Hello, world!" and then some numbers to the console.
name = "Alice"
age = 30
height = 1.75
print("Hello, world!")
print(name)
print(age)
print(height)
# Calculating the BMI (Body Mass Index)
weight = 70 # in kilograms
bmi = weight / (height 2)
print("BMI:", bmi)
# Common mistake: Incorrect string concatenation
# print("My name is " + name + " and I am " + str(age) + " years old.") # This would cause an error
# Correct way: Use f-strings (formatted string literals)
print(f"My name is {name} and I am {age} years old.")
This code first prints a basic greeting. Then, it prints the values of the variables `name`, `age`, and `height`. The BMI calculation demonstrates a simple mathematical operation. The commented-out code shows a common mistake when concatenating strings – you must convert numeric values to strings using `str()`. The f-string is a modern and more readable way to combine variables into a string. F-strings are enclosed in curly braces `{}` and allow you to directly embed variables within a string.
Explanation: The `print()` function takes the provided strings and numbers as input, converts them to strings, and then displays them on the console, separated by spaces. The f-string efficiently substitutes the variables `name` and `age` into the string, generating the final output.
Key takeaway: Understand how `print()` works and when to use f-strings for flexible output.
Output
Hello, world!
Alice
30
1.75
BMI: 23.233071349984146
My name is Alice and I am 30 years old.
Example 2: Variable Assignment and Data Types
Variables in Python store values. Python has several built-in data types, including integers, floats, strings, and booleans. We’ll explore these and how to assign them to variables.
# This program demonstrates variable assignment and different data types.
# Integer
number = 10
# Float
price = 99.99
# String
message = "Welcome!"
# Boolean
is_valid = True
# Printing the variables
print("Number:", number)
print("Price:", price)
print("Message:", message)
print("Is valid:", is_valid)
# Performing arithmetic operations
sum_result = number + price
print("Sum:", sum_result)
# String concatenation with f-strings
greeting = f"The price is {price:.2f}." # .2f formats the float to two decimal places
print(greeting)
In this example, we assign different data types to variables. We then print these variables to the console. We also perform a simple addition and demonstrate string formatting using f-strings. The `:.2f` format specifier ensures that the `price` is printed with exactly two decimal places.
Explanation: The `print()` function displays the values stored in the variables. The f-string allows us to format the output, specifying the precision of the floating-point number.
Key takeaway: Learn about different data types in Python and how to use f-strings for formatting output.
Output
Number: 10
Price: 99.99
Message: Welcome!
Is valid: True
Sum: 109.99
The price is 99.99.
Example 3: User Input and Variable Conversion
We can also get input from the user using the `input()` function. However, the `input()` function returns a string. Therefore, we often need to convert the input to a different data type (e.g., integer or float) using `int()` or `float()`.
# This program takes user input, converts it to an integer and a float,
# and performs a calculation.
# Prompt the user to enter their name
name = input("Enter your name: ")
# Prompt the user to enter their age
try:
age = int(input("Enter your age: "))
except ValueError:
print("Invalid age. Please enter a number.")
exit()
# Prompt the user to enter the radius of a circle
try:
radius = float(input("Enter the radius of the circle: "))
except ValueError:
print("Invalid radius. Please enter a number.")
exit()
# Calculate the area of the circle
area = 3.14159 radius radius
# Print the results
print("Name:", name)
print("Age:", age)
print("Radius:", radius)
print("Area of the circle:", area)
# Common mistake: If the user enters a non-numeric value for age or radius, the program will crash.
# To prevent this, use try-except blocks to handle potential ValueError exceptions.
This example demonstrates how to get user input and convert it to different data types. The `try-except` block handles potential `ValueError` exceptions that may occur if the user enters non-numeric input. This makes the program more robust.
Explanation: The `input()` function reads a string from the user. The `int()` and `float()` functions convert the string to an integer and a float, respectively. The `try-except` block handles errors that occur if the conversion fails.
Key takeaway: Learn how to handle user input and perform data type conversions safely.
Output
Enter your name: John
Enter your age: 25
Enter the radius of the circle: 5.0
Name: John
Age: 25
Radius: 5.0
Area of the circle: 78.53975



Leave a Reply