We've already discussed why Python is one of the best programming languages for beginners. And now we're going to prove it. We'll start with instructions on how to enter data and, in the end, you’ll be able to write your own calculator. Let's have fun!
Prepare the workspace
The first step is to install Python on your computer. (You can download it for free from the official website.) The installation process is as easy as installing Google Chrome. Simply follow the instructions.
You can now start programming. To do this comfortably, you should install a development environment like Wing or PyCharm. Development environments are handy because they have plenty of useful features, such as a project manager, auto corrector, debugger ― which allow you to stop the program at some point and inspect its state ― and many more. You’ll find detailed installation instructions on any integrated development environment (IDE) website.
If you don’t want to install Python on your computer, you can use an online development environment to run code.
The first thing you will come across in coding is variables: they are like containers that hold data. In order to illustrate their usefulness, we can simply look at code that doesn't use them. Here is a line of code that displays the message “Hello, World!”:
Here print() is the command, and "Hello, World!" is the data. But what if we want to output "Hello, World!" five times? We could do the following:
It looks pretty bulky. We can type "Hello, World!" into a container — a variable:
In the first line, we created, or as programmers call it, initialized a variable. Then we just bring it up inside the command we want. The symbol "=" here acts as an assignment operator. In other words, when translated from Python to English, a = "Hello, World!" will mean a containing "Hello, World!”.
You can also change the contents of the variable, replacing their content with new ones:
Furthermore, you can program a variable so that it stores a user's input:
a = input()
After launching, the program will wait for the user to type something and press Enter and then output the entered content.
You can also show the message that the user will see before the input:
a = input("Type something and press Enter: ")
This code works the same as the previous one, but also displays the message "Type something and press Enter: ".
There are a few simple rules to follow when choosing variable names:
- A variable name can only contain Latin letters, numbers, and the underscore character.
- The variable name must not contain spaces.
- The variable name must not begin with a number.
- Case is important: var and Var are different variables.
When naming variables, remember that variable names should not coincide with keywords and built-in function names because it can lead to unexpected behavior and errors in your code.
For example, if you use the variable name "print" to store a value and later try to call the built-in "print" function, you will get an error because Python will try to call your variable instead of the function.
Below are built-in functions and keywords for Python:
If you need to create multiple variables, you can do this using either multiple lines or a single one:
As you can see, variables can contain data of various types — numeric, text, and others. Let's look at some of them.
Data types in Python
There are large data types in Python, such as numeric, string, sequence, etc. We will cover the basic ones.
Let's start with the numbers. The most commonly used numeric data type is the Integer type. It's used to represent whole numbers in the 2147483648 to 2147483647 range. You can also write Integer values as a mathematical expression if the result is a whole number.
Python uses mathematical operators (+, -, *, /, ^) for mathematical operations. As you can see from the code above, “+” is used for addition, “-” for subtraction, and “*” for multiplication, and the calculations in parentheses take higher priority.
“//” is used for whole number division. If our code were like this:
a = 9 // 2
b = 7 // 2
We would get an output like this:
For division, where the result can be a fractional number, use the “/” operator. But, in this case, we will get a different type of data — a floating point number:
In the first case, we used the "//" operator to force an integer result.
Floating point numbers are unstable in Python and many other programming languages because they are stored differently in computer memory than whole numbers. This is what it looks like:
a = 0.1
b = 0.2
c = a + b
The expected output of this code is 0.3. But the actual output may look the following way:
Floating point numbers in Python is an advanced topic, so we'll skip it this time. For a lot of situations, simpler numbers get the job done. Now just move on to the next data type.
If you want the input entered by the user to be read as a number, you have to explicitly specify the data type int in the input() command:
a = int(input(“Enter an integer: ”))
Such a variable can only store an integer number. If you want the user to enter a floating-point number, you must specify the float data type:
a = float(input(“Enter a floating-point number”))
Let's move on to the text data. When we output "Hello, World!", we were already using text data. In Python, this type of data is called String. You can do a lot of interesting things with strings, but we'll look at just a couple of examples.
In order to create a variable containing a string, you need to write something in double or single quotes:
a = "Text in double quotes"
b = 'Text in single quotes'
Text in double quotes
Text in single quotes
We can also create an empty string if we don’t leave spaces in quotes:
a = ""
This is not the same as creating a string with only a space:
a = " "
Although in both cases we will get a visually empty string in the output, the computer will interpret them as two different strings.
Like with numbers, we can apply mathematical operators to strings. But not all of them, just “+” and “*”. The following code shows how this works:
As you can see, addition joins strings, and multiplication works like multiple additions:
The following code shows the differences when using mathematical operators with string and numeric data:
We got the number 9 and a line with the text "333”.
By default, the data entered with input() is interpreted by the computer as a String.
An extremely important data type for creating constructs with conditions, which we will get below, is Boolean. There are only two possible values for a Boolean-type variable: True and False.
This looks pretty useless. But, the beauty of boolean values is in how you can create them. You are already familiar with the mathematical operators (+, -, *, //, /), now let's get to know the other group — the comparison operators.
We can compare the values of variables. In order to do that, we have the following operators:
- “==” to see if a variable's values are equal
- “!=” to find out if the variables' values are different
- “>” to find out if the value to the left of the operator is greater than the value to the right
- “<” to find out if the value to the left of the operator is lower than the value to the right
- “>=” to find out if the value to the left of the operator is not lower than the value to the right
- “<=” to find out if the value to the left of the operator is not greater than the value to the right.
The values of expressions with these operators can only be True or False:
You can also compare strings for equality:
Basic constructions in programming
We already know some of the data types that Python works with. Now let's learn how to build constructs from this data.
Imagine that you need to write a program that checks if the user entered the password correctly. In this case, you need to consider two possible scenarios:
- First — the user has entered the password correctly;
- Second — the user has entered the password incorrectly.
What the program will do depends on user input. This logic is implemented through conditional statements, also called “if-else” constructs. This is what it looks like:
The if-else constructions are built like this:
if the condition is satisfied (the value of the expression is True):
event A occurs
else (the value of the expression is False):
event B occurs
As you can see, the code inside each condition does not start on a new line but is indented by four spaces. It is important to follow this rule for your code to work correctly. Also, don't forget to put colons at the end of each condition.
But what if the program has more than two scenarios of interaction with the user? In this case, the program will follow the “if-elif-else” structure. Let's change our program a little bit:
The if-elif-else constructions are built like this:
if the condition A is satisfied:
event A occurs
elif the condition B is satisfied (the value of the first expression is False, but the value of the second expression is True):
event B occurs
else (the value of both expressions is False):
event C occurs
Another important construction in programming is loops. What makes a computer better than a human is that it doesn't get tired of routine work. You can give a computer a task and program it to repeat a task as often as you want. In programming, such instructions are written using loops.
Remember we entered the program “Hello, World!” five times? Here it is:
And here's how you can shorten the code with a loop:
Such a construction is called a "for loop". Compose it according to the logic below:
for loop variable in range(number of repeats):
But what if we don't know exactly how many repeats we need? There is another type of loop for that — the conditional loop, also known as the while loop in Python.
Let's modify our program with password input. Now, until the user enters the correct password, the program will ask the user to enter the password again:
Let's see how this code works.
- First, we store the correct password in the password variable.
- Then we store an empty string in the user_input variable. This is to make the while loop condition work, which is that user_input is not equal to password. That's how we get inside the loop. And now as long as user_input != password condition is True, the loop will be executed, i.e. there will be outputted messages:
Enter the password:
Wrong password, login denied
To break the loop, we have to break the user_input != password condition, i.e. make user_input == password. In other words, when a user inputs the correct password, they will get the following message:
Password accepted, login allowed
The print("Password accepted, login allowed") line is not indented because it is not part of the loop anymore and will only be executed when the loop has been passed.
The problem with our program is that it displays the "Wrong password, login denied" message before the user has even entered anything. To fix this, let's add an if-else construct to the program:
Now if the user entered the password correctly on the first try, they get the message "Password accepted, login allowed". The loop will only be executed if the password input is incorrect. Note that if we insert one construct into another, the code of the inner construct is indented by four more spaces.
Sometimes in programming, you need to use an infinite loop. In order to create it, just write True in the while loop condition:
print("Something is going on")
Such a loop will work until you close the program manually.
However, you can write a condition inside the infinite loop to end the loop. To do this, use the break command along with a conditional operator. Let's see what a program looks like that outputs what the user enters until they enter "end":
The last construction we’ll look at today is called a function. If we often use the same bit of code, it becomes tedious to write it repeatedly in different parts of the program. In order to simplify the process, we can turn it into a function — a subprogram where we can insert the commands we need.
Remember how we shortened the code of a program that outputs "Hello, World!" 5 times?
for i in range(5):
We can cut it down to one line:
But if we just input this into our program, the computer won't understand what we want. So we have to describe the function first:
When we describe a function, we first write “def”, the function name after the space, brackets, and a colon. We write our code with four spaces indented inside, or, as they say ― in the function's body. The general view of the function looks like this:
But what if we want to output something different, and do it as many times as we want ― do we have to write a new function each time? The answer is no. A function is a flexible tool, so it can be customized with function arguments. Here's what it looks like:
The function arguments are what we put in parentheses after the function name. Function arguments are specified with a comma. When calling a function, we need to put the arguments in the same order as in the function description.
We can also let the user decide what to output and how many times:
Functions can do more than simply print something ― they can also process the data to extract values:
To get some value as a result of a function, you need to store that result in a variable and return that variable to where the function was called from. To do this, the last line in the function body must consist of the return keyword and a variable with the result. The variable is usually called "result" or "res".
You can also write the expression after the return command. Let's write a function that converts temperature from degrees Fahrenheit to degrees Celsius:
Writing a calculator in Python
You already know some basics, so let's write a simple program — a calculator.
The calculator has to take three values — an operation (add, subtract, multiply, and divide), the first number, and the second number. Let's write a function for each action:
You can run this code in the Python command line or in the integrated development environment. The calculator will work the same way everywhere. Try it!
Congratulations! You have written your first Python program. Give yourselves a round of applause!
Now that you know the basics of Python, you're ready to build even cooler applications. With TripleTen’s Data Science Bootcamp, you'll quickly learn how to do just that. They teach Python along with some libraries and much more. If you’re ready to break into IT, check out TripleTen and start your journey toward a new career today!