-
Notifications
You must be signed in to change notification settings - Fork 0
CircuitPython Snippets
The following guide walks through a handful of features of the language of Python. If you are not yet familiar with Python (the programming language upon which CircuitPython is heavily based), this is the guide for you! I would encourage you to try running the snippets here to familiarize yourself with the language, especially if anything seems confusing.
In programming, variables are used to store and manipulate data. A variable is like a container that holds a value. You can give a variable a name, and assign a value to it using the assignment operator (=). Once you've assigned a value to a variable, you can refer to that value by using the variable name.
Here's an example of how you might use variables in Python code:
# Declare two variables and assign values to them
x = 5
y = 3
# Use the variables in an arithmetic operation
result = x + y
# Print the result
print(result) # Output: 8In this example, we declare two variables (x and y) and assign values to them. We then use those variables in an arithmetic operation to calculate a new value (result). Finally, we print the value of result to the console using the print() function.
The print() statement is a built-in function in Python that allows you to display output on the screen of your computer. You can view this output or test it using the serial terminal. You can use the print() statement to display strings, numbers, and other types of data.
Here's an example of how you might use the print() statement to display a message on the screen:
print("Hello, world!")In this example, we use the print() statement to display the message "Hello, world!" on the screen. The message is enclosed in quotation marks to indicate that it is a string.
You can also use the print() statement to display the values of variables. For example:
x = 42
print("The value of x is:", x)In this example, we declare a variable x with the value 42, and then use the print() statement to display a message along with the value of x. The message and the value of x are separated by a comma, which tells Python to print them both on the same line.
You can use the print() statement to display multiple values by separating them with commas. For example:
x = 3
y = 4
print("The values of x and y are:", x, y)In this example, we declare two variables x and y, and then use the print() statement to display a message along with the values of x and y.
The print() statement is a fundamental tool for debugging and testing your code. By using the print() statement, you can display the values of variables, the results of calculations, and other types of data, which can help you to understand how your code is working and identify any errors or bugs.
In Python, mathematical operators are used to perform arithmetic operations on numeric values. Here are some of the commonly used mathematical operators in Python:
Addition (+): Adds two values together
Subtraction (-): Subtracts one value from another
Multiplication (*): Multiplies two values together
Division (/): Divides one value by another
Modulo (%): Divides one value by another and returns the remainder
Exponentiation (**): Raises one value to the power of another
Here's an example of how you might use some of these operators in Python code:
x = 5
y = 3
# Addition
result = x + y
print(result) # Output: 8
# Multiplication
result = x * y
print(result) # Output: 15
# Division
result = x / y
print(result) # Output: 1.6666666666666667
# Modulo
result = x % y
print(result) # Output: 2
# Exponentiation
result = x ** y
print(result) # Output: 125In Python, import statements are used to bring in functionality from other modules or libraries. For example, if you want to use the math module to perform mathematical operations, you can import it like this:
import mathAfter importing the math module, you can use its functions in your code. For example, you can use the sqrt function to compute the square root of a number like this:
import math
x = 16
y = math.sqrt(x)
print(y) # Output: 4.0In Python, a boolean expression is an expression that evaluates to either True or False. Boolean expressions are often used to make decisions in programs.
Here are some common boolean operators in Python:
== (equals)
!= (not equals)
< (less than)
> (greater than)
<= (less than or equal to)
>= (greater than or equal to)
With boolean expressions, you can also use boolean operators, like and, or, and not.
Here is an example of printing boolean expressions to see their values:
print(True) # Prints `True`
print(False) # False
print(2 > 3) # False
# Using some boolean operators:
print(not True) # False
print(not False) # True
print(not 2 > 3) # True
print(2 > 3 or 1 > 0) # True
print(2 > 3 and 1 > 0) # FalseHere's an example of using a boolean expression in a program:
x = 5
y = 10
if x < y:
print("x is less than y")
else:
print("x is greater than or equal to y")A while loop is used to repeat a block of code as long as a certain condition is true.
To create a while loop, use the while statement, followed by a boolean expression and a :.
The code that you want to be looped should follow directly after, indented. As soon as something is not indented, it is not considered part of the while loop and thus will not execute until the while loop exits.
The simplest type of while loop is the forever loop or the "while True" loop:
while True:
print("I'm gonna print this forever and ever")
# This will never get to this point in the program, since
# the loop will never exit. It will loop forever.
print("This statement will never print")Alternatively, a while False loop will never execute, because the boolean expression of False is, by definition, False.
while False:
print("You will never see this")
print("Hello!")Here is an example of a more complicated while loop where we use a variable:
x = 0
while x < 10:
print(x)
x += 1This program will print the numbers 0 to 9, because the condition x < 10 is true as long as x is less than 10.
A for loop is used to iterate over a sequence of elements. Here's an example of a for loop:
fruits = ["apple", "banana", "cherry"]
for fruit in fruits:
print(fruit)This program will print each element in the fruits list: "apple", "banana", and "cherry".
Another way to use a for loop is with a range of numbers. The range() function generates a sequence of numbers, which you can use to iterate over a range of values. Here's an example of using a for loop with a range of numbers:
for i in range(5):
print(i)This program will print the numbers 0 to 4.
You can also specify a starting value for the range, like this:
for i in range(2, 5):
print(i)This program will print the numbers 2 to 4.
A function is a reusable block of code that performs a specific task. Functions can take input arguments and return output values. Here's an example of a function:
def add_numbers(x, y):
result = x + y
return result
sum = add_numbers(3, 4)
print(sum) # Output: 7In this example, the add_numbers function takes two arguments (x and y) and returns their sum. The sum variable is assigned the value returned by the function when called with arguments 3 and 4.
Python f-strings (short for formatted string literals) provide a concise and convenient way to embed expressions inside string literals. An f-string is created by prefixing a string with the letter f or F, and then embedding expressions inside curly braces {} within the string. When the string is evaluated, the expressions inside the curly braces are replaced with their corresponding values.
Here's an example of how you might use an f-string in Python code:
name = "Alice"
age = 25
height = 1.65
# Create an f-string that includes variables
greeting = f"My name is {name}, and I'm {age} years old. My height is {height:.2f} meters."
print(greeting) # Output: "My name is Alice, and I'm 25 years old. My height is 1.65 meters."In this example, we create an f-string called greeting that includes variables for name, age, and height. We use curly braces {} to embed the variables in the string, and we also use a format specifier :.2f to format the height variable as a float with two decimal places.
Note that in Python there are two main ways of storing numbers in a variable- ints and floats. An int (short for integer) is just a number without a decimal. A float can have a decimal in it. Either can be positive, negative, or zero.
F-strings are a powerful tool for creating formatted strings in Python, and they are especially useful when you need to include variables or expressions in your strings. They can also make your code easier to read and maintain by reducing the amount of concatenation and formatting code that you need to write.
Copyright 2022-2023 Heather Brayer, Joseph R. Freeston, & Lucas Tousignant