Building My Toolkit is a series in which I document my learning of various tech and data tools. Ultimately, my goal is to incorporate these skillsets in my role as an institutional research practitioner. Each week, I discuss the progress I’ve made with a particular tool, currently the Python programming language.
Up until now, the coding examples have been relatively static — meaning that I hardwired the code snippets to work exactly as I want to, and there is no input on the part of the user to direct the flow of a program. Naturally, you can imagine that this is not very realistic, as many roles in higher education rely on technology and the information that we input into our computers. Fortunately the Python syntax to prompt for user input is quite simple:
name = input("What is your name? ")
In this example, I use the input function to prompt the user for their name by telling the user what we want them to do. There are also ways to validate the data, such as checking to make sure that no integers are entered into the name field or we might use the title function to ensure that even if the user were to enter ‘JOE’, ‘jOe’, or ‘joe’, as names, they would each get passed into the program as ‘Joe’. Incorporating user input into future projects will allow me to create dynamic and user-driven programs, such as a simple text-based role-playing game. On a very fundamental level, the same sort of logic is at work when users enter their credentials into an e-mail client or other software.
Another handy feature that I learned about this week was the use of while loops. Essentially, while loops do what the name implies: While a condition X or Y (or both!) is unmet, a block of programming logic will continue to execute. For example:
current_number = 1
while current_number < 5:
print(current_number)
current_number += 1
In this example, I tell the program to print the current number to the terminal, which I initialize with a value of 1. As long as the number is less than 5, the program will add 1 to the current value and print the new number until the condition (number < 5) is satisfied. And so the result of this program would simply be:
1
2
3
4
This sort of logic is quite common in a variety of cases. The find and replace feature in Microsoft Office is a great example. As long as the program detects another iteration of the user’s query, the program will proceed to highlight and replace that iteration. Again, the logic is oversimplified here, but I challenge you to consider other ways in which the while loop logic drives other applications that you may work with.
So far, we’ve talked about all of the neat things we can do through programming logic, from continuing to loop through certain blocks of code to executing certain code based on a given value. Next time we’ll take a look at functions, which are handy ways to bundle various bits of code together in a handy way that we can call upon as needed in our program.