Difference between revisions of "Python"

From Centre for Bioinformatics and Computational Biology
Jump to: navigation, search
(Slicing)
(Replaced content with "=== Variables === === Conditionals === === Loops === === Functions === === Classes ===")
Line 1: Line 1:
 
=== Variables ===
 
=== 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:
+
=== Conditionals ===
 
+
=== Loops ===
<source lang="java">
+
=== Functions ===
int some_number;
+
=== Classes ===
</source>
+
 
+
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:
+
<source lang="python">
+
def some_function(x: int) -> float:
+
    return x / 3.2
+
</source>
+
 
+
==== 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:
+
<source lang="python">
+
# 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
+
</source>
+
 
+
===== Operators =====
+
There are a wide variety of operation that you can perform on integers and floats. Listed below are the most used operators.
+
{| class="wikitable" style="text-align: left;"
+
! Character
+
! Operator
+
! Example
+
|-
+
| + || Addition || <source lang="python">a = 12 + 14.3 # Returns 26.5</source>
+
|-
+
| - || Subtraction || <source lang="python">a = 2 - 2.9 # Returns -0.9</source>
+
|-
+
| * || Multiplication || <source lang="python">a = 4 * 1.5 # Returns 6</source>
+
|-
+
| / || Division || <source lang="python">a = 9 / 3 # Returns 3</source>
+
|-
+
| % || Modulus || <source lang="python">a = 7 % 3 # Returns 1</source> || Returns integer the integer <br/> remainder after division
+
|-
+
| // || Floor division || <source lang="python">a = 8 // 3 # Returns 2</source> || 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:
+
<source lang="python">
+
a: bool = True
+
b: bool = False
+
</source>
+
 
+
==== 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.
+
 
+
<source lang="python">
+
# Initializing an empty string
+
a: str = ""
+
 
+
# Initializing a string with text
+
b: str = "Your text goes here"
+
</source>
+
 
+
If you need a string that either contains a single or double quote then just enclose the string with the other type of quote
+
<source lang="python">
+
# 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"'
+
</source>
+
 
+
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"
+
<source lang="python">
+
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:
+
</source>
+
 
+
If you want to use the backslash character in a string then you need to escape it using another backslash
+
<source lang="python">
+
a: str = "D:\\User\\Documents\\" # Returns D:\User\Documents\
+
</source>
+
 
+
===== Operators =====
+
Operations on string are more limited than floats and integers.
+
{| class="wikitable" style="text-align: left;"
+
! Character
+
! Operator
+
! Example
+
|-
+
| + || Addition || <source lang="python">a = "Hello" + " " + "World" # Returns "Hello World"</source>
+
|-
+
| * || Multiplication || <source lang="python">a = "ha" * 4 # Returns "hahahaha"</source>
+
|}
+
 
+
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.
+
<source lang="python">
+
# 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]
+
</source>
+
 
+
==== 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.
+
<source lang="python">
+
# Values in a tuple are comma separated
+
a: tuple = ("Hello", "World", 15, 19.6, True)
+
</source>
+
 
+
==== 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.
+
<source lang="python">
+
# Declaring an empty set
+
a: set = set()
+
 
+
# Declaring and initializing a set
+
a: set = {"Hello", "World", 15, 19.6, True}
+
</source>
+
 
+
==== 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.
+
<source lang="python">
+
# Declaring an empty dictionary
+
a: dict = {}
+
 
+
# Declaring and initializing a dictionary
+
a: dict = {"A": "Hello", "B": "World", "C": 15, "D": 19.6, "E": True}
+
</source>
+
 
+
=== 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 "[ ]":
+
<source lang="python">
+
# 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"
+
</source>
+
 
+
Values in dictionaries are returned by using the key.
+
<source lang="python">
+
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
+
</source>
+
 
+
==== 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) ).
+
 
+
<source lang="python">
+
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]
+
</source>
+
 
+
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.
+
 
+
<source lang="python">
+
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:]
+
</source>
+

Revision as of 13:26, 26 June 2019

Variables

Conditionals

Loops

Functions

Classes