Python Code Explanation

Ask questions about projects relating to: computer science or pure mathematics (such as probability, statistics, geometry, etc...).

Moderators: kgudger, bfinio, Moderators

Locked
DharshanT
Posts: 1
Joined: Thu Feb 09, 2017 2:20 pm
Occupation: Student

Python Code Explanation

Post by DharshanT »

Hello Sir/Madam

I have chosen the "Sounds Like RFID: Using a Radio Frequency Identification (RFID) Reader to Make Musical Instruments" project this year, but I am confused on one area of the Python code.

Please explain what the following code means line by line.

Thank you


# This is a short program that reads data coming from the RFID reader, one
# character at a time. The data coming in is 10 chararcters of useful information
# followed by 2 characters that indicate the end of the tag. It takes each incoming
# character and decides if it's a character a human can read or if it's one of the special
# end-of-tag characters. When it thinks it's done with the tag, it calls the 'handle_data()'
# progam we defined just above.
def read_from_port(ser):
# Let's start with an empty storage area for the incoming data
new_data = ""
while True:
# Read in one character
reading = ser.read(1)
# If we got one, the 'length' will be 1. If not, we have nothing to look at
if len(reading) > 0:
# A standard CR character (ASCII 13, or 0x0D) tells us we have all the data
if b'\r' == reading:
# If the data is complete, call our data handler to do something with it
handle_data(new_data)
# clear the storage area and get ready for new data
new_data = ""
elif reading >= b'0' and reading <= b'F':
# The character is human readable and will be in the range 0-9 or A-F,
# so stick it on the end of the storage area to build up the incoming data string
new_data = new_data + reading.decode()
MadelineB
Moderator
Posts: 908
Joined: Fri Jun 20, 2014 4:42 pm
Occupation: Biostatistician/Data Scientist
Project Question: Interested in volunteering as an expert
Project Due Date: n/a
Project Status: Not applicable

Re: Python Code Explanation

Post by MadelineB »

Hello,

I'm not sure I understand what you are asking. The text that you displayed consists of comments and code. The lines which are comments all start with #. The lines which do not start with # are code. Each comment is, in fact, explaining what the code on the following line is doing. When you run the code, the comment lines will be ignored since they start with #.

Please let us know if you have more questions.
Locked

Return to “Grades 9-12: Math and Computer Science”