Coding Articles
Basic coding terminology, planning your coding career, programming for web, freelancing tips, example coding projects, and more.
Articles From Coding
Filter Results
Cheat Sheet / Updated 04-27-2022
Coding is fast becoming a skill that every child needs to be educated for in the 21st Century. But coding is taught at only a small fraction of schools, and often only at the high school level. Helping kids learn how to code also means you’re assisting them in developing a skill that is highly marketable and sets them apart from peers at school and later, in their careers. The topics in this cheat sheet can assist you on getting started when your kid expresses an interest in learning how to code.
View Cheat SheetCheat Sheet / Updated 02-25-2022
Coding is equal parts vocabulary, logic, and syntax. Coding may at first seem intimidating, but with practice, though, it's easy to get comfortable with its terminology, concepts, and structure. Understanding coding is not unlike learning a new language: Use it often enough and you'll find yourself able to speak, think, and write in code. Still, it's natural for beginners to have questions. There are many coding resources available to you, both on- and off-line. Ask around and you'll find you're not alone — many other people are learning. After all, coding is a never-ending education. Master one facet or another and a new one opens in front of you.
View Cheat SheetCheat Sheet / Updated 02-23-2022
Coding, or computer programming, is your way of communicating with technology. It’s the new literacy you need to master to be successful in the coming decades. Like any form of communication, coding takes place through language. Just as there are many human languages (English, French, Mandarin, Spanish, and so on), there are many coding languages! Two examples of coding languages are Scratch and JavaScript. Scratch is perfect as a coding language for kids because it’s easy and fun to use, Scratch coding for kids allows you to build programs by snapping together commands in the same way you assemble a puzzle. JavaScript is a step up in difficulty because it’s an authentic programming language, used by real coders. JavaScript powers many technologies, and you can use it to make both apps for your phone and control code for operating electronics gadgets. You can ease into JavaScript by using blocks to build programs (just like Scratch) and then switching to text-based coding when you’re ready. Here, discover tips for creating programs in Scratch, coding JavaScript apps in App Lab, and writing JavaScript code in MakeCode to operate the micro:bit electronics board.
View Cheat SheetCheat Sheet / Updated 01-19-2022
Coding is equal parts vocabulary, logic, and syntax. Coding may at first seem intimidating, but with practice, though, it’s easy to get comfortable with its terminology, concepts, and structure. Understanding coding is not unlike learning a new language: Use it often enough and you’ll find yourself able to speak, think, and write in code. Still, it’s natural for beginners to have questions. There are many coding resources available to you, both on- and off-line. Ask around and you’ll find you’re not alone — many other people are learning. After all, coding is a never-ending education. Master one facet or another and a new one opens in front of you.
View Cheat SheetArticle / Updated 07-01-2020
Unstructured data files consist of a series of bits. The file doesn’t separate the bits from each other in any way. You can’t simply look into the file and see any structure because there isn’t any to see. Unstructured file formats rely on the file user to know how to interpret the data. For example, each pixel of a picture file could consist of three 32-bit fields. Knowing that each field is 32-bits is up to you. A header at the beginning of the file may provide clues about interpreting the file, but even so, it’s up to you to know how to interact with the file. This example shows how to work with a picture as an unstructured file. The example image is a public domain offering from commons.wikimedia.org. To work with images, you need to access the scikit-image library, which is a free-of-charge collection of algorithms used for image processing. Here’s a tutorial for this library. The first task is to be able to display the image on-screen using the following code. (This code can require a little time to run. The image is ready when the busy indicator disappears from the IPython Notebook tab.) from skimage.io import imread from skimage.transform import resize from matplotlib import pyplot as plt import matplotlib.cm as cm example_file = ("http://upload.wikimedia.org/" + "wikipedia/commons/7/7d/Dog_face.png") image = imread(example_file, as_grey=True) plt.imshow(image, cmap=cm.gray) plt.show() The code begins by importing a number of libraries. It then creates a string that points to the example file online and places it in example_file. This string is part of the imread() method call, along with as_grey, which is set to True. The as_grey argument tells Python to turn color images into grayscale. Any images that are already in grayscale remain that way. Now that you have an image loaded, it’s time to render it (make it ready to display on-screen. The imshow() function performs the rendering and uses a grayscale color map. The show() function actually displays image for you. Close the image when you’re finished viewing it. (The asterisk in the In [*]: entry tells you that the code is still running and you can’t move on to the next step.) The act of closing the image ends the code segment. You now have an image in memory, and you may want to find out more about it. When you run the following code, you discover the image type and size: print("data type: %s, shape: %s" % (type(image), image.shape)) The output from this call tells you that the image type is a numpy.ndarray and that the image size is 90 pixels by 90 pixels. The image is actually an array of pixels that you can manipulate in various ways. For example, if you want to crop the image, you can use the following code to manipulate the image array: image2 = image[5:70,0:70] plt.imshow(image2, cmap=cm.gray) plt.show() The numpy.ndarray in image2 is smaller than the one in image, so the output is smaller as well. Typical results are shown below. The purpose of cropping the image is to make it a specific size. Both images must be the same size for you to analyze them. Cropping is one way to ensure that the images are the correct size for analysis. Another method that you can use to change the image size is to resize it. The following code resizes the image to a specific size for analysis: image3 = resize(image2, (30, 30), mode='nearest') plt.imshow(image3, cmap=cm.gray) print("data type: %s, shape: %s" % (type(image3), image3.shape)) The output from the print() function tells you that the image is now 30 pixels by 30 pixels in size. You can compare it to any image with the same dimensions. After you have all the images in the right size, you need to flatten them. A data set row is always a single dimension, not two dimensions. The image is currently an array of 30 pixels by 30 pixels, so you can’t make it part of a data set. The following code flattens image3 so that it becomes an array of 900 elements that is stored in image_row: image_row = image3.flatten() print("data type: %s, shape: %s" % (type(image_row), image_row.shape)) Notice that the type is still a numpy.ndarray. You can add this array to a data set and then use the data set for analysis purposes. The size is 900 elements, as anticipated.
View ArticleArticle / Updated 06-29-2018
After you and your young coder finish making your app, you can share it with anyone who has an Android device. Just go to your list of Projects (Projects → My Projects), check the box next to the app you want to publish, and click Publish to Gallery. Fill out the form by uploading an image and providing a description. This is where you can put any attributions of media that you might have used in your app. Click the Publish button when you’re ready. The screen you’re taken to, after you publish your app, has a share link, which you can share with your friends who might want to check out your code. They can then click Open The App and remix it to try it on their own! To share your app with friends who just want to play your game, you have two options. Generate a temp QR code. This code allows your friends to download your app. Open your app and choose Build → App (provide QR code for .apk). In the pop-up window is the QR code, which you can share with your friends. Using any QR code scanner, they can scan the QR code, open the link that is associated with the QR code, and a download starts. After the download is complete, they can open the app and play your game! The game is available until they delete it, even though the QR code expires in two hours. Download your app files and distribute them to your friends. You can do this by choosing Build → App (save .apk to my computer). Then you can upload the file to Google Drive (or any other accessible server), make sure it’s accessible for anyone to view the file, and then distribute the link to the file. When your friends open the link on their Android device, the app starts downloading.
View ArticleArticle / Updated 06-29-2018
If your young coder wants to try apps, give the MIT App Inventor a try. To get started with MIT App Inventor, you need a Google account. Then follow these steps to set up your programming environment: Go to MIT App Inventor and click Create Apps in the top-right corner of the webpage. Sign in with your Google account. Give permission for Google to share your email address with App Inventor. Accept the Terms and Services for App Inventor and click Continue when you’re ready. Dismiss the survey and other items that pop up so that you can get started! You now see a view where all your projects are listed. You’re now ready to start designing and writing your first mobile app! Community and support within MIT App Inventor App Inventor was first released in 2010, and the community of coders and educators has grown. Make sure you’re signed in and then click Gallery. The image below shows the gallery where you find projects and tutorials that other coders have made and published. You and your coder can contribute to these too! In addition to the community gallery, MIT has created a number of resources for individuals and classrooms. For example, you’ll find over 30 tutorials divided by difficulty level and an option to filter by topic (such as game). There are also a ton of resources about using App Inventor, setting everything up, troubleshooting, and documentation. All this can be found in the MIT App Inventor library. Although this page is a bit less user-friendly — basically a list of links — it can be a great place to start if you have a question or experience any trouble. The community isn’t just created by MIT; there are also a number of books that you can find on App Inventor and forums where you can ask questions and get very specific answers on the App Inventor website under Resources. There are also specific resources for educators. Be sure to explore all the resources when getting your young coder acquainted with the software. The layout of MIT App Inventor Before you get started on your first mobile game, take the time to get acquainted with the programming environment. There are two areas your coder will spend time in: Design View and Code View. To get to Design View, click Start New Project in the top left of the programming environment. Name your project “myFirstApp.” The Design View opens. Note these six areas: Menu Bar: The menu bar across the top has the title of your app, options for multiple screens, and a toggle button for Designer and Blocks. Palette: On the left is a list of options for things to add to your app. Viewer: The viewer is basically what you see on your mobile device after you test your app. This is where you organize all the components to add to your app. Components: The components list shows all the elements in your app. Sometimes components are invisible, so this is an important view to know everything in your screen. Media: Under the Components view is a Media view where any sounds or images that you have uploaded to your app appear. Properties: If you click a component in the Components view, then the properties for that component is listed in this view. You can also change properties in this view, too. Then, to see the Code View, click the Blocks button on the very right of the Menu Bar. Menu Bar: Just like in the Design View, the menu bar allows you to switch screens or go back to the Design View. Blocks: This view has all the coding blocks (also referred to as tiles). There are generic blocks, but if you have a component in your design, there also are blocks specifically for that component. Media: This view has all the sounds and images that you have uploaded to your app. Coding Area: The coding area is where you drag the coding blocks to actually make your app respond to your users.
View ArticleArticle / Updated 06-29-2018
When you and your young coder are trying to debug, sometimes no error messages give you insight into the problem. Here, you find a list of strategies for debugging programs where you don’t get an error message, or the error message doesn’t give you enough information. Turning sections on and off One of the best ways to debug is to disable sections of code so that you have small sections to test. Using Scratch In Scratch, you might have a lot of scripts that start when the green flag is pressed. This can cause problems if some of the scripts cancel out or affect the other scripts. For example, the image below shows three scripts associated with one sprite. The problem that the user notices is when the mouse pointer is touching the sprite, it does not meow. To try to figure out the problem, the coder might disconnect all the scripts and only have one script connected at a time. Then they see that the code for the mouse pointer touching the sprite works correctly, but that there is another problem (the code that stops all sounds forever). By connecting and disconnecting the blocks, the coder can identify the problem. Using App Inventor Other block-based languages like App Inventor make turning sections on and off even easier! The image below shows how if you right-click a code block, you can disable that block. In this example, you might want to make sure the initial property settings work before creating the lists and hiding the items. Then, after you confirm the properties are set properly, you can enable the call to setupLists to make sure that works. Then you can enable the call to hideItems to make sure that works. By turning off all sections and then turning each one on one at a time, it’s easier to find bugs. Using Python Text-based languages have a similar way of turning sections on and off — you only have to comment out the lines of code. In Python, you can comment out a single line of code like this: #print 'Hi' And you can comment out multiple lines of code like this: "' for x in range(0, 4): print ('Hi ' + pets[x]) "' Commenting out code is how you “turn off” or “disable” parts of your code when you’re in a text-based language. Testing sample data A common bug that coders run into is not testing data to make sure that the program works. This can especially be a problem if you’re writing programs that take user input. It’s important to make sure you and your young coder think about what kind of input you’re expecting, and test to make sure the input is handled correctly. You might have a program that gets input from the user and prints what the user types, like this Python code: name = raw_input('What is your name? ‘) print (‘Hi ' + name) It’s important to test to make sure that if you put the following types of input, they still do what you, as the coder, expect: Sarah Sarah Guthals 13 11/15 Sarah 55 Guthals By mixing letters, spaces, numbers, and other symbols like / you’re ensuring that your program performs as expected. This type of testing is unit testing and ensures that small portions of your program execute correctly with varying input. Adding output messages One of the most challenging aspects of coding is that the code is abstract and sometimes the data is hidden. This is especially tricky when you have complex data or are performing complex operations on data. By adding a number of output messages in your code, you can indicate when certain sections of code have been reached, or you can show the current values of certain variables at various points during execution. An example of adding output messages to a program to gain insight in Python follows. Here, your goal is to write a program to solve an algebraic expression. For example: x = input('Provide a number for x: ') y = input('Provide a number for y: ') first = 2*x second = 6*y sum = first - second print '2x + 6y = ' print (sum) There is an error in this program; instead of adding the first and second elements, the coder is accidentally subtracting. Though this error is fairly obvious because this example is small, it shows how a simple typo could completely change the output. If you run this code, you get results like: Provide a number for x: 2 Provide a number for y: 3 2x + 6y = -14 This is clearly wrong. 2*2 + 6*3 = 4 + 18 = 22, not -14. One way of debugging this code is to add output messages at each point. For example, you could change your code to: x = input('Provide a number for x: ') print ('x: ') print (x) y = input('Provide a number for y: ') print ('y: ') print (y) first = 2*x print ('first: ') print (first) second = 6*y print ('second: ') print (second) sum = first - second print "2x + 6y = " print sum Then, when you run the code you get the following output: Provide a number for x: 2 x: 2 Provide a number for y: 3 y: 3 first: 4 second: 18 2x + 6y = -14 Then the coder can see that x, y, first, and second are all correct. This must mean that it’s just when the sum is calculated that there is an error.
View ArticleArticle / Updated 06-29-2018
It’s easy for kids to make semantic errors when they’re first learning to code. Unlike syntax errors, semantic errors are often more difficult to capture. This is because semantic errors are typically errors in the programming logic, rather than something that you typed incorrectly. Here, you find a couple of examples of semantic errors that you and your young coder might encounter in a few different programming languages. Infinite loops Infinite loops are loops that never end! They go on infinitely. This can be a problem because it might seem like the code just isn't working, but really the program is just running forever and ever. Using Java If you wrote a small Java program where you wanted to print the numbers 0 through 9, you might write something like this: for(int index = 0; index < 10; index--) { System.out.println(index); } But there is an error in this code! Instead of updating the index to be index + 1, the code updates the index to be index – 1! So the code does the following: index = 0 Is index < 10? Yes Print index 0 index = index – 1 index = -1 Is index < 10? Yes Print index -1 index = index – 1 index = -2 Is index < 10? Yes Print index -2 index = index – 1 index = -3 Is index < 10? Yes Print index -3 This continues forever, because it’s impossible for index to be greater than or equal to 10. So when you run the Java code, the program continues to print forever, until you kill the program! Using Scratch Although infinite loops can be a problem, some programming languages deliberately have implemented infinite loops to make some pretty neat effects! For example, in Scratch there is a forever block which can do some cool things. Off by one Another very common error to run into is called an off by one error. This is very common when dealing with lists and iterating through lists. Using Scratch Scratch, as usual, handles off by one errors for the user without really indicating there’s a problem. For example, the image below shows a program that loops through a list of pets and has the sprite say Hi petName, where petName is replaced with the item from the list (either Luke, Winston, or Princess). The loop repeats four times, but there are only three items in the list. Instead of completely breaking, on its last iteration, Scratch prints Hi with nothing after it. Using Python Other programming languages are not as forgiving. For example, in Python you might have the following program to say hello to the three pets: pets = ['Luke’, 'Winston', 'Princess'] for x in range(1, 3): print (‘Hi ‘ + pets[x]) If you run this program, the output would be: The reason ‘Hi Luke’ doesn’t print is because lists in Python start at 0, not at 1. The correct code would be: pets = ['Luke', 'Winston', 'Princess'] for x in range(0, 3): print ('Hi ' + pets[x]) The range function used in Python: range(0, 3) Represents the elements 0, 1, and 2 because the range function includes the first number but excludes the second. Another version of an off by one error in Python would be if you went beyond the length of the list. For example: pets = ['Luke', 'Winston', 'Princess'] for x in range(0, 4): print ('Hi ' + pets[x]) This causes even more of an issue, because instead of simply missing an element in the list, you’re trying to access an element that never existed in the first place. The output for running this code is: Hi Luke Hi Winston Hi Princess Traceback (most recent call last): File "filename.py", line 4, in print ('Hi ') + pets[x] IndexError: list index out of range There is an actual error, because the data for pets[4] doesn’t exist, so the computer cannot resolve it; therefore it doesn’t know what to do. Off by one errors can be really tricky for young coders, especially if they’re switching between languages where lists start at 1 versus lists that start at 0.
View ArticleArticle / Updated 06-29-2018
Your coder can provide flexibility to her programs by coding parameters to subprograms. For example, coding a square subprogram allows the program to draw a square of a defined size each time the subprogram is called. But what if you want the square subprogram to draw squares of differing sizes? By adding a parameter to the subprogram you can do just that. A parameter is a variable that you pass into a subprogram, which the subprogram uses as it executes. You can pass a parameter into the square subprogram that tells the code how big to draw the square. Scratch code block with parameters Scratch allows you to add one or more parameters to any subprogram block you create. Your coder can begin by making a simple block. Then, your coder can add parameters when she first creates the block, or she can edit the block after it has been created — the process is essentially the same. Here are the steps for editing the square code block previously created: In the More Blocks category, right-click (Windows) or control+click (Mac) the instance code block tile that you previously created. Select Edit from the pop-up menu which appears. The Edit Block dialog box appears. At the Edit Block dialog box, click the Options tab to expand the options for adding parameters. Click the icon for any of the parameter options shown to add that parameter to your block. You can choose Add Number Input, Add String Input, Add Boolean Input, or Add Label Text. When you click an icon to add that parameter, a blank field is added to your instance code block tile. You can add more than one parameter. Inside the blank field on the instance code block tile, type the variable name of the parameter(s) you’re adding. Select the Run without Screen Refresh check box. This allows for faster execution of your program. Click OK. The dialog box closes and the code block tile now shows the added parameter(s). In Scratch, parameters added to code blocks play the same role as variables. When the parameter is added, you can use it just like a variable in your program — although be aware that it doesn’t appear in your list of variables in the Data category. Using your edited block with parameters is easy! Just drag the parameter tile from the code block definition (the big “hat” tile) into your code when you want to use the parameter. The parameter replaces code which you previously defined outright. Instead of the code tile for move 100 steps, you now have a code tile for move size steps. This allows for more flexible usage of the code block because it can now accept a number for the size, sent by the main program, and execute the code block with that size as the side length. Your main program then calls the parameterized block, sending it a number to use for the size: square 30 draws a square with side lengths of 30 pixels; square 110 draws a square with side lengths of 110 pixels. JavaScript, with parameters You can add parameters to your JavaScript functions to add flexibility to your programs. To create a function with a parameter in Code.org's App Lab, using JavaScript, complete these steps: At the Functions category of tiles, drag a function myFunction(n) tile into the program workspace. The n is a parameter. If you already added a myFunction() command without a parameter, you can add the parameter by typing the parameter inside the parentheses. (Or, if you are working in tile mode, press the little horizontal arrows to add or remove parameters from your function.) In text mode, separate multiple parameters using a comma and a space following each parameter. Replace the myFunction(n) placehoder, by typing a name for the function, and a name for your parameter(s). Use camelCase naming conventions for JavaScript. Each parameter is a variable in your program. Attach commands to define your function. The parameters are referenced by their variable names inside the function. Use the function name and parameter values to call it from your main program. The parameters values are passed into the function. Parameter values are assigned to the parameter variables and used inside the function. See the image below for a JavaScript program with functions and parameters, written in the App Lab. This program draws a field of twenty flowers of different sizes and pink color, randomly distributed in the display. Note that there are two parameterized functions: one to draw oneFlower(size), and one to draw onePetal(size) of the flower. Here, the main program calls the oneFlower(size) function that has been defined to include a size parameter. The oneFlower (randomNumber(5, 20)) function call sends a random number, from 5 to 20, to the oneFlower(size) function; size takes on a new value between 5 and 20 each time the function is called. The oneFlower(size) function then calls the onePetal(size) function. The onePetal(size) function receives whatever value its parent subprogram received for size. The effect is that flowers of different sizes are drawn onscreen. The emulator shows the result of executing the program. Java, with parameters The image below shows a Java class named Product, written in the BlueJ IDE. The class contains one method, Product, which has two parameters, a and b. Here's how to code this program: Code the class name: public class Product {. Code the main program. This is the section labeled main. The main program calls the multiply method, which receives two parameters. Code the multiply method, which has two parameters, a and b. The multiply method defines three variables, a, b, and total. Variables a and b are parameters defined as integers. Their values, 5 and 7, are received from the call located in the main program. The multiply method computes total and prints out its value. Close the class with a curly bracket. The image below shows the execution of Product. Notice that the values of the variables a and b can be changed outside of the multiply method to result in a new product for total. This makes the multiply method modular and easy to reuse with different variable values on each use. Parameterizing methods build a more flexible program. Subprograms can also generate information that they pass onto other subprograms or back to the main program. In Java, your coder sometimes sees the code void. This means that, when the subprogram is called, it's not sending anything back to the program that called it. In other cases, your coder sees a variable type and name following the name of the main program or of a subprogram. That type and name tells you what type of information is going to be received by the program making the call. The subprogram contains a return command indicating what variable value is being returned (passed back to) the program that called it.
View Article