MicroPython For micro:bit (Part 2: DataTypes & Numbers)

MicroPython For micro:bit (Part 2: DataTypes & Numbers)

For a complete table of contents of all the lessons please click below as it will give you a brief of each lesson in addition to the topics it will cover. https://github.com/mytechnotalent/micropython_for_microbit

Today we are going to discuss datatypes and numbers as it relates to MicroPython on our micro:bit.

By the end of the lesson we will have accomplished the following.

* Written a 0005_calculator_repl.py app which will output add, subtract, 
multiply and divide two numbers in the REPL or web terminal or console.

* Written a 0006_square_footage_repl app which will take a width and height in
feet from the repl and print and display the square footage in our micro:bit display LED matrix.

* Written a 0007_final_score_talk_repl app which will calculate a final 
score of a player and indicate the result of a hardcoded boolean.

We will focus on 4 primary primitive datatypes that are built-in to MicroPython.

* string
* integer
* float
* boolean

string

We are familiar with the concept of the string from last lesson. A string is nothing more than a string of characters.

Let's open up our Python Web Editor (full instructions were in Part 1 if you need to double-check) and type the following.

name = 'Kevin'
print(name)


Kevin

We see that our name variable properly prints the word 'Kevin'.

Let's demonstrate that a string really is a string of characters. Each letter or character in a string is referred to as an element. Elements in MicroPython are what we refer to as zero-indexed meaning that the first element starts at 0 not 1.

Let's try an example:

name = 'Kevin'
print(name[0])
print(name[1])
print(name[2])
print(name[3])
print(name[4])

print(name[-1])

print(name[1:4])

print(name[1:])


K
e
v
i
n

n

evi

evin

We see that we do have 5 characters starting at 0 and ending with 4 so the first element is 0 and the fifth element is 4. We can also see that the -1 allows us to get the last element. In addition we can see 1:4 prints the 2nd, 3rd and 4th element (1, 2, 3) but not the 5th element. We see that if we do 1: that will print the 2nd element and the remaining elements.

If we try print an element that is out of bounds we will get an error.

name = 'Kevin'
print(name[5])


IndexError: str index out of range

A string is what we refer to as immutable as you can't change individual letters or characters in a string however you can change the entire string to something else if it is a variable.

Let's look at an example to illustrate.

# CAN'T DO
name = 'Kevin'
name[0] = 'L'

TypeError: 'str' object doesn't support item assignment

# CAN DO
name = 'Kevin'
print(name)
name = 'Levin'
print(name)


Kevin
Levin

We can see that we in fact can't change an individual element in a string but we can change the string to be something else completely by reassigning the variable name.

When you add strings together you concatenate them rather than add them. Let's see what happens when we add two strings that are numbers.

print('1' + '2')


12

We can see we get the string '12' which are not numbers as they are strings concatenated together.

integer

An integer or int is a whole number without decimal places.

print(1 + 2)


3

Here we see something that we would naturally expect. When we add two integers together we get another integer as shown above.

float

A float is a number with fractions or decimals. One thing to remember about a float is that if you add, multiply, subtract or divide an integer with a float the result will ALWAYS be a float.

print(10.2 + 2)


12.2

boolean

A boolean has only two values which are either True or False. Make sure you keep note that you must use a capital letter at the beginning of each word.

A True value means anything that is not 0 or None and a False value is None or 0.

The None keyword is used to define a null value, or no value at all. None is not the same as 0, False, or an empty string.

None is a datatype of its own (NoneType) and only None can be None.

is_happy = True
print(is_happy)

is_angry = False
print(is_angry)

score = None
print(score)


True
False
None

A boolean can be used in so many powerful way such as setting an initial condition in an app or changing conditions based on other conditions, etc.

Type Checking & Type Conversion

We can check the datatype very easily by doing the following.

my_string = 'Kevin'
print(type(my_string))

my_int = 42
print(type(my_int))

my_float = 77.7
print(type(my_float))

my_boolean = True
print(type(my_boolean))


<class 'str'>
<class 'int'>
<class 'float'>
<class 'bool'>

You can also convert datatypes by what we refer to as casting or changing one datatype to another.

my_int = 42
print(type(my_int))


<class 'int'>
<class 'str'>

Math Operations In MicroPython

In MicroPython we have an order of operations that are as follows.

Parentheses ()
Exponents **
Multiplication *
Division /
Addition +
Subtraction -

If you look at them together you can see we have PEMDAS. This is a way we can remember.

In addition multiplication and division are of equal weight and the calculation which is left-most will be prioritized. This is the same for addition and subtraction.

print(5 * (9 + 5) / 3 - 3)

# First: (9 + 5) = 14
# Second: 5 * 14 = 70
# Third: 70 / 3 = 23.33334
# Fourth: 23.33334 - 3 = 20.33334


20.33334

APP 1

Let's create our first app for the day and call it 0005_calculator_repl.py.

first_number = int(input('Enter First Number: '))
second_number = int(input('Enter Second Number: '))

my_addition = first_number + second_number
my_subtraction = first_number - second_number
my_multiplication = first_number * second_number
my_division = first_number / second_number

print('Addition = {0}'.format(my_addition))
print('Subtraction = {0}'.format(my_subtraction))
print('Multiplication = {0}'.format(my_multiplication))
print('Division = {0}'.format(my_division))
print(type(my_division))


Enter First Number: 3
Enter Second Number: 3
Addition = 6
Subtraction = 0
Multiplication = 9
Division = 1.0
<class 'float'>

Notice when we use division in MicroPython that the result is a float. This will always be the case.

APP 2

Let's create our second app for the day and call it 0006_square_footage_repl.py:

from microbit import display

length = float(input('Enter length: '))
width = float(input('Enter width: '))

square_footage = length * width

print('Your room size is {0} square feet.'.format(square_footage))
display.scroll('Your room size is {0} square feet.'.format(square_footage))


Enter length: 4
Enter width: 5
Your room size is 20.0 square feet.

APP 3

Let's create our third app for the day and call it 0007_final_score_talk_repl.py:

from microbit import display, Image
from speech import say

SPEED = 95

player_score = int(input('Enter Player Score: '))
player_score_bonus = int(input('Enter Player Score Bonus: '))
player_has_golden_ticket = True

player_final_score = player_score + player_score_bonus

display.show(Image.SURPRISED)
print('Player final score is {0} and has golden ticket is {1}.'.format(player_final_score, player_has_golden_ticket))
say('Player final score is {0} and has golden ticket is {1}.'.format(player_final_score, player_has_golden_ticket))
display.show(Image.HAPPY)


Enter Player Score: 4
Enter Player Score Bonus: 5
Player final score is 9 and has golden ticket is True.

Project 2 - Create a Talking Mad Libs app 

Today we are going to create a talking mad libs app and call it p_0002_talking_madlibs.py:

Start out by thinking about the prior examples from today and spend an hour or two making a logical strategy based on what you have learned.

The app will first set the SPEED of the speech module. It will then get a noun from the user and then get a verb from the user and then finally create a madlib. Print this out and have the speech module talk out the result.

Give it your best shot and really spend some time on this so these concepts become stronger with you which will help you become a better MicroPython Developer in the future.

The real learning takes place here in the projects. This is where you can look back at what you learned and try to build something brand-new all on your own.

This is the hardest and more rewarding part of programming so do not be intimidated and give it your best!

If you have spent a few hours and are stuck you can find the solution here to help you review a solution. Look for the Part_2_DataTypes_+_Numbers folder and click on p_0002_talking_madlibs.py in GitHub.

I really admire you as you have stuck it out and made it to the end of your second step in the MicroPython Journey! Great job!

In our next lesson we will learn about MicroPython conditional logic!

要查看或添加评论,请登录

Kevin Thomas的更多文章

社区洞察