Difference between revisions of "Python"

From Centre for Bioinformatics and Computational Biology
Jump to: navigation, search
(Variables)
(Conditionals)
 
(22 intermediate revisions by the same user not shown)
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:
+
==== Declaration and typing ====
 +
'''Keyword:''' Declaring variables, variable assignment, boolean values, integers, floats, strings, lists, dictionaries (ordered dictionaries, default dictionaries), tuples, sets, mutable and immutable data types, variable typing.
 +
<source lang="python">
 +
####
 +
# Boolean variables can only contain one of two values: True or False
 +
#    Boolean values are annotated by using the "bool" keyword
 +
a: bool = True
 +
####
  
<source lang="java">
+
####
int some_number;
+
# Integers are variables that contain any positive or negative whole number
</source>
+
#    Integers are annotated using the "int" keyword
 +
# Floats are variables that contains any positive or negative decimal
 +
#    Floats are annotated using the "float" keyword
 +
a: int = 15
 +
b: int = -23
  
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.
+
c: float = 6.4
 +
d: float = -9.5
 +
####
  
It is thus recommended that you type variables. An example of typing in python:
+
####
<source lang="python">
+
# Strings are variables that contain text
def some_function(x: int) -> float:
+
#    Strings are annotated using the "str" keyword
    return x / 3.2
+
a: str = "This is a string"
</source>
+
b: str = 'Strings can be enclosed using single quotes'
  
==== Integers and Floats ====
+
# Initializing an empty string:
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.
+
a = ""
 +
####
  
Assigning a value to an integer or float looks as follow:
+
####
<source lang="python">
+
# Lists are collections of other variables
# The only difference between assigning to a float and an integer is
+
#     Lists are annotated using the "list" keyword
# whether or not the number has a decimal
+
a: list = ["Some string", 15, 9.6, True]
a: int = 2
+
b: float = 2.0
+
</source>
+
  
===== Operators =====
+
# Initializing an empty list:
There are a wide variety of operation that you can perform on integers and floats. Listed below are the most used operators.
+
a = []
{| 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".
+
# Sets are lists that cannot contain duplicate values
 +
# They also do not keep the order of the variables
 +
# Sets are a lot faster than lists when looking for specific values
 +
#    Sets are annotated using the "set" keyword
 +
a: set = {"Some string", 15, 9.6, True}
  
Declaring a boolean is as easy as assigning either Trye or False to a variable:
+
# Initializing an empty set:
<source lang="python">
+
a = set()
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.
+
# Tuples are lists that cannot be changed after being created
 +
# They are useful when returning multiple values from a function
 +
#    Tuples are annotated using the "tuple" keyword
 +
a: tuple = ("Some string", 15, 9.6, True)
  
<source lang="python">
+
# Because tuples cannot be changed there is no point in initializing an empty one
# Initializing an empty string
+
####
a: str = ""
+
 
 +
####
 +
# Dictionaries work of Key - Value pairs
 +
# Keys can be any immutable type - integers, floats, strings and tuples
 +
# Dictionaries do not keep the their order
 +
#    Dictionaries are annotated using the "dict" keyword
 +
a: dict = {"A": "Some string", "B": 15, "C": 9.6, "D": True}
  
# Initializing a string with text
+
# Initializing an empty dictionary:
b: str = "Your text goes here"
+
a = {}
 +
####
 
</source>
 
</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
+
==== Casting ====
 +
'''Keywords:''' Casting
 
<source lang="python">
 
<source lang="python">
# When printed to console it will display as It's cold today
+
# Only certain operations can be performed on certain types of variables
a: str = "It's cold today"
+
# Changing between types of variables is called "casting"
 +
a: str = "15"
  
# When printed to console it will display as Me: "Hey"
+
b: int = int(a)    # b = 15
a: str = 'Me: "Hey"'
+
c: float = float(b) # c = 15.0
 +
d: str = str(c)    # d = "15.0"
 
</source>
 
</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"
+
==== Mathematical operations ====
 +
'''Keywords:''' Operators, string concatenation, list concatenation
 
<source lang="python">
 
<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:
+
# Integers and floats support most arithmetic operations
# My name is:
+
a = 15
# My surname is:
+
b = 6
</source>
+
  
If you want to use the backslash character in a string then you need to escape it using another backslash
+
c = a + b # c = 21
<source lang="python">
+
c = a - b # c = 9
a: str = "D:\\User\\Documents\\" # Returns D:\User\Documents\
+
c = a * b # c = 90
</source>
+
c = a / b # c = 2.5
  
===== Operators =====
+
# There are some special operators:
Operations on string are more limited than floats and integers.
+
# modulus (%) returns what is left after division
{| class="wikitable" style="text-align: left;"
+
# floor division (//) throws away the decimal place
! Character
+
c = a % b  # c = 3
! Operator
+
c = a // b # c = 2
! 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.
+
####
 +
# Strings only support 2 mathematical operators
 +
# The addition (+) is used to concatenate strings
 +
# The multiplication (*) returns multiples of a string
 +
a = "Hello"
 +
b = "World"
  
==== Lists ====
+
c = a + b # c = "HelloWorld"
Lists are just a collection of other types of variables. Lists can contain any other variable, be it a number, string or another list.
+
c = a * 3 # c = "HelloHelloHello"
<source lang="python">
+
####
# Declaring an emptry list
+
a: list = []
+
  
# Declaring and initializing a list
+
####
# Values in a list are comma separated
+
# Lists, tuples can be added to each other
a: list = ["Hello", "World", 15, 19.6, True]
+
# It concatenates the collections together
</source>
+
a = ["Hello", 15]
 +
b = [9.6, True]
  
==== Tuples ====
+
c = a + b # c = ["hello", 15, 9.6, True]
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)
+
# You can use "mathematical shorthand" to make some code more readable
 +
# Shorthand is supported for all operators and works with strings, numbers, lists and tuples
 +
a = 12
 +
b = "Hello"
 +
c = "World"
 +
 
 +
a = a + 6 # Normal way
 +
a += 6    # Shorthand gives the same result
 +
 
 +
b = b + c # Normal way, c = "HelloWorld"
 +
b += c    # Shorthand gives the same result
 +
####
 
</source>
 
</source>
  
==== Sets ====
+
==== Modifying collections ====
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.
+
'''Keywords:''' Collections, lists, tuples, dictionaries, sets
 
<source lang="python">
 
<source lang="python">
# Declaring an empty set
+
####
a: set = set()
+
# LISTS
 +
# You can add values to a list by using the append() method:
 +
a = []
  
# Declaring and initializing a set
+
a.append("Hello")
a: set = {"Hello", "World", 15, 19.6, True}
+
a.append(15)
 +
a.append(True)
 +
 
 +
print(a) # a = ["Hello", 15, True]
 +
####
 +
 
 +
####
 +
# SETS
 +
# You can add values to a list by using the add() method
 +
# A list of values can be added to a set by using the update() method
 +
a = set()
 +
b = [15, 9.6, True]
 +
 
 +
a.add("Hello")
 +
a.update(b)
 +
 
 +
print(a) # a = {"Hello", 15, 9.6, True}
 +
####
 +
 
 +
####
 +
# TUPLES
 +
# Tuples cannot be added to, they do not change
 +
####
 +
 
 +
####
 +
# DICTIONARIES
 +
# You can add a new value pair by assigning the key to a value
 +
a = {}
 +
 
 +
a["A"] = "Hello"
 +
a["B"] = 15
 +
a["C"] = 9.6
 +
a["D"] = True
 +
 
 +
print(a) # a = {"A": "Hello", "B": 15, "C": 9.6, "D": True}
 +
####
 
</source>
 
</source>
  
==== Dictionaries ====
+
=== Conditionals ===
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.
+
'''Keywords:''' Logical operators, and, or, not, in, if statement, if else, else if, try catch blocks, exception handling.
 +
==== If statement ====
 
<source lang="python">
 
<source lang="python">
# Declaring an empty dictionary
+
# If statements are used when you want to do something when a condition is met
a: dict = {}
+
# The if or elif part occurs when the condition returns true
 +
# The else part occurs when none of the previous conditions returned true
 +
a = 12
 +
b = 15
  
# Declaring and initializing a dictionary
+
# The example below will return "Did the elif" because b > a
a: dict = {"A": "Hello", "B": "World", "C": 15, "D": 19.6, "E": True}
+
if a > b:
 +
    print("Did the if")
 +
elif b > a: # Condition returns true
 +
    print("Did the elif")
 +
else:
 +
    print("Did the else")
 +
 
 +
# The operators available:
 +
# > < >= <= ==
 +
# != (not equal) can be used or the keyword "not"
 +
 
 +
# If you want to create more complex conditions you can make use of "and", "or" and "in"
 +
# And requires that all conditionals return true
 +
# Or requires that one of the conditionals return true
 +
# In returns true if a certain value is found inside a collection
 +
a = [15, 9, 6]
 +
b = 6
 +
 
 +
if 15 in a:
 +
    print("Found it")
 +
 
 +
# Would not run the code inside the if statement
 +
if (15 in a) and (b > 9):
 +
    print("The item is in the list and 6 > 9")
 +
 
 +
# Would run the code inside the if statement
 +
if (15 in a) or (b > 9):
 +
    print("The item is in the list or 6 > 9?")
 +
 
 +
# You can have calculations and function calls inside conditions:
 +
if (15 + 2) > b:
 +
    print("17 > 6")
 
</source>
 
</source>
  
=== Indexing and Slicing ===
+
==== Try except ====
 +
 
 +
=== Loops ===
 +
=== Functions ===
 +
=== Classes ===

Latest revision as of 06:46, 28 June 2019

Variables

Declaration and typing

Keyword: Declaring variables, variable assignment, boolean values, integers, floats, strings, lists, dictionaries (ordered dictionaries, default dictionaries), tuples, sets, mutable and immutable data types, variable typing.

####
# Boolean variables can only contain one of two values: True or False
#     Boolean values are annotated by using the "bool" keyword
a: bool = True
####
 
####
# Integers are variables that contain any positive or negative whole number
#     Integers are annotated using the "int" keyword
# Floats are variables that contains any positive or negative decimal
#     Floats are annotated using the "float" keyword
a: int = 15
b: int = -23
 
c: float = 6.4
d: float = -9.5
####
 
####
# Strings are variables that contain text
#     Strings are annotated using the "str" keyword
a: str = "This is a string"
b: str = 'Strings can be enclosed using single quotes'
 
# Initializing an empty string:
a = ""
####
 
####
# Lists are collections of other variables
#     Lists are annotated using the "list" keyword
a: list = ["Some string", 15, 9.6, True]
 
# Initializing an empty list:
a = []
####
 
####
# Sets are lists that cannot contain duplicate values
# They also do not keep the order of the variables
# Sets are a lot faster than lists when looking for specific values
#    Sets are annotated using the "set" keyword
a: set = {"Some string", 15, 9.6, True}
 
# Initializing an empty set:
a = set()
####
 
####
# Tuples are lists that cannot be changed after being created
# They are useful when returning multiple values from a function
#     Tuples are annotated using the "tuple" keyword
a: tuple = ("Some string", 15, 9.6, True)
 
# Because tuples cannot be changed there is no point in initializing an empty one
####
 
####
# Dictionaries work of Key - Value pairs
# Keys can be any immutable type - integers, floats, strings and tuples
# Dictionaries do not keep the their order
#     Dictionaries are annotated using the "dict" keyword
a: dict = {"A": "Some string", "B": 15, "C": 9.6, "D": True}
 
# Initializing an empty dictionary:
a = {}
####

Casting

Keywords: Casting

# Only certain operations can be performed on certain types of variables
# Changing between types of variables is called "casting"
a: str = "15"
 
b: int = int(a)     # b = 15
c: float = float(b) # c = 15.0
d: str = str(c)     # d = "15.0"

Mathematical operations

Keywords: Operators, string concatenation, list concatenation

####
# Integers and floats support most arithmetic operations
a = 15
b = 6
 
c = a + b # c = 21
c = a - b # c = 9
c = a * b # c = 90
c = a / b # c = 2.5
 
# There are some special operators:
# modulus (%) returns what is left after division
# floor division (//) throws away the decimal place
c = a % b  # c = 3
c = a // b # c = 2
####
 
####
# Strings only support 2 mathematical operators
# The addition (+) is used to concatenate strings
# The multiplication (*) returns multiples of a string
a = "Hello"
b = "World"
 
c = a + b # c = "HelloWorld"
c = a * 3 # c = "HelloHelloHello"
####
 
####
# Lists, tuples can be added to each other
# It concatenates the collections together
a = ["Hello", 15]
b = [9.6, True]
 
c = a + b # c = ["hello", 15, 9.6, True]
####
 
####
# You can use "mathematical shorthand" to make some code more readable
# Shorthand is supported for all operators and works with strings, numbers, lists and tuples
a = 12
b = "Hello"
c = "World"
 
a = a + 6 # Normal way
a += 6    # Shorthand gives the same result
 
b = b + c # Normal way, c = "HelloWorld"
b += c    # Shorthand gives the same result
####

Modifying collections

Keywords: Collections, lists, tuples, dictionaries, sets

####
# LISTS
# You can add values to a list by using the append() method:
a = []
 
a.append("Hello")
a.append(15)
a.append(True)
 
print(a) # a = ["Hello", 15, True]
####
 
####
# SETS
# You can add values to a list by using the add() method
# A list of values can be added to a set by using the update() method
a = set()
b = [15, 9.6, True]
 
a.add("Hello")
a.update(b)
 
print(a) # a = {"Hello", 15, 9.6, True}
####
 
####
# TUPLES
# Tuples cannot be added to, they do not change
####
 
####
# DICTIONARIES
# You can add a new value pair by assigning the key to a value
a = {}
 
a["A"] = "Hello"
a["B"] = 15
a["C"] = 9.6
a["D"] = True
 
print(a) # a = {"A": "Hello", "B": 15, "C": 9.6, "D": True}
####

Conditionals

Keywords: Logical operators, and, or, not, in, if statement, if else, else if, try catch blocks, exception handling.

If statement

# If statements are used when you want to do something when a condition is met
# The if or elif part occurs when the condition returns true
# The else part occurs when none of the previous conditions returned true
a = 12
b = 15
 
# The example below will return "Did the elif" because b > a
if a > b:
    print("Did the if")
elif b > a: # Condition returns true
    print("Did the elif")
else:
    print("Did the else")
 
# The operators available:
# > < >= <= ==
# != (not equal) can be used or the keyword "not"
 
# If you want to create more complex conditions you can make use of "and", "or" and "in"
# And requires that all conditionals return true
# Or requires that one of the conditionals return true
# In returns true if a certain value is found inside a collection
a = [15, 9, 6]
b = 6
 
if 15 in a:
    print("Found it")
 
# Would not run the code inside the if statement
if (15 in a) and (b > 9):
    print("The item is in the list and 6 > 9")
 
# Would run the code inside the if statement
if (15 in a) or (b > 9):
    print("The item is in the list or 6 > 9?")
 
# You can have calculations and function calls inside conditions:
if (15 + 2) > b:
    print("17 > 6")

Try except

Loops

Functions

Classes