Difference between revisions of "Python"

From Centre for Bioinformatics and Computational Biology
Jump to: navigation, search
(Integers and Floats)
(Conditionals)
 
(34 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 it 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
 +
####
 +
 
 +
####
 +
# 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}
  
<source lang="java">
+
# Initializing an empty dictionary:
int some_number;
+
a = {}
 +
####
 
</source>
 
</source>
  
Many scripting languages, like python, are weakly or loosely type. This means that you are not required to asign a type to a variable when you create this. Variable can also easily change types. This makes the language extremely flexible, but it become easy to get confused with what type a variable is.
+
==== Casting ====
 +
'''Keywords:''' Casting
 +
<source lang="python">
 +
# Only certain operations can be performed on certain types of variables
 +
# Changing between types of variables is called "casting"
 +
a: str = "15"
  
It is thus recommended that you type variables. An example of typing in python:
+
b: int = int(a)    # b = 15
 +
c: float = float(b) # c = 15.0
 +
d: str = str(c)    # d = "15.0"
 +
</source>
 +
 
 +
==== Mathematical operations ====
 +
'''Keywords:''' Operators, string concatenation, list concatenation
 
<source lang="python">
 
<source lang="python">
some_number: int
+
####
 +
# 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
 +
####
 
</source>
 
</source>
  
==== Integers and Floats ====
+
==== Modifying collections ====
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.
+
'''Keywords:''' Collections, lists, tuples, dictionaries, sets
 +
<source lang="python">
 +
####
 +
# LISTS
 +
# You can add values to a list by using the append() method:
 +
a = []
  
Assigning a value to an integer or float looks as follow:
+
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}
 +
####
 +
</source>
 +
 
 +
=== Conditionals ===
 +
'''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">
# The only difference between assigning to a float and an integer is
+
# If statements are used when you want to do something when a condition is met
# whether or not the number has a decimal
+
# The if or elif part occurs when the condition returns true
a: int = 2
+
# The else part occurs when none of the previous conditions returned true
b: float = 2.0
+
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")
 
</source>
 
</source>
  
===== Operators =====
+
==== Try except ====
  
==== Booleans ====
+
=== Loops ===
==== Strings ====
+
=== Functions ===
==== Lists ====
+
=== Classes ===
==== Tuples ====
+
==== Sets ====
+
==== Dictionaries ====
+

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