Difference between revisions of "Python"

Variables

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:

`int some_number;`

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```
Operators

There are a wide variety of operation that you can perform on integers and floats. Listed below are the most used operators.

Character Operator Example
`a = 12 + 14.3 # Returns 26.5`
- Subtraction
`a = 2 - 2.9 # Returns -0.9`
* Multiplication
`a = 4 * 1.5 # Returns 6`
/ Division
`a = 9 / 3 # Returns 3`
% Modulus
`a = 7 % 3 # Returns 1`
Returns integer the integer
remainder after division
// Floor division
`a = 8 // 3 # Returns 2`
Rounds down after division

Booleans

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

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\`
Operators

Operations on string are more limited than floats and integers.

Character Operator Example
`a = "Hello" + " " + "World" # Returns "Hello World"`
* Multiplication
`a = "ha" * 4 # Returns "hahahaha"`

String concatenation is accomplished by using the addition operator. Concatenation only sticks the strings together, any spaces, tabs or special characters you will need to add yourself.

Lists

Lists are just a collection of other types of variables. Lists can contain any other variable, be it a number, string or another list.

```# Declaring an emptry list
a: list = []

# Declaring and initializing a list
# Values in a list are comma separated
a: list = ["Hello", "World", 15, 19.6, True]```

Tuples

Tuples are lists that can not be changed after they have be declared. They are often used when returning multiple values from functions, and unlike lists can be used as keys in dictionaries.

```# Values in a tuple are comma separated
a: tuple = ("Hello", "World", 15, 19.6, True)```

Sets

A set is a list that cannot contain duplicate values. The order of the items in a set are also not consistent. Sets can be changed after being created.

```# Declaring an empty set
a: set = set()

# Declaring and initializing a set
a: set = {"Hello", "World", 15, 19.6, True}```

Dictionaries

Dictionaries consist of key - value pairs. A key value is associated with a corresponding value. A key can be an integer, float, string or tuple. A dictionary cannot contain duplicate keys. The value can be of any data type. A key and value are separated by a colon. Different key - value pairs are separated by commas.

```# Declaring an empty dictionary
a: dict = {}

# Declaring and initializing a dictionary
a: dict = {"A": "Hello", "B": "World", "C": 15, "D": 19.6, "E": True}```

Indexing and Slicing

Indexing

Accessing a specific value in a list or tuple, or returning a specific character from a string requires an index. The first value in a list or tuple, or the first character in a string is referred to as index 0. Some language start indexing at 1, by they are few and far between.

Accessing values are done using square brackets "[ ]":

```# Lists and tuples work the exactly the same
a: list = ["Hello", "World", 15, 19.6, True]
b = a[0] # b is equal to "Hello"
b = a[2] # b is equal to the 3rd element in list a: 15

# Strings are just lists of characters
a: str = "Hello"
b = a[0] # b is equal to "H"
b = a[2] # b is equal to the 3rd character in string a: "l"```

Values in dictionaries are returned by using the key.

```a: dict = {"A": "Hello", "B": "World", "C": 15, "D": 19.6, "E": True}
b = a["A"] # b is equal to "hello"
b = a["D"] # b is equal to 19.6```

Slicing

If you want more than one value from a list/tuple or string then can you make use of slicing. Slicing is done by specifying a start and stop index, separated by a colon. The values are returned as the same type of variable. Start index is included and stop index excluded (Mathematically writen as [x,y) ).

```a: list = ["Hello", "World", 15, 19.6, True]
# b is equal to the list a from position 0 to 3, excluding 3 -> index 0,1 and 2
# b is equal to a list ["Hello", "World", 15]
b = a[0:3]

# c is equal to the list a from position 1 to 3, excluding 3 -> index 1 and 2
# b is equal to a list ["World", 15]
c = a[1:3]```

If a start or stop index is left out then it is implied that is start index is the very start of the list/string or that the stop index is the very end of the list/string. This is useful when you do not know ahead of time how long the list/string is going to be.

```a: list = ["Hello", "World", 15, 19.6, True]
# b is equal to the list a from the start to 3, excluding 3 -> index 0,1 and 2
# b is equal to a list ["Hello", "World", 15]
b = a[:3]

# c is equal to the list a from position 1 to the end -> index 1, 2, 3 and 4
# c is equal to a list ["World", 15]
c = a[1:]```