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
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.
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...)
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
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...)
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...)
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 a Python code example for [specific robotics/embedded/educational task].
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:
Reference Text Book - Links
Reference Sites -
Key: 📰 Slides / Audio 🎧 / 📽️▶️ Video/YouTube / 🎧▶️📽️ Audio/Video / ✨ Resources / 🖼️ Tutorial / 📖 Reading Activity / 📝 Writing Activity / 📖 📝 Reading/Writing / 📟 Coding / 🛠️ LAB Activity / 🚀 Quiz / 🔎 Review / ✔️ Mastery Check / ✍️ Sign Up /🍕 Extra Credit / 🕸️ Web Links / 👩🏽🎓🧑🏽🎓🧑🏿🎓👩🏫 Class / 🏵️📜📃 Certificate / 🗂️ 📈 Collecting Survey Data
/🧟 Review / 🦾 Practice / 🆙Level Up /
🎚️🦑📤🎯 🚧
- 🦑 Special Project -
Assignment Type: ⚓ Establishing (Minimum Standard) / ⛏️ Developing (Digging Deeper) / 💎 Aspiring (Putting It Together)
This is an ⚓ Establishing Assignment (Minimum Standard) - "Everyone Do" Assignment
This is an ⛏️ Developing (Digging Deeper) - "Everyone Should Do, To Stretch" Assignment
This is an 💎 Aspiring (Putting It Together) - "When you have done the ⚓ Establishing and⛏️ Developing" Assignment
🚀 Formative Quiz - 🔎 Review
🚀 Quiz -🔀 Mastery Path
🚀 Summative Quiz -✔️ Skills Mastery Check
Quiz - verify that they are all listed as a "Formative", "Mastery Path", or "Summative"
🚀 Formative Quiz - These are quizzes that the students can take a few times. I have them either set for unlimited times, or 3-5 times, where the final score is their average. The idea is that these Formative Quizzes are designed for students to learn and master a skill. while I want them to ger 100%, and when it's set to unlimited tries, the student should get 100% eventually. When the quiz is set to 3-5 tries with an average, then they should be prepared and should take the quiz seriously. I set the quiz to not show the right answer, but I do let them see their wrong answer. I also put the explanation of the right and wrong answer in the right and wrong answer prompt for each question. That way they can see why they got the answer wrong and learn from that experience.
8.1.0.3.2.4 - Python - Ch 3 - Functions - Quiz #2 -Built-In Functions - 🚀 Formative Quiz
🚀 Quiz -🔀 Mastery Path - These Mastery path quizzes are to be presented after the student has had a chance to do some labs and some Formative quizzes. The goal is to let students have 2 chances to take this quiz, and take the average of the 2 attempts. Based on the average, they will be presented with a Canvas Mastery Path, where they will have an option for take additional quiz and assignments to help with remediation. This will get them ready to take the Summative Quizzes.
8.1.0.3.3.1 - Python - Ch 3 - Functions - Mastery Quiz #1 - 🚀 Quiz -🔀 Mastery Path
🚀 Summative Quiz -✔️ Skills Mastery Check - These Mastery path quizzes are to be presented after the student has had a chance to do some labs and some Formative quizzes. The goal is to let students have 2 chances to take this quiz, and take the average of the 2 attempts. That will be their final module/subject topic grade.
8.1.0.3.3.1 - Python - Ch 3 - Functions - Skills Mastery Check Quiz #1 - 🚀 Summative Quiz -✔️ Skills Mastery Check
Raspberry Pi Resources on Kerry Bruce's Google drive
Cheat sheet - https://programmingwithmosh.com/python/python-3-cheat-sheet/
good tutorial series - Introduction and Parts - Raspberry Pi and Python tutorials p.1 - maybe assign this as home work when we take our Raspberry Pi's home
Element 14 - Getting Started With The Raspberry Pi 3
How To Log Into Python Learning Sites
TryPython - Fun Interactive Class (you have to pay now)
CodeCademy - Learn Python
Python Introduction - Some python and some cygwin command line
Lesson 1 - Running The Python Interpreter
Lesson 2 - Getting Ready to Write a Program
Lesson 3 - Writing and Running a Program
jim.the.STEAM.Clown's Github - https://github.com/jimTheSTEAMClown/Python-Code
Adafruit Raspberry PI & Python Project Tutorials <-- lots of Python specific projects
ideone - https://ideone.com/
codepad - http://codepad.org/
The Python Tutorial - Good place to Start
Official Pi Project Book - magiPi link to Raspberry Pi projects
Full Stack Python - Some useful Full Stack Videos too...
Introduction Slide Deck for Python - Mr Ganesh Bhosale
Random Resource Links - Stuff to review and sort...
This is where my Raspberry Pi Resource will go... they will show up in about 2 weeks (Jan 7 2019)... in the mean time you can see my Python Resource page from last year 2017-2018 <-- this will go away as soon as I have made this organizational update