Python is a powerful, yet user-friendly language ideal for automating tasks and solving complex problems. In this tutorial, we'll cover:
- Inputting and outputting information
- Storing information
- Getting help when we need it
By the end, you will have enough knowledge to create your own calculator using Python.
What is a program?
At a basic level, programming involves creating a list of instructions for the computer to follow, based on the input information. Let's use a calculator as a simple example. First, I input the numbers and operators for my problem by typing on the keypad. When I press
=, the calculator follows its list of instructions to perform my desired calculation. This instructions list, called a script, also tells the calculator to output the solution to the screen so that I can read it.
Python is a high-level programming language, meaning that we can read and write code that can be understood easily by a human (high-level), instead of writing code in a form the computer understands (low-level). So we could write
123 + 456 in our code, and Python will convert this to the binary representation, or the 0's and 1's, that the computer needs. Additionally, it also converts the output back to a form that we can read. Python does all the low-level conversion behind the scenes so we can do all our work at a high-level. This makes Python very friendly to use and easier to learn than other programming languages.
Basic math operations are built-in to the Python language. We can simply type them in our script and Python will be able to process them correctly. We only need to know which symbols to use for our desired operations (see the table below).
|-||Subtraction and Negative Numbers|
Python also includes some other operators, which can be found in the documenation here.
The code editor below contains three different sections. We write our script under the
script.py tab on the left.
script.py refers to a file named "script" with the .py extension, the Python filetype. Before running our script, the right side of the window will be blank. Once run, the Output and Variables sections will appear if our code contains output and/or variables. Variables allow us to store and edit information in our program, we will discuss them in detail later in this tutorial.
Pressing Run below will cause Python to process the input mathematical operations, but since our script does not specify what to output or define any variables we will not see anything happen. We will learn to address these issues in the next two sections.
Printing to the screen
By displaying our output, we can obtain the results of our calculations and check that the results match our expectations. To show the results on the screen, Python uses the
print() function. A function is a piece of code that accomplishes a specific task. Functions in Python need to be called, or told to run, by adding parenthesis after the function's name. When we type
print() Python runs code that will output whatever is written, or passed, to it within the parenthesis. By calling
print() and passing our math problems to it, we can see the work that Python is doing. Now running the code below will display the answer to each problem in the Output section.
Now we can see that each problem had the same solution, 16, but we actually printed two types of numbers, integers and floats. You'll notice that our division problem printed
16.0 instead of just
16 like the others. Python (and mathematicians) refer to whole numbers as integers and Python calls a number with a decimal a floating point number, or float. When we add, subtract, multiply, and use exponents with integers, we always get an integer as the result, so Python outputs an integer for these operations. However, with division, we often get a fractional result so Python will always output a floating point number for division.
In addition to printing numbers, we often want to use
print() to give instructions, provide an explanation, or to debug our code. To accomplish this, we will want Python to print a line of text. Python has its own name for text data, it's called a string. To create a string in Python, we place quotations around the text. Usually we can choose between double or single quotations, but we need to be careful if there are quotations or apostrophes in our string.
"Hello, my name is Devin." <-- Python string with double quotes 'I like to play poker.' <-- Python string with single quotes "Have you seen "Rounders"?" <-- This does not work because Python sees two strings, "Have you seen " and "?" with a variable called Rounders in the middle 'You should watch "Rounders"!' <-- Use single quotes so the double quotes do not confuse Python "It's a really good movie." <-- Use double quotes so the apostrophe does not confuse Python
Strings require the quotations so that Python does not mistake the text for a variable name. We will discuss variables in the next section.
It is traditional to print the string "Hello World!" as your first program (here's why). It's time to write your first python script! In the editor below:
- Press Run
- On the right you should see
Hello World!displayed in the Output section.
Congratulations on completing your first program! We just need a few more tools to be ready to take on creating our own calculator program.
Code can get confusing quickly if we have a ton of numbers and/or text information and no way of identifying what each piece of information represents. Fortunately, we can give our information a descriptive name and store its value using variables. Once that information is stored, we can reference it again anytime using the variable. We can also change the value of the variable whenever we need to.
Variables also make it easier not to repeat code. The DRY (Don't Repeat Yourself) principle should be applied to your code whenever possible. If you find yourself copy/pasting the same information repeatedly, consider storing that value as a variable.
Let's say that I am using Python to write event invitations for all of my friends. I want to write the same message, but add their names to personalize it. I want to avoid typing the same message over and over, like the script below.
# Not DRY print("Hello Davin, you are cordially invited to my really big important event. Please RSVP at your earliest convenience.") print("Hello Hayden, you are cordially invited to my really big important event. Please RSVP at your earliest convenience.") print("Hello Chantelle, you are cordially invited to my really big important event. Please RSVP at your earliest convenience.")
#in Python is used to represent a comment. Anything written to the right of a
#on a line is a comment which allows us to provide extra information about our code. Python understands that this is not part of the actual code and ignores it when running the code.
I can store the different parts as variables. Python uses the
= to assign any Python object to a variable.
My message has three parts:
- The start of the message
- The name
- The end of the message.
I will assign values to the variables
end. Once I have defined a variable by assigning it it a value, I can just type the variable name and Python will know that I am referring to the information stored in that variable. I also need to change the
name variable so I assign a new name each time before printing my next invitation.
# DRY start = "Hello " name = "Davin" end = ", you are cordially invited to this really my important event. Please RSVP at your earliest convenience." print(start + name + end) name = "Hayden" print(start + name + end) name = "Chantelle" print(start + name + end)
Python provides many useful ways to format string data. Here I used the
+ sign to combine strings, a process known as concatenation. You'll have the opportunity to learn more about strings in another tutorial, for now let's focus on the value of variables.
Using variables, I only had to type my invitation once. Then I could use the variables to draft unique invitations by only changing the
name variable. As we learn more Python skills, using variables will help prevent us from repeating even more code. Additionally, the "DRY" code above provides a more descriptive, readable code. I can easily tell that the purpose of this code is to print the same statement each time, with a different name.
Variables can be named anything you want as long as they pass the guidelines below.
|The variable name cannot contain
|The variable must start with a letter or
|first, Second, _third||4th, 5_th|
|The rest of the variable name consists of
only letters, numbers, and underscores
|pass, passesT00, also_PASSES||fail!, f@ils, #alsoFailz|
In addition to following the guidelines, we want to be careful not to give our variables the same name as Python's built-in functions. For example, we have been using the built-in
print() function throughout this tutorial. When Python sees
Often code editors, like the Dataquest one above, will use a different color to identify Python built-in functions but a full list of them can also be found here.
Choosing a descriptive variable name helps you to remember the value being stored and avoid overwriting built-in functions, so be specific! Most of your time coding will be spent reading code, not writing it, and descriptive variables help make code more readable. A longer variable name requires more typing time, but in the long run you will save time for yourself and everyone else by being able to read and understand your code quickly.
Programming is a continuous learning process. Each new program brings new challenges and another opportunity to learn. Accelerating the learning process involves becoming a master at getting help. Fortunately, Python provides one of the best communities of any programming language, a wealth of shared information online, and its own help function.
Google offers the quickest route help for a specific problem. Often this will direct you to the documentation, Stack Overflow, or Github resources that you will need to solve the problem. However, Google will also direct you to other great resources, like Dataquest, that could prove helpful. Do not hesitate to join the communities at Dataquest, Stack Overflow, and Github. If you cannot find an answer to your question, you can post your question and let the community point you in the right direction.
Help in Python
Python also includes a built-in function to provide help. For the
help() function we can pass the name of the object that we need help with. Everything in Python is an object, meaning we can store it as variable or pass it to a function. When we pass an object to the
help() function, it provides any documented information about the object. For example,
1 is an
int (short for integer) object, if we type
help(1) Python will output information about
int objects. We can also pass variables and even functions to
help(). Let's try it as a variable. Type
help(x) below the variable, to learn more about the
int object type.
Now we can see the the docstring for
int, which provides documentation about integer objects. Do not be intimidated by the documentation, it will make more sense as your Python skills progress. Using Python's
help() can sometimes be quicker than heading to your browser and searching for help.
Project: building a calculator
Right now we have only a very basic set of Python tools, so our calculator will be very simple. However, I encourage you to revisit this projects from time to time and improve them using any new tools that you have learned. There will be less direction in the project than the previous examples, so do not be afraid to get help. Let's begin!
- Assign an addition calculation that equals 32 to the
- Use the
print()function to output the
- Run the code
- Create a variable named
- Assign a subtraction calculation that equals 9 to your
- Use the
print()function to output the string "The solution is..."
- Use the
print()function to output the
- Run the code
- Create two variables
- Assign 4 to
xand 9 to
- Create a variable named
additionand assign it the value of
x + y
- Repeat step 3 for the variables
exponent, changing to the appropriate math operator each time.
- Print your
Great Work! Keep working hard, getting help and learning each day. Learning a language takes time and can be frustrating. Stay persistent and remember that each time your code fails is another learning opportunity. Python is a great language that you will quickly learn to love for both its simplicity and its power.