Python Variables
Now that you’ve set up Python and written your first “Hello, World!” program, it’s time to dive into some foundational concepts. We’ll explore Python’s basic syntax, how to store data with “variables”, and talk about the different types of data you’ll work with in Python.
Table of Contents
What Are Variables?
Variables are used to store data. Think of them as containers that hold information. In Python, creating a variable is simple: just assign a value to a name.
Creating a Variable
To create a variable, use the =
sign to assign a value:
name = "Alice"
age = 25
In this example:
- The variable
name
stores the value"Alice"
(a string). - The variable
age
stores the value25
(an integer).
Variable Naming Rules
There are a few rules and conventions for naming variables:
- Must start with a letter or an underscore (
_
). - Can contain letters, numbers, and underscores (but can’t start with a number).
- Cannot be Python keywords (such as
print
,if
,else
,while
, etc.).
Examples of valid variable names:
first_name = "Bob"
age_25 = 25
_location = "New York"
Examples of invalid variable names:
2nd_name = "Bob" # Invalid: starts with a number
first-name = "Bob" # Invalid: uses a hyphen instead of an underscore
You can use any valid name for a value, but try to use variable names that reflect the data you are storing. For example, it is perfectly valid Python to write
age = "Bob" # Bad choice of variable name
name = 25 # Neither is this
But it’s not a good idea. When you come back to this code after a period of time, you will find it very hard to understand. One day soon, you might want to give your code to another developer, or even publish it! When you do, you want it to be as easy to understand as possible.
Data Types in Python
Python has several built-in data types – we have mentioned two of them already (Integers and Strings). The most common types are:
1. Integer (int)
Integers are whole numbers without a decimal point.
age = 30
2. Floating Point (float)
Floating point numbers or just “floats” are numbers a decimal point.
price = 19.99
3. String (str)
Text, enclosed in either single quotes ('
) or double quotes ("
) are called “strings”
name = "Alice"
greeting = 'Hello, world!'
4. Boolean (bool)
Represents True
or False
.
is_sunny = True
is_raining = False
You don’t need to specify the type of a variable when creating it. Python is dynamically typed, meaning it infers the type of the variable from the value you assign.
Working with Variables
You can perform various operations on variables depending on their type.
1. Changing a Variable’s Value
You can reassign a variable to a new value at any time.
x = 10
x = 20 # Now x is 20
2. Using Variables in Expressions
You can use variables in mathematical operations, or concatenate them if they’re strings.
# Integer addition
a = 5
b = 3
result = a + b
print(result) # Output: 8
# String concatenation
first_name = "John"
last_name = "Doe"
full_name = first_name + " " + last_name
print(full_name) # Output: John Doe
3. Combining Different Data Types
You may sometimes need to combine different types of variables. For example, you can print both text and numbers together using the str()
function to convert numbers to strings.
age = 25
message = "I am " + str(age) + " years old."
print(message) # Output: I am 25 years old.
Comments and Code Structure
Comments are pieces of text in your code that Python ignores. They are useful for explaining what your code does and making it more readable.
Single-Line Comments
Use the #
symbol to write a single-line comment:
# This is a single-line comment
age = 30 # Variable storing the age
Multi-Line Comments
You might not want to use a #
symbol on every line for a long multi-line comment. In that case you can use triple quotes ("""
or '''
) for block comments.
"""
This is a multi-line comment.
It can span multiple lines.
"""
The Print() Function Revisited
The print()
function is used to display output to the screen. You can print variables, strings, and results of expressions. Here’s how to use it effectively:
Printing Multiple Values
You can print multiple values by separating them with commas:
name = "Alice"
age = 25
print("Name:", name, "Age:", age) # Output: Name: Alice Age: 25
This way, you can print different types of variables (like strings and integers) together without needing to convert types.
Usinf f-strings for Better String Formatting
Python provides a convenient way to format strings using f-strings. An f-string
allows you to embed expressions inside string literals.
name = "Alice"
age = 25
print(f"My name is {name} and I am {age} years old.")
# Output: My name is Alice and I am 25 years old.
With f-strings
, you don’t need to worry about converting types manually — Python handles it for you.
Basic Input from the User
To make programs interactive, you can ask the user for input using the input()
function. The input is always read as a string, so you may need to convert it to the desired type.
Using Input()
name = input("Enter your name: ")
print(f"Hello, {name}!")
Converting User Input
If you need a number, you’ll need to convert the input to the appropriate type (e.g., int
or float
).
age = input("Enter your age: ") # age is a string
age = int(age) # Convert the input to an integer
print(f"You are {age} years old.")
Key Concepts Recap
- Variables store data such as numbers, strings, and booleans.
- Python is dynamically typed, meaning the type of variable is determined by the value it holds.
- The
print()
function is used to display information, andinput()
allows for user input. - Use comments to make your code readable and understandable.
Exercises
- Create variables for your name, age, and favorite color. Print them in a single sentence using an
f-string
. - Write a program that asks the user for their birth year, calculates their current age, and prints it.
- Experiment with creating different types of variables (integers, floats, booleans, strings) and printing them.
Next time, we’ll explore basic operations and expressions, including how to perform arithmetic, comparison, and logical operations in Python.
FAQ
Q1: Do I need to declare the type of a variable in Python?
A1: No, Python is a dynamically typed language, meaning you don’t need to explicitly declare the type of a variable. The type is automatically inferred based on the value you assign. For example, age = 25
will automatically be recognized as an integer (int
), and name = "Alice"
will be recognized as a string (str
).
Q2: Why do I get an error when I try to combine strings and numbers using +
?
A2: Python doesn’t allow you to directly combine a string with a number using the +
operator. For example, print("I am " + 25 + " years old")
will result in an error because you can’t add a string and an integer. To fix this, you need to convert the number to a string using str()
, like this:
print("I am " + str(25) + " years old")
Alternatively, use an f-string:
print(f"I am {25} years old")
Q3: How do I change the type of a variable?
A3: To change a variable’s type, you can use Python’s built-in type conversion functions such as int()
, float()
, str()
, and bool()
. For example:
x = "100" # x is a string
x = int(x) # Now x is an integer
Python doesn’t implicitly convert types during operations, so you need to manually convert them when necessary.
Q4: Why is user input from input()
always treated as a string, even when I type a number?
A4: The input()
function always returns the user input as a string, even if the user enters a number. If you need a number (like an integer or a float), you must explicitly convert the input using int()
or float()
. For example:
age = input("Enter your age: ") # This will be a string
age = int(age) # Convert the string to an integer
Q5: How can I check the type of a variable?
A5: You can use the type()
function to check the data type of a variable. For example:
age = 25
print(type(age)) # Output: <class 'int'>
This is useful when debugging or verifying the type of data you’re working with.
Q6: What happens if I try to reassign a variable to a different type?
A6: In Python, you can freely reassign a variable to a value of a different type because Python is dynamically typed. For example:
x = 10 # x is an integer
x = "hello" # Now x is a string
However, be careful when doing this, as it can make your code harder to understand and debug if variable types change unexpectedly.
Q7: Can I create a variable name with spaces or special characters?
A7: No, variable names in Python cannot contain spaces or special characters (like @
, #
, or -
). Variable names must start with a letter or an underscore (_
), and they can contain letters, numbers, and underscores. For example, first_name
is a valid variable name, but first-name
or first name
is not.
Q8: How can I write multi-line strings?
A8: You can write multi-line strings by using triple quotes ('''
or """
). This allows you to span text across multiple lines, which can be useful for long strings or documentation within your code. For example:
message = """This is a multi-line
string that spans multiple
lines."""
Q9: What’s the difference between a comment and a string in Python?
A9: A comment is a piece of text ignored by Python and is meant for developers to read. Comments are made using the #
symbol. Strings, on the other hand, are actual data used by your program. If you want to add notes or explanations that won’t be executed by Python, use a comment.
For example:
# This is a comment
name = "Alice" # This is another comment
# Triple quotes can also be used for multi-line comments:
"""
This is a multi-line comment
which can span several lines.
"""
However, triple quotes are technically strings (even if not assigned to a variable), but Python ignores them when they are not used as part of the code. It’s common to use triple quotes as multi-line comments, though single-line comments with #
are more typical.
Q10: What does it mean when we say Python is case-sensitive?
A10: Python is a case-sensitive language, which means that variable names like age
, Age
, and AGE
are considered three distinct variables. Be careful with capitalization, as it can cause bugs if you accidentally use the wrong case for variable names.
Q11: What happens if I try to use a variable before assigning it a value?
A11: If you try to use a variable before it has been assigned a value, Python will raise a NameError
. For example:
print(x) # NameError: name 'x' is not defined
To avoid this, make sure all variables are defined before you use them in your code.
Q12: Can I assign multiple variables at once?
A12: Yes, Python allows you to assign values to multiple variables in a single line. For example:
x, y, z = 1, 2, 3
This assigns x = 1
, y = 2
, and z = 3
in a single statement. You can also assign the same value to multiple variables:
a = b = c = 10
Q13: What is a “SyntaxError”, and how can I avoid it?
A13: A SyntaxError
occurs when the Python interpreter encounters code that doesn’t follow Python’s syntax rules. Common causes include:
- Missing colons (
:
) in control statements likeif
,for
, andwhile
. - Incorrect indentation.
- Using the wrong operator (e.g.,
=
instead of==
for comparisons).
To avoid syntax errors, ensure that your code follows Python’s syntax rules carefully. When aSyntaxError
occurs, Python usually tells you where the error is, which helps in debugging.
Q14: Why is indentation so important in Python?
A14: In Python, indentation is used to define code blocks (such as in functions, loops, and conditionals). Unlike other programming languages that use braces ({}
) to define blocks of code, Python uses indentation. If the indentation is incorrect, Python will raise an IndentationError
. Make sure you consistently use the same amount of spaces (usually 4 spaces) or tabs.
For example:
if age > 18:
print("You are an adult.")
else:
print("You are a minor.")
Q15: Can I change the value of a variable after it has been created?
A15: Yes, you can change (we say, ‘reassign’) the value of a variable at any time in Python. For example:
x = 10
x = 20 # Now x is 20
Python allows variables to change type as well as value, so a variable that once held an integer can later hold a string.
Practice Ideas
- Experiment with different data types: Try storing different types of data in variables (like strings, integers, booleans, and floats) to get familiar with how Python handles them.
- Debugging tips: When working with input and output, if something doesn’t behave as expected, use
print()
statements to display variable values at different stages of your program to help identify issues.