RHHS Compsci 2016
Don’t skip these!
In Python, the type of variable you create depends on the type of data you initialized it with.
Below are some basic variable types we should tell you about:
>Integer (ex. noOfCarrots = 5)
These can store both positive and negative whole numbers. You cannot store numbers with
fractions or decimals as an integer. An advantage of using integers is that they take up less
memory in the system.
>Float (ex. lengthOfBridge = 12.33)
These are numbers written with decimals and fractions. If you know your variable might need
to store more than just whole numbers, then initialize your variable with a decimal (ex.
money = 5.0 as opposed to money = 5) to create a float. The disadvantage of floats to integers
is that they use more memory.
>String (ex. nameOfPet = “Delicious Food” or phoneNumber = “911”)
These store sets of characters including letters, spaces, punctuation and numbers you don’t
intend on performing arithmetic on. Think of it as the actual text in your program. When
assigning a string, make sure to place quotation marks around it to distinguish it from
>Boolean (ex. shouldSuspend = False)
These store only True or False values. They use the least amount of memory.
Be careful about variable types; you might end up with some funky data if you’re not. For
instance, example = 9 + 10 will get you 19, while example = “9” + “10” will get you “910”. This
is because in the first example, Python considers the values of the integers, while the second
has Python consider the characters themselves.
Sometimes, you may want to change one variable type into another. Let’s say you have “4” as a
string, but you want the number 4 to do math with. Changing variable types from one to
another is called casting. To cast, you simply put the variable in a cast function: numberString
= “4” then number = int(numberString). str(x) and float(x) do similar things but changing to a
different variable type.
Casting is very powerful, but you have to be careful when you cast! Let’s say you have the
following: name = “Vince” then you try to do number = int(name), you will have an error.
You may not want a single comparison to determine the results of your code. As such, you
may also use these operators in conditions: