Variables allow you to store and change values based on certain conditions. In many low level languages like C, C++ and Java when declaring a variable it is required that you also specify of what type the variable will be. This type is then static and will never change. In java for example declaring a variable that will in the future store a number looks like this:
Many scripting languages, like python, are weakly or loosely typed. This means that you are not required to assign a type to a variable when you create it. This makes the language extremely flexible, but it become easy to get confused with what type a variable is, especially when passing them into functions and assigning function return values.
It is thus recommended that you type variables. An example of typing in python:
def some_function(x: int) -> float: return x / 3.2
Integers and Floats
Integers and floats are the default number data types in python. Integers are whole numbers, while floats are fraction, or number with decimals. Both integers and floats can be positive or negative.
Assigning a value to an integer or float looks as follow:
# The only difference between assigning to a float and an integer is # whether or not the number has a decimal a: int = 2 b: float = 2.0
There are a wide variety of operation that you can perform on integers and floats. Listed below are the most used operators.
a = 12 + 14.3 # Returns 26.5
a = 2 - 2.9 # Returns -0.9
a = 4 * 1.5 # Returns 6
a = 9 / 3 # Returns 3
a = 7 % 3 # Returns 1
| Returns integer the integer |
remainder after division
a = 8 // 3 # Returns 2
|Rounds down after division|
Bollean values are either one of two value: True or False. Booleans are mostly used in conditionals and in very rare cases as "switches".
Declaring a boolean is as easy as assigning either Trye or False to a variable:
a: bool = True b: bool = False
Strings are variables that contain text. Strings can contain any combination of alphanumerical characters and special characters. Strings are enclosed in either two single quotes or two double quotes.
# Initializing an empty string a: str = "" # Initializing a string with text b: str = "Your text goes here"
If you need a string that either contains a single or double quote then just enclose the string with the other type of quote
# When printed to console it will display as It's cold today a: str = "It's cold today" # When printed to console it will display as Me: "Hey" a: str = 'Me: "Hey"'
The backslash character is known as an escape character. It, in combination with other characters, are used to represent characters like a tab "\t", newline "\n" and carriage return "\r"
a: str = "My name is: \nMy surname is:" # The "\n" tells us that a new line should start there, the result is: # My name is: # My surname is:
If you want to use the backslash character in a string then you need to escape it using another backslash
a: str = "D:\\User\\Documents\\" # Returns D:\User\Documents\