Python (Beginner) - Lesson 3: Variables, User Input, and Basic I/O
Welcome to Lesson 3! In this lesson, we will explore how to store and manipulate data using variables, capture user input from the keyboard, and display output to the screen. These are foundational skills for any interactive program and are critical as you progress in Python programming. We will cover variable assignment, the mechanics of dynamic typing, methods for receiving input, and multiple techniques for formatting output—all while working in Visual Studio Code.
Variables
What Are Variables?
Variables in Python act as containers that store data values. Unlike some other programming languages, Python is dynamically typed. This means that you do not need to declare the type of a variable when you create it; Python determines the data type automatically based on the value assigned. This feature makes Python both flexible and easy to use, especially for beginners.
Key Points About Variables:
Dynamic Typing:
You can assign a value to a variable without explicitly declaring its type.
The type of the variable can change over time if you reassign it a new value of a different type.
Naming Conventions:
Choose meaningful variable names to make your code easier to understand.
Use lowercase letters and underscores for multi-word variable names (e.g.,
user_name
,favorite_color
).Avoid using Python reserved words (such as
print
,if
,else
, etc.) as variable names.
Example Code:
# Variable assignment examples
name = "Alice" # A string variable storing a name
age = 30 # An integer variable storing age
pi_value = 3.14159 # A float variable storing a numerical value
is_student = True # A boolean variable indicating a true/false condition
Explanation:
name
holds a sequence of characters (a string).age
holds an integer value.pi_value
holds a float, which is a number with a decimal point.is_student
is a boolean variable that can be eitherTrue
orFalse
.
The dynamic nature of Python means that you can later reassign these variables to values of a different type if needed, though doing so may not always be recommended for code clarity.
User Input
The input()
Function:
Python provides a built-in function called input()
that allows your program to capture input from the user. When input()
is called, the program pauses and waits for the user to type something in the VS Code integrated terminal. Whatever the user types is returned as a string.
Key Points:
Always Returns a String:
Even if the user types a number,
input()
will return that number as a string.If you need to perform arithmetic operations, convert the string to the appropriate numeric type (e.g.,
int()
orfloat()
).
Prompting the User:
You can pass a prompt string to the
input()
function to instruct the user on what to enter.
Example Code:
# Prompting the user for their name
user_name = input("Enter your name: ")
# Output a greeting using the captured input
print("Hello, " + user_name + "! Welcome to Python programming.")
Explanation:
The program displays the prompt
"Enter your name: "
in the VS Code terminal.The user's input is stored in the variable
user_name
.The
print()
function concatenates the greeting message with the value ofuser_name
and outputs the result.
String Formatting
As you start creating dynamic messages, you’ll often need to combine fixed text with variable data. Python offers several ways to format strings. Two popular methods are concatenation and f-string formatting.
1. Concatenation:
Concatenation involves using the +
operator to join strings together.
Example:
# Using concatenation to combine strings
user_name = input("Enter your name: ")
greeting = "Hello, " + user_name + "! Welcome to Python programming."
print(greeting)
Drawbacks:
It can be cumbersome when combining multiple variables or when converting non-string values (you must explicitly convert numbers using
str()
).It may reduce readability when building complex strings.
2. f-Strings (Formatted String Literals):
Introduced in Python 3.6, f-strings allow you to embed expressions directly inside string literals by prefixing the string with an f
.
Example:
# Using f-strings for a cleaner approach
user_name = input("Enter your name: ")
greeting = f"Hello, {user_name}! Welcome to Python programming."
print(greeting)
Advantages of f-Strings:
Readability: The code is cleaner and easier to understand.
Flexibility: You can embed any valid Python expression inside the braces.
Efficiency: f-strings are generally faster and more concise than other formatting methods.
Additional Example:
Let’s consider a scenario where we ask the user for their first and last names and display a personalized greeting:
# Asking for first and last names separately
first_name = input("Enter your first name: ")
last_name = input("Enter your last name: ")
# Using both concatenation and f-string formatting for demonstration
# Concatenation method
greeting_concat = "Hello, " + first_name + " " + last_name + "! Welcome to Python programming."
print("Using concatenation:")
print(greeting_concat)
# f-string method
greeting_fstring = f"Hello, {first_name} {last_name}! Welcome to Python programming."
print("Using f-string formatting:")
print(greeting_fstring)
Explanation:
The code first gathers
first_name
andlast_name
from the user.It then constructs the greeting message using both concatenation and f-string methods.
This side-by-side demonstration shows the differences in readability and ease-of-use between the two methods.
Basic Input/Output in Visual Studio Code
Working in Visual Studio Code, you will use the integrated terminal to interact with your Python programs. Here are some tips:
Running Your Code:
Save your file with a
.py
extension (e.g.,lesson3_variables_io.py
).Open the integrated terminal in VS Code (use the menu: Terminal > New Terminal).
Run your script by typing
python lesson3_variables_io.py
and pressing Enter.
Debugging Output:
Use the
print()
function liberally to display variable values and understand your program's flow.The integrated terminal will show all output, making it easy to test and debug your code.
Tasks
Now it’s time to put what you’ve learned into practice. Complete the following tasks using Visual Studio Code:
Favorite Color Program:
Create a new Python file (e.g.,
favorite_color.py
).Write a program that:
Asks the user for their favorite color using the
input()
function.Constructs a greeting message that includes the entered color using f-string formatting.
Prints the final message to the screen.
String Formatting Experiment:
Modify your program from Task 1 to include both methods of string formatting:
Use string concatenation to create the greeting message.
Use an f-string to create the greeting message.
Run both versions and compare the readability and ease-of-use.
Variable Exploration:
In a new Python file (e.g.,
variable_exploration.py
), declare several variables of different types:A string variable for a person’s name.
An integer variable for their age.
A float variable for a balance or measurement.
A boolean variable to indicate a condition (e.g.,
is_member
).
Use the
print()
function to display each variable along with a brief description.Add comments to explain the purpose of each variable and the reasoning behind the chosen values.
Recall Questions
Review and answer the following questions to solidify your understanding of today’s lesson:
How does the
input()
function work in Python?Describe how it captures user input and what type of data it returns by default.
What is the benefit of using f-strings for formatting output?
Explain how f-strings enhance readability and simplify the inclusion of variables within text.
Explain how Python handles variable assignment.
Discuss dynamic typing and the flexibility of reassigning variables without explicit type declarations.
By completing this lesson, you’ve learned how to manage data using variables, interact with the user through input and output functions, and format strings using different techniques. These skills are essential for building interactive programs and serve as a stepping stone to more complex projects. Continue practicing these concepts in Visual Studio Code to develop fluency in writing clean, efficient Python code.