Python - Chapter 1 - Introduction to Variables, Data Types, & Expressions
Python: Lessons, Lectures, & Labs - Robots & Rovers - 🤖🚙
Python: Lessons, Lectures, & Labs - Robots & Rovers - 🤖🚙
Web Site: WWW.STEAMCLOWN.ORG | Contact: TopClown@STEAMClown.org | LinkedIn: Jim Burnham | You Tube: jimTheSTEAMClown | TikTok: STEAM Clown
Consider Supporting my Open Source STEAM Curriculum Development -- Check Out My How To Help Page - Patreon, PayPal, Venmo, My Amazon Wishlist
Every rover, no matter how advanced, makes decisions based on data. Distance sensors measure how far away an obstacle is. Encoders report how fast the wheels are turning. Batteries provide voltage readings that determine how long the rover can operate. To control a rover using Python, we must be able to store this variable data collected from the sensors, work with it, and use expressions to compute results from it.
This chapter introduces the three fundamental building blocks that make all Python programs possible:
Variables — how Python stores and names values for later use
Data Types — how Python understands and categorizes information
Expressions — how Python performs calculations and evaluations
These concepts form the foundation of every robotics program. Whether you are calculating how far a rover can move forward, deciding when to stop to avoid an obstacle, or simply collecting and reporting a sensor reading to an output device, like an LCD screen, console monitor, or some other display device, you are using expressions, data types, and variables.
By the end of this chapter, you will be able to write simple but meaningful Python programs that model real rover behavior, even before you begin controlling physical hardware.
Chapter Roadmap: In this chapter, you will learn how to:
Create and name variables correctly
Identify and use common Python data types
Write and evaluate Python expressions
Combine variables and expressions to model rover behavior
Write Python code relevant to rover sensors, movement values, and robot state
These foundational skills will prepare you for upcoming chapters, where you will control program flow, respond to sensor input, and begin writing complete rover control programs.
Python is a powerful language that is readable, expressive, and widely used in robotics for sensor interaction, motor control, and decision logic:
Read sensor values (e.g., distance, light, temperature)
Store those values in variables
Compute decisions (e.g., “stop”, “turn”, “slow down”)
Send commands to actuators (e.g., wheels, servos)
Before controlling movement, you must understand how Python stores, evaluates, and manipulates data. These concepts: variables, data types & expressions, are the foundations of all Python programs.
A Value is one of the basic pieces of data that a Python program can work with, such as a number or string. Every value in Python belongs to a Data Type — a category that tells Python what kind of value it is and how it behaves.
Python, like any other structured language has values in form of Variables, defined as Data Types and they are used to resolve Expressions.
Data Types represents the kind of value that tells what operations can be performed on a particular data.
Since everything is an object in Python programming, Data Types are actually classes and variables are instances (objects) of these classes.
Integer (int)
Whole numbers without decimals.
Example: 42, -7
Floating-point number (float)
Numbers with a decimal point.
Example: 3.14, 0.0
String (str)
Text enclosed in quotes.
Example: "Forward", 'STOP'
Data types are the classification or categorization of data items. Everything in python is an "object", and because of this, they need to be defined by a data type.
Numbers
Integers
Long Integers
Floats
Complex Numbers
Boolean Logic (True/False)
bool
(More On These Later)
Lists
Tuples
Sets
Dictionaries
Strings
File Objects
In Python 3 (modern Python)
There is NO separate long type. (Python 3 merged them)
int handles all whole numbers
int = unlimited precision integer
Small or extremely large — Python manages it automatically
In Python, an int represents any whole number, and Python automatically handles very large values, so there is no separate long type.
x = 10
y = 999999999999999999999
Both are:
type(x) == type(y) # True
A float is a data type used to store numbers with decimal points. Floats are commonly used in robotics to represent:
Sensor distances
Voltages
Speeds
Time measurements
Floats allow more precise measurements than integers, but they can include small rounding errors, so they should be used carefully in comparisons. Use float whenever measurements are not whole numbers.
Floats allow more precise measurements than integers
But they can include more significant digits and can include small rounding errors
They should be used carefully in comparisons. <-- More on this "rounding" in a later LAB
Use float whenever measurements are not whole numbers.
Floats may also be in scientific notation, with E or e indicating the power of 10. When a number is really really big or very very small, it is more readable to represent it as an exponent.
2.5e2 = 2.5 x 102 = 250
Big Numbers:
6.02214076e23 is Avogadro’s number, and it is very very big. You would have to agree that 6.0221407623 or 6.02214076e23 is more readable than 6.0221407600000000000000000000000
4.7e6 rather than 47000000, which might be a resistor value of 4.7MΩ
10e3 rather than 10000, which might be a resistor value of 10KΩ
7e9 = Population of the world is around 7 billion written out as 7000000000
1.08e9 = Approximate speed of light is 1080 million km per hour or 1080000000 km per hour
3.99e13 = Distance from the sun to the nearest star (Proxima Centauri) is 39900000000000 km
Small Numbers:
These exponents can also be negative 2.2e-9 = 2.2 x 10-9 = .0000000022 or 2.2 pF
You might also see some small number represented in scientific or engineering notation like: capacitor
2.2e-9 rather than .0000000022, which might be a capacitor value of 2.2 x 10-9 = 2.2 pF
2.4e-3 = Diameter of a grain of sand is 24 ten-thousandths inch or .0024 inch
7.53e-10 = Mass of a dust particle is 0.000000000753 kg
9.1093822e-31 = Mass of an electron is 0.00000000000000000000000000000091093822 kg
4.0e-7 = Length of the shortest wavelength of visible light (violet) is 0.0000004 meters
Floats allow more precise measurements than integers
But they can include more significant digits and can include small rounding errors <-- More on this later
They should be used carefully in comparisons
Use float whenever measurements are not whole numbers
Float
>>> pi = 3.14159265359
>>> print(pi)
??? <--What got printed?
>>> type(pi)
??? <--What got printed?
Dividing Numbers Int to Float
>>> x = 10
>>> y= 2
>>> z = x / y
>>> print(z)
??? <--What got printed?
>>> y= 3
>>> z = x / y
>>> print(z)
??? <--What got printed?
Forcing An Integer Divide With //
>>> z=x//y
>>> print(z)
??? <--What got printed?
>>> type(z)
??? <--What got printed?
Big Numbers:
>>> x = 2.5e3
>>> print(x)
??? <--What got printed?
>>> x = 2.5e15
>>> print(x)
??? <--What got printed?
>>> x = 2.5e16
>>> print(x)
??? <--What got printed?
Small Number:
>>> x = 2.2e-3
>>> print(x)
??? <--What got printed?
>>> x = 2.2e-4
>>> print(x)
??? <--What got printed?
>>> x = 2.2e-9
>>> print(x)
??? <--What got printed?
>>>
In mathematics, a complex number is a number that can be expressed in the form a + bi, where a and b are real numbers, and i is a symbol called the imaginary unit, and satisfying the equation i2 = -1.
Because no "real" number satisfies this equation, i was called an imaginary number by René Descartes.
For the complex number a + bi,
a is called the real part
b is called the imaginary part.
Typically an imaginary number is used to denote a point location on a Cartesian plane
Where you have an "x" value and a "y" value.
The "x" value is the real part of this number and the "y" is the imaginary.
Both numbers are "real" numbers and can be integer or float values.
If we wanted to plot the point x= 3 and y = 7, we could represent this as a complex number:
my_graf_number = (3+7j)
>>> x = 3+7j
>>> print(x)
>>> r = x.real
>>> i = x.imag
>>> print(r, ",",i)
Why use complex numbers to hold x , y points?
Put lidar_point = (3 + 4j) in parenthesis, even though you don't have to, just to make it more readable and intentional.
lidar_point = (3 + 4j)
# Convert complex to cartesian
x = lidar_point.real
y = lidar_point.imag
print(lidar_point)
print("x =", x)
print("y =", y)
y
↑
5 | . . . . . .
4 | . . . x . .
3 | . . . . . .
2 | . . . . . .
1 | . . . . . .
0 | . . . . . .
R 0 1 2 3 4 5 → x
Storing a x, y integers as a complex number x = 5, y = 3
x = 5
y = 3
lidar_point = complex(x,y)
print(lidar_point)
print(type(lidar_point))
y
↑
5 | . . . . . .
4 | . . . . . .
3 | . . . . . x
2 | . . . . . .
1 | . . . . . .
0 | . . . . . .
R 0 1 2 3 4 5 → x
A string (str) in Python is a sequence of characters enclosed in single quotes ('...') or double quotes ("...").
Strings are used to store textual information, such as:
Rover status messages: "MOVING", "STOP"
Sensor labels: "FrontSensor"
Logs or debug messages: "Battery low!"
status = "MOVING"
sensor_label = "Front Sensor"
>>> my_snake_sound_variable = 'Hissssssss'
>>> print(my_snake_sound_variable)
??? <--What got printed?
>>> print(type(my_snake_sound_variable))
??? <--What got printed?
my_snake_sound_variable is a variable object, and the value inside the object is a string "Hisssssss"
my_snake_sound_variable is a type <class 'str'>
>>> my_char_variable = '25'
>>> print(my_char_variable)
??? <--What got printed?
>>> print(type(my_char_variable))
??? <--What got printed?
>>>
my_char_variable is a variable object, and the value inside the object is a string "25"
my_char_variable is a type <class 'str'>
Was this what you expected? When you put quotes around something, Python tends to think this is a string...
>>> x = 42
>>> y = 20
>>> z = x + y
>>> print(z)
??? <--What got printed?
>>> x = 42
>>> y = "20"
>>> z = x + y
>>> print(z)
??? <--What got printed?
Strings in Python behave like a list of characters:
Each character in the string has a position (index)
You can access, slice, or iterate over a string just like a list
greet ="Hello World"
print(greet)
# Access individual characters
print(greet[0]) # 'H'
print(greet[6]) # 'W'
# Slicing
print(greet[1:5]) # 'ello'
Just like a list, string indexing starts at 0, and negative indices count from the end (-1 is the last character).
Immutable? What does that mean?
You cannot change a character in place:
greet = "Hello World"
greet[0] = "M" # This will raise an error
Instead, you create a new string:
greet = "M" + greet[1:]
print(greet)
A Boolean variable is a type of variable that can only hold two possible values: True or False
Booleans are commonly used to represent conditions, states, or flags in a program
A robot might need to know:
If an obstacle is detected
If a motor is running
If a battery is low
Using a Boolean variable makes it easy to store, check, and control these conditions
Boolean - Comparison Operators
Equal to (==)
Not equal to (!=)
Greater than (>)
Less than (<)
Greater than or equal to (>=)
Less than or equal to (<=)
Note: We are using the "==" operator rather than the "=", because we want a comparison evaluation not an assignment operation.
>>> 5 == (3 + 2)
??? <--What got printed?
>>> 1 == 2
??? <--What got printed?
>>> "bob" == "Bob"
??? <--What got printed?
>>> x = 9
>>> 6 < x
??? <--What got printed?
You can assign a variable with the Boolean value of True or False, and then use these in Loops and Flow Control operations. We will see examples of that in later lessons.
>>> my_bool_var = True
>>> print(my_bool_var)
??? <--What got printed?
>>> my_bool_var = False
>>> print(my_bool_var)
??? <--What got printed?
Cntl-a, then paste this code:
# Boolean flag to track if obstacle is detected
obstacle_detected = False
# Sensor reading (distance in cm)
distance_front = 15
# Check if an obstacle is close
if distance_front < 20:
obstacle_detected = True
# Print the status
print("Obstacle detected?", obstacle_detected)
Re run with distance_front = 22
Evaluating Math and Order of Operations
Python allows you to perform a variety of mathematical operations on numbers using arithmetic operators. These are essential when working with sensor readings, distances, speeds, or battery levels in robotics.
Practical Tip for Robotics
Use integer division (//) for counts, steps, or discrete units.
Use float division (/) for distances, voltages, or precise measurements.
Combine multiple operators carefully, and use parentheses to make your logic explicit.
# Rover wheel parameters
wheel_speed = 3 # speed in cm/sec
travel_time = 5 # time in seconds
# Calculate distance using multiplication
distance = wheel_speed * travel_time
print("Distance traveled:", distance, "cm")
??? <--What got printed?
# Battery voltage readings
battery_start = 12.63
battery_current = 11.24
# Subtract to find voltage drop
battery_drop = battery_start - battery_current
print("Battery voltage drop:", battery_drop, "V")
When more than one operator appears in an expression, the order of evaluation depends on the rules of precedence. For mathematical operators, Python follows mathematical convention
Python follows PEMDAS order of operations:
Parentheses → Exponents → Multiplication/Division → Addition/Subtraction
Using parentheses ensures calculations are evaluated correctly
>>> x = 2*3-1
>>> print(x)
??? <--What got printed?
>>> x = 6+4/2
>>> print(x)
??? <--What got printed?
>>> x = 2*(3-1)
>>> print(x)
??? <--What got printed?
>>> x = (6+4)/2
>>> print(x)
??? <--What got printed?
Simultaneous Assignment
Python also allows chained assignment, which makes it possible to assign the same value to several variables simultaneously:
>>> x = y = someVar = 42
>>> print(x, y, someVar)
??? <--What got printed?
You explored the most common data types, Variables & Expresions
Integers (int) for whole numbers
Floating-point numbers (float) for measurements with decimals
Strings (str) for text and messages
Booleans (bool) for true/false logic and control flags
Dig Deeper: Review These Chapters/Resources
As a Teacher, I have reservations about students immediately asking ChatGPT as the first thought when trying to code something. I can see how these code LLM's are great for experienced Python developers, but Students without much experience will not understand code, or even know what they should expect... and that is the Key to being successful "Learning" while also getting help from LLM's.
While using ChatGPT, I constantly see flagrant errors. Errors that many time cause me to waste time, or go down a "rabbit hole" just to understand what happened and if what the LLM said is valid. An inexperienced code would miss these errors, waste a huge amount of time, or worse, deploy code whit ah really bad bug or implementation.
I have seen ChatGPT import old, obsolete or unsupported Libraries
I have seen code where If statements are clearly inverted, and the logic flow is clearly wrong.
Prompt to help drive ChatGPT and Claude and other LLM's to work harder at providing well thought out code, which it has verified and followed rules.
Prompt:
"
Generate Python learning reference material, code example, Quiz material for [specific robotics/embedded/educational task].
Also, if provided, use any wen links as focus of material generated:
[web links]
Follow these strict rules to ensure high-quality, maintainable, and educational code:
1) Library Selection:
Use only the latest, actively maintained Python libraries.
Do not use and avoid deprecated, obsolete, or unmaintained libraries.
Typically Lab examples should use Python code that is targeted to run on a Raspberry Pi
Justify every third-party library used: Why it is needed. What specific features are being used. Why the standard library alone is insufficient
Justify every library selection in comments or documentation. Explain why it is chosen for robotics or embedded applications.
2) Imports:
Every import must have a purpose; document what features are used and where it is used in the code.
Do not include unused, "future-Use", or convenience or unnecessary imports.
Never introduce a dependency unless strictly required and fully explained.
If a dependency is optional, provide a version without it.
3) Variables and Functions:
Every variable and function must have a clear role.
Use meaningful names reflecting robotics or embedded context (e.g., motor_speed, distance_sensor).
Include comments explaining why variables and functions exist.
4) Code Structure & Quality:
Follow PEP8 for readability.
Include docstrings for all functions/classes.
Write modular code suitable for educational purposes or embedded deployment. Examples should be Robotics or Autonomous Rover focused
The code must execute without modification in a standard Python environment.
State the required Python version (e.g., Python 3.11+).
Do not assume external files, hardware, or environment variables unless explicitly stated.
If hardware or simulated data is involved, clearly mock or emulate it.
Handle Common Errors Gracefully, Validate inputs where appropriate.
Avoid silent failures.
Clearly explain what errors may occur and why.
5) Requested Code Topics & Accompanying Lab Examples:
Target and tailor any code examples to Robotics and Autonomous Rover.
Examples should be targeted at Students learning Python, and have extensive documentation and tips and hints in the form of code comments.
No “Magic” Code. Avoid unexplained syntax, shortcuts, or idioms. If a construct might confuse students or beginners, explain it inline or in comments.
Explain why variables, functions, and data structures are named as they are.
Explain why the chosen approach is appropriate for the problem.
Comments should be intentional & explain why, not restate what the code already says.
Avoid redundant comments.
Code should be readable by someone learning Python.
Avoid premature abstraction.
Prefer step-by-step logic over compressed patterns.
6) Final-Pass Dependency & Logic Check:
Before presenting the final answer, perform a silent self-review against these rules and correct any violations.
Mentally execute the code to ensure:
Every import is used
Every variable is initialized and used appropriately
All functions have a purpose
No dead or redundant code exists
Document the final dependencies and their necessity.
7) Output & Visualization:
If visualizing data (sensors, lidar, plots), ensure the method works in a standard Python environment.
Prefer console-safe or simple plotting libraries suitable for educational and embedded demonstrations.
Provide the complete, ready-to-run Python example, fully documented, suitable for robotics/embedded/educational use.
"
This is a text book you will be using in class. Many of the lectures and Lessons will contain material from this book. You will be assigned reading and coding assignments pulled from this resource.
On its own, this book won’t turn you into a professional software developer any more than a few guitar lessons will turn you into a rock star. But if you’re an office worker, administrator, academic, or anyone else who uses a computer for work or fun, you will learn the basics of programming so that you can automate simple tasks
This is an open sources Python Text book by Allen B. Downey, and you will be using it in class. Some of the lectures and Lessons will contain material from this book. You will be assigned reading and coding assignments pulled from this resource.
The Author, Allen, had some specific goals when he wrote this book:
Keep it short. It is better for students to read 10 pages than not read 50 pages.
Be careful with vocabulary. I tried to minimize jargon and define each term at first use.
Build gradually. To avoid trap doors, I took the most difficult topics and split them into a series of small steps.
Focus on programming, not the programming language. I included the minimum useful subset of Python and left out the rest.
PDF Version - Think Python: How to Think Like a Computer Scientist (PDF)
HTML Version - Think Python: How to Think Like a Computer Scientist (HTML)
This is an open sources Python College class taught by Dr Severance from the University of Michigan, and you will be using it in class. Some of the lectures and Lessons will contain material from this class. You will be assigned reading and coding assignments pulled from this resource.
Python 4 Every one - Open Source University level Python class - Dr Charles Severance
Introduction by Dr Severance - 📽️ 🎧
Class Lessons & Videos - https://www.py4e.com/lessons - 📽️ 🎧 📰 📖 📝🛠️
Text Book - Python 4 Everybody (HTML) - 📝🛠️
Browser-based Python Shell - https://www.python.org/shell/ - one command at a time
Browser-based Python interpreter - replit.com - 🛠️ LAB Activity - Signup for free account (They have monetized this to be un-useful)
Browser-based Python interpreter - trinket.io - 🛠️ LAB Activity - Signup for free account (Can't save projects)
Python Tutor - Interactive Code Visualization site - See code execute, see memory allocations, etc
Python Interpreter - Online GDB
W3School Python Tutorials - Comprehensive Python Tutorial and Reference Examples with options to try out code
Python Tutorial & Reference Guide - From Tutorials Point - Good Easy Learning - Reference & Examples
Python 2.7 On-Line Python Interpreter - Tutorials Point
Python Reference from Valley Of Code - Python Online Reference, that is really good.
CodeCademy - Python 3 - You can sign up. They want you to get a 7-day trial, but then they revert to a free option. Don't enter any Credit Card info, just register for the free options.
Python Code In An Hour - This is an Hour-long Webinar (if the link is broken check here on YouTube for a crappy recording)
(NEW) - exercism.org - Colding exercises. Solve coding exercises and get mentored to gain true fluency in your chosen programming languages. Exercism is open-source and not-for-profit. Not just Python, but lots of languages.
Ziro Studio - Tutorial and coding in a fun 3D world. It has examples of some complex code, which you can modify and "see" what happens.
CodingBat Python Exercises - Challenges you can practice coding. Check your code and even check for an implementation.
8.1.0.1.1 - Chapter 1 - Introduction to Expressions, Data Types, and Variables - 📰 Slide Presentation
8.1.0.1.1 - Chapter 1 - Introduction to Expressions, Data Types, and Variables - 📖 Lesson Tutorial
Mechatronics - <topic> - 📽️ Video / 🎧 Video/Podcast (TBD)
Mechatronics - <topic> - LAB #1 - 🛠️ LAB Activity (Coming Soon... Really, I'm working on it...)
Mechatronics - <topic> - LAB #2 - 🛠️ LAB Activity (Coming Soon... Really, I'm working on it...)
If you are a teacher and want to connect and teach this Lesson or Module, discuss how I teach it, give me feedback, please contact me at TopClown@STEAMClown.org
To access this Lesson Plan and the Teacher collaboration area, you will have needed to connect with me so I can Share the content with you. Please go to the Teachers & Partner Page, check out my Licensing and fill out my Collaboration and Curriculum Request Form. I'll review and then grant you access to the requested areas and lesson plans if they exist.
If you have questions or feedback on how I can make a presentation, lesson, lab better please give use my Feedback Form.
I’ll work on getting these in, but it’s the last thing I want to work on :-) When I have them updated, I’ll move to the top of the Lesson Plan.
NGSS: <list standard numbers>
California CTE Standards: <list standard numbers>
Related Instructional Objectives (SWBAT): <list standard numbers>
CCSS: nnn, RSIT: nnn, RLST: nnn, WS: nnn, WHSST: nnn, A-CED: nnn, ETS: nnn <list standard numbers>
Main Standard:
Priority standards:
National Standards:
Text Book - Automate the Boring Stuff with Python, 2nd Edition: Practical Programming for Total Beginners
Text Book - Think Python: How to Think Like a Computer Scientist (HTML) 3rd Edition
Reference Python Class - Python 4 Everyone
Images:
add links to w3schools for any text like float()
Add labs from the presentation
8.3.C.N - Chapter N - Python - Topic - Sub Topic - 📰 Slide Presentation
8.3.C.N - Chapter N - Python - Topic - Sub Topic - 📖 Lesson Tutorial
Mechatronics - <topic> - 📽️ Video / 🎧 Video/Podcast (TBD)
Mechatronics - <topic> - LAB #1 - 🛠️ LAB Activity (Coming Soon... Really, I'm working on it...)
Mechatronics - <topic> - LAB #2 - 🛠️ LAB Activity (Coming Soon... Really, I'm working on it...)