Difference between revisions of "Python"

From Centre for Bioinformatics and Computational Biology
Jump to: navigation, search
(Variables)
(Indexing and Slicing)
Line 140: Line 140:
  
 
=== Indexing and Slicing ===
 
=== 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>

Revision as of 09:58, 20 June 2019

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
+ Addition
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
+ Addition
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