Python fundamentals
Variables and assignment
Give values names, update them with assignment, and use clear Python variable names.
Lesson 7 of 63
Reading: about 2 min
Lesson + practice: about 10 min
Difficulty: Beginner
On this page5 sections
A variable is a name that refers to a value. The = sign assigns the value on its right to the name on its left. Create a new file named variables.py in your python-roadmap folder and run it as you did in Chapter 1.
name = "Sam"
sessions = 3
print(name)
print(sessions)Sam 3
Update a value
Assigning a new value to the same name replaces its previous value. Python reads the statements in order.
sessions = 3
sessions = 4
print(sessions)4
Choose clear names
Variable names can contain letters, digits, and underscores, but cannot start with a digit. Names are case-sensitive: study_minutes and Study_minutes are different. Use descriptive lowercase names with underscores, such as minutes_per_session. Avoid spaces and Python keywords such as class.
Why this works
The name on the left of = receives the value calculated on the right. Reassignment changes what that name refers to from that point onward; earlier output does not change retroactively. A descriptive name helps a reader understand what a number measures.
Practice
Create variables for your name, the number of study sessions you plan, and the minutes in each session. Print each value. Then change the number of sessions, save, and rerun the script.
What does sessions = 4 do?
Reveal answer
It assigns the integer value 4 to the name sessions.
Try another case
After count = 2 and then count = count + 3, what does print(count) show?
Check your answer
Reveal answer
It shows 5. Python evaluates the old count plus 3, then assigns the result back to count.
Your progress
Reveal the check answer or reach the end to complete this lesson.