Variables, Operators, Data Types

Intro to Python: Section 3

In this section, you will learn how to use different variables, perform simple operations, and receive user input.

Variables

A variable is a representation of an object. They function similarly to variables as you would use them in Algebra or another math class. They’re placeholders for other things or values. Except in Python, variables can represent much more than just numbers. They can represent strings of text, characters, objects, files, and much more.

Specifically, a variable is a named reference to an object stored somewhere in the computer’s memory.

The best way to learn about variables is to use them! Create a new python project or continue using the same file from the last section.

Let’s create a variable, assign a value to it, and print that value to the screen.

x = 5
print("The variable x equals ", x)Code language: Python (python)

When you run the program, it should just print out “The variable x equals 5”

Let’s take a deeper look at all the parts involved here.

In the first line, I create a new variable with the identifier ‘x’

An identifier is the name of the variable. You may make any identifier you’d like, so long as it’s not a reserved Python keyword and contains no spaces or special characters. They may contain numbers, but they may not start with numbers. An exception applies for under_scores. You’re allowed to use underscores in identifiers in Python.

The equal sign is the assignment operator in Python, and most other programming languages. It assigns a value to a variable. So the first line is assigning a value of 5 to the variable identified as x.

The second line uses the print() function discussed in the previous section. However, now it has a second argument within the parenthesis. Each additional argument in the function call is separated by a comma. How each function handles its arguments varies depending on the function and how it was designed.

In the case of the print function, if you pass it an additional argument, it will combine that with the previous argument. So in this case, it’s taking the string of text “The variable x equals ” and sticking the variable x on the end.

Remember, x is a placeholder pointing to a value of 5. So when we use x in the print function, it’s going to replace ‘x’ with the value 5. This allows the program to print out “The variable x equals 5” when it is run.

Arithmetic Operators

Python has several operators you should familiarize yourself with. These are the simplest operators and the easiest way to make your programs begin to do things.

The addition operator is the plus sign, just as you’d expect.

x = 5
y = 10
z = x + y
print(z)Code language: Python (python)

The code above sets x to 5, y to 10, and z to the sum of x and y with the addition operator. This means z will be equal to 15 and the program should print out ’15’ when executed.

The subtraction operator is the minus sign.

x = 5
y = x-5
print(y)Code language: Python (python)

Note in the above code that I set y equal to x – 5. We can use any combination of variables or numbers here. The code above prints out the number 0.

The multiplication operator is an asterisk.

print(5*5)Code language: PHP (php)

In this example, I multiplied 5 by 5 in the print function call. This means Python will first calculate 5*5 behind the scenes before printing the result to the screen.

The division operator is a forward slash.

first_variable = 100
second_variable = 10
quotient = first_variable/second_variable
print(quotient)Code language: Python (python)

For this example, it divides 100 by 10 and prints out the result, 10. I used longer variable names or identifiers in this example. Note that for multi-word identifiers I separated each word with an underscore. You don’t have to do this, but it’s standard convention with Python programs. I could have just as easily named the variables “firstvariable” and “SecondVariable” and it would have worked the same.

The final operator we’ll discuss is the modulus operator or remainder operator. It finds the remainder of dividing two numbers. It is a percent sign.

x = 10
y = 3
remainder = x % y
print(remainder)Code language: Python (python)

The above code will print out the number 1, since 10 divided by 3 is 3 with a remainder of 1.

Additional Notes

You may change the value of a variable at any time. It’s not set in stone when you create it.

x = 10
x = 20
x = 15
print("x is: ", x)Code language: Python (python)
Terminal
x is: 15

Python executes code line by line from the top down. This means that the print statement will print out the final value we set x to, 15.

You may also set a variable equal to itself and modify it in some way.

my_variable = 100
my_variable = my_variable + 50
print(my_variable)Code language: Python (python)
Terminal
150

The above code prints out 150, since my_variable was initialized with a value of 100, then we told it to add 50 to itself.

Behind the scenes, Python is actually reassigning the variable to point somewhere else in memory each time we assign it a different value. It’s not truly changing 100 into 150, but rather, updating the reference my_variable to point to 150 instead of 100. This will be an important concept to understand later if you get more involved with computer science.

Order Precedence

It’s possible to use any combination of the above operators in one line of code.

For example:

x = 5
m = 0.5
b = -2
y = m * x + b
print("The y coordinate at x = ", x, " is ", y)Code language: Python (python)

The above example solves for y using slope intercept form. It prints out the proper answer:

Terminal
The y coordinate at x = 5 is 0.5

Now, consider the point slope form of the equation of a line, given as:

Say you want to solve for m given two points on the line, (5,7) and (9,15)

The equation to find slope is change in y over change in x.

𝑚=𝑦−𝑦1𝑥−𝑥1

We need to translate that equation into python. Let’s start with our given values:

x = 5
y = 7
x1 = 9
y1 = 15Code language: Python (python)

Now, we must solve for m. The easiest way to do this is by reducing the equation down to a single line.

𝑚=(𝑦−𝑦1)÷(𝑥−𝑥1)

Python follows standard order of operations, or order precedence. If you remember the PEMDAS acronym from grade school, it’s very similar. The order is as follows:

  • Parenthesis
  • Exponents
  • Multiply
  • Divide
  • Add
  • Subtract

Python will evaluate expressions from left to right, using the above ordering first.

Just like in a traditional math class, you can use parenthesis to group items you want solved first. So our equation in python is:

m=(y-y1)/(x-x1)
print("The slope is: ", m)Code language: PHP (php)
Terminal
The slope is:  2.0

We get an answer of 2.0. This is correct. But what if you forgot the parenthesis?

m=y-y1/x-x1
Terminal
The slope is: -5.0

We got a much different answer that time! The slope is incorrect. In this scenario, it first divided y1 by x, then evaluated the expression from left to right. This yields a result of -5.0 instead of 2.0.

User Input

In 99% of cases, you’re going to want the user to be able to feed information into the program for some sort of processing or storage. Whenever the user issues a command or does something recognizable by the PC, it is receiving user input.

User input may be anything from clicking a button with a mouse to a webcam tracking someone’s facial expressions. The devices that receive user input are called user input devices. Any device or sensor that sends information to a computer is a user input device. Scanners, computer mice, touch screens, keyboards, game controllers, webcams, fingerprint scanners, and gyroscopes are all examples of possible input devices.

Since we’re working with python from the command line or terminal in this series, we will read user input from the console. This was demonstrated briefly in the introductory section.

message = input("Type a message: ")
print("You typed: ", message)Code language: Python (python)

We can assign a variable to a value the user enters by using the input function. The input function takes a string as an argument. This argument is the message displayed to the user before getting their input. The program will wait for the user to type something and hit the return key, then the flow continues.

So the above code asks the user to type a message, stores the result in the ‘message’ variable, and then prints it back out to the screen.

Now consider a situation where you want the user to enter a number. We then find the square and cube of that number and print the results to the screen.

x = input("Please enter a number: ")
square = x * x
cube = x * x * x
print(x, " squared is ", square, " and cubed is ", cube)Code language: Python (python)

Suppose you run the program and type in the value “5” for x. What happens?

If you run it, you’ll see that the program errors out. You get a message saying:

Terminal
TypeError: can't multiply sequence by non-int of type 'str'

So what exactly went wrong? Well, when we use the input function, it returns a string.

Strings may contain letters, numbers, words, etc. Strings are sequences of characters, strings of text. It’s a string containing the number, not the number itself. Asking Python to multiply a string by a string is like trying to multiply the word “Apple” by “Apple”. It doesn’t make sense, so a TypeError is thrown.

When a TypeError is thrown, it means something is wrong with the type of the variables you’re working with.

There are several different types of variables. We’re only going to focus on Strings and numbers for now. Numbers can be further divided into more specific types of numbers. Python supports the following types of numbers:

  • int – The most basic type of number. A number with no decimal places. May be positive or negative.
    • Examples: 1, 5, -10, 50, 999…
  • long – A longer type of int
  • float – “floating point” values – they contain decimals.
  • complex – a complex number – an ordered pair with an imaginary unit. We will not be worrying about this type.

In your introductory courses, the most common types you’ll come across in Python are int, float, and string.

If you ever want to know the type of a variable, you can use the type() function on the variable to see what it is.

x = input("Please enter a number: ")
type_of_x = type(x)
print("The variable x is a :", type_of_x)Code language: PHP (php)
Terminal
Please enter a number: 54
The variable x is a : <class 'str'>

When I ran the program and typed in a number, I see that x is a ‘str’ or String. We need to convert this String into a Number. Do we want to convert it into an int (no decimals allowed) or a float (decimals allowed)?

I’ve decided to go with float, since floats can have both whole numbers (e.g. 1 becomes 1.0) and decimal places.

To convert between types, you can parse the variable into another data type. The syntax for doing this is quite simple. Just write the type you’re trying to convert to, and pass the String in as an argument. It’s a function that converts to the specified type.

You may also hear this referred to as casting. Casting differs slightly from parsing. Parsing is usually a safer method. Casting is “forcing” a variable to change types, without checking for errors. When you parse from strings with Python, it checks for errors before attempting to do anything with the data.

If I want to convert x to an int, I could write:

x = int(x)Code language: Python (python)

For a float it would be:

x = float(x)Code language: Python (python)

So to fix the error encountered earlier, I just cast x to a float after I get its value and continue on my way.

x = input("Please enter a number: ")
x = float(x)
square = x * x
cube = x * x * x
print(x, " squared is ", square, " and cubed is ", cube)Code language: Python (python)
Terminal
Please enter a number: 4
4.0  squared is  16.0  and cubed is  64.0

Since I picked float, even though I entered “4” it still adds the decimal place. If I selected int instead, it would not include the decimal place.

0 0 votes
Article Rating
Subscribe
Notify of
guest
0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments