Python Variables And Data Types

Writing code involves the handling of information. If we’re making a game, we need to store the user’s score. We’ll need their current balance if we’re creating a trading application. One of the most common things you’ll do when programming is to store a value so you can use it later. To do that, we use a variable. Think of a variable as a name you can always use to retrieve a previously stored value. A variable is simply a container for a value. When we run our programs, the computer gives us space in its memory where we can put data that we want to use as a reference for later. This data is a variable, much like how we label containers in our garage so we know where to go for our favorite tools. We declare variables in Python by giving them a name and setting their value. This is called assigning the value. And this assignment is done with the assignment operator, the equals sign. 

seventeen = 17

As we see here, seventeen is the name of our variable, and because of the equals sign, we are assigning it the value of 17. That means that somewhere in the computer’s memory, it’s made space for our variable and stored our value. Later, when we ask the computer to print what’s inside the seventeen variable, it prints out 17, the value we previously assigned. Although we’re using an equals sign, try not to think of it as you did in high school algebra. In programming, the equals sign means I want to take the value on the right and store it in the variable on the left. It doesn’t mean the two sides are equal. That’s important to keep in mind. 

colorful_tree = 'Maple'

This time, we’ve created a variable named colorful_tree and assigned it to the value of “Maple”. Even though we’ve made both of these variables by giving them a name, there’s something different about the value we assigned them. Can you spot the difference? Yes, we only use numbers with the first value, and for the second value, we have single quotes with letters inside. This is because we want the variables to represent different data types. A data type allows us to put our variable in a particular category so that the computer knows how much space to give us in its memory. And it generally knows how we plan to use our variable later in the program. In this example, the 17 is an integer, like what we’re already familiar with from math class. If you’ve forgotten, an integer is a whole number with no decimal places. The letters inside the single quotes are called a string because it’s made up of a string of characters. You can check the type of any value or variable in Python using the type function. 

seventeen = 17
colorful_tree = 'Maple'

print(type(seventeen))
print(type(colorful_tree))
# <class 'int'>
# <class 'str'>

Above, we print out the type of the seventeen and then the colorful_tree variables. We can see the first is ‘int’, or short for integer. And the next variable is ‘str’, short for string. There are many other types of values available in Python, as well.

Variables In Python And Other Languages

Depending on the programming language that you’re working with, variables can behave in different ways. Some languages require you to define your variables and their types before using them, like Java, C#, and C++. For example, if we want to store the name of a Dog in Java, we would have first to declare that it’s going to be of type string and then give our variable a name, doggie

String doggie = "Champ";
System.out.println(doggie);

When we run this code, we get “Champ” as our output. Since we’ve defined our variable as a type string, we can’t later decide to set this variable to a different type, like an integer. When we compile our program, we’ll receive an error because Java is a strict programming language. It doesn’t allow you to reassign data types in this way. But if we compare this to a more relaxed language like Python, we don’t need to declare a variable’s type before using it. 

doggie = "Champ"
print(doggie)

# Champ

Here, we declare the variable and use it at the same time. Notice how we only provide the name, not the type. But when we ran this code, the Python interpreter could figure out the type based on the value we provided. If we wanted to give a value of a different type, Python has no issues with that. It just figures it out and keeps on moving. There are pros and cons to both styles. The more relaxed languages tend to be more flexible and result in less code, whereas with more strict languages, you have fewer surprises when the code is run. Like all things in programming, there are a few rules that we have to follow when working with variables in Python. First, variable names should contain only letters, numbers, and underscores. Even though numbers are allowed, the name shouldn’t start with a number. 3rdeyeblind would not be a valid name, for instance. Second, spaces are not permitted in the name. Using an underscore to simulate a space like account_balance would be just fine. Third, it’s important to know that names are case-sensitive. Capital D Doggies is not the same as lowercase d doggies. Python considers them to be two different locations in memory. And finally, variables cannot be keywords. 

# Python program to print the list of all keywords
import keyword

# printing the keywords
print("Python keywords are...")
print(keyword.kwlist)

# ['False', 'None', 'True', 'and', 'as', 'assert', 'async', 'await', 'break',
# 'class', 'continue', 'def', 'del', 'elif', 'else', 'except', 'finally', 'for',
# 'from', 'global', 'if', 'import', 'in', 'is', 'lambda', 'nonlocal', 'not',
# 'or', 'pass', 'raise', 'return', 'try', 'while', 'with', 'yield']

Python, you can run the code snippet above to get a listing of all the keywords. You generally want to use short, descriptive names that make your code easy to understand. Naming things sound easy, but it can be challenging. It’s often cited as one of the most challenging problems in computer science. 

Working With Python Numbers

We use numbers to store a person’s high score in a game or even the number of likes on a picture. Python treats numbers differently depending on their use, and the difference is primarily based on whether it’s whole or fractional. Let’s look at a few examples.

addition = 2 + 2
subtraction = 2 - 2
multiplication = 2 * 2
division = 2 / 2
exponent = 2 ** 2
modulus = 2 % 2

print(addition)
print(subtraction)
print(multiplication)
print(division)
print(exponent)
print(modulus)

# 4
# 0
# 4
# 1.0
# 4
# 0

No matter how large the number is, we use no commas when working with Python. In some programming languages like JavaScript, There’s no distinction between numbers with and without decimal places. Whereas in most programming languages, numbers with decimal places are considered unique, numbers with decimal places are considered special, and they’re typically called floats. A float is any number with a decimal point.

# example of floats

float1 = 1.0
float2 = 25.8
float3 = 1.7
float4 = 7.1

A float is any number with a decimal point. It’s short for a floating-point number. Floats are used when more precision is required, like in the case of your account balance. You may notice lots of different decimal places when working with floats. Just ignore them for now.

Using Python Strings

In programming, we use strings when dealing with text like an email address or someone’s name. The name comes from the fact that it’s a string of characters one after the other. The characters can be letters, numbers, symbols, and even spaces. They’re typically represented by beginning and ending quotes. Programmers can pass strings directly to functions or be stored in variables. For example, we can use the print function in Python to display a message on the screen, like, “A beautiful sunrise!”.

print("A beautiful sunrise!")

# A beautiful sunrise!

Notice that we have the opening and closing double quotes. These let Python know it should print out the characters between the quotes just as we’ve typed them. We could also define a variable containing the exact string and get the same result. We could also use single quotes to create a string with Python. If you need to use a double quote inside your string, you can make the string using single quotes. If you would like to use a single quote inside of your string, then, in that case, you can use double quotes for the string. It is also possible to escape quotes inside of a defined string.

# single and double quotes python

print("How's it going?")
print('How\'s it going?')

print('That "sounds" fun')
print("That \"sounds\" fun")

In general, many Python developers prefer to use single quotes; however, there is a case where you’ll be forced to use double quotes, which is when you need to use a single quote as part of your string.

Correct Use Of Whitespace In Python

Python doesn’t care about extra empty lines in your programs, just like most languages. It’s common for developers to add additional blank lines, also known as white space. You can think of it kind of like paragraphs in a book. When things are squished together, you might find it challenging to figure out what the code will do.

import random
import math
lower = int(input("Enter Lower bound:- "))
upper = int(input("Enter Upper bound:- "))
x = random.randint(lower, upper)
print("You only have",
      round(math.log(upper - lower + 1, 2)),
      " chances to guess the number!\n")
count = 0
while count < math.log(upper - lower + 1, 2):
    count += 1
    guess = int(input("Guess a number:- "))
    if x == guess:
        print("Congratulations you did it in ",
              count, " attempts")
        break
    elif x > guess:
        print("You guessed too low!")
    elif x < guess:
        print("You Guessed too high!")
if count >= math.log(upper - lower + 1, 2):
    print("\nThe number is %d" % x)
    print("\tBetter Luck Next time!")

The code above runs just fine, but it may be a little tricky to read without using whitespace to give us a visual hint. The code below uses whitespace, blank lines, and comments to offer a more user-friendly code-reading experience.

import random
import math

# set the lower and upper bounds for the random number
lower = int(input("Enter Lower bound:- "))
upper = int(input("Enter Upper bound:- "))
x = random.randint(lower, upper)

# tell user how many guesses they have left
print("You only have",
      round(math.log(upper - lower + 1, 2)),
      " chances to guess the number!\n")

# initialize the number of guesses
count = 0

# use a loop to count the number of guesses
while count < math.log(upper - lower + 1, 2):
    count += 1

    # ask user for their guess
    guess = int(input("Guess a number:- "))

    # if the guess is correct, tell the user and break the loop
    if x == guess:
        print("Congratulations you did it in ",
              count, " attempts")
        break

    elif x > guess:
        print("You guessed too low!")
        
    elif x < guess:
        print("You Guessed too high!")

# if the user runs out of guesses, tell them what the number was
if count >= math.log(upper - lower + 1, 2):
    print("\nThe number is %d" % x)
    print("\tBetter Luck Next time!")

Using Python Comments

Comments are notes to your future self and others to describe what your code does. Right now, we have small programs. We can keep the flow of it all in our heads, but as you continue to grow your programming skills, you’ll be writing much longer programs. Some may even be thousands of lines of code spread over dozens of files. It would be impossible to keep all of that in your head. By adding comments to your code, you can document the purpose of the different variables, functions, and classes. You can think of them as virtual sticky notes. The code above is an excellent example of how to use comments in Python code. Comments are started with hash marks. When Python sees a hash mark, it knows it can ignore the rest of the line. The comments do not impact the output of our code. Besides serving as reminders, we can also use comments to help temporarily ignore some code. Programmers use this technique all of the time. It’s called commenting out code. Instead of just deleting lines of code, we can comment them out.