Operator | Name | Description |
---|---|---|
a + b |
Addition | Sum of a and b |
a - b |
Subtraction | Difference of a and b |
a * b |
Multiplication | Product of a and b |
a / b |
True division | Quotient of a and b |
a // b |
Floor division | Quotient of a and b , removing fractional parts |
a % b |
Modulus | Integer remainder after division of a by b |
a ** b |
Exponentiation | a raised to the power of b |
-a |
Negation | The negative of a |
+a |
Unary plus | a unchanged (rarely used) |
# addition, subtraction, multiplication
print((4 + 8) * (6.5 - 3))
# Division
print(11 / 2)
a = 24
print(a)
a = a + 2
print(a)
print(a + 2)
a += 2 # equivalent to a = a + 2
print(a)
Operation | Description |
---|---|
a == b |
a equal to b |
a < b |
a less than b |
a <= b |
a less than or equal to b |
a != b |
a not equal to b |
a > b |
a greater than b |
a >= b |
a greater than or equal to b |
print(22 / 2 == 10 + 1)
# 25 is even
print(25 % 2 == 0)
# 66 is odd
print(66 % 2 == 0)
# check if a is between 15 and 30
a = 25
print(15 < a < 30)
x = 4
print((x < 6) and (x > 2))
print((x > 10) or (x % 2 == 0))
print(not (x < 6))
Operator | Description |
---|---|
a in b |
True if a is a member of b |
a not in b |
True if a is not a member of b |
print(1 in [1, 2, 3])
print(2 not in [1, 2, 3])
Type | Example | Description |
---|---|---|
int |
x = 1 |
integers (i.e., whole numbers) |
float |
x = 1.0 |
floating-point numbers (i.e., real numbers) |
complex |
x = 1 + 2j |
Complex numbers (i.e., numbers with real and imaginary part) |
bool |
x = True |
Boolean: True/False values |
str |
x = 'abc' |
String: characters or text |
NoneType |
x = None |
Special object indicating nulls |
5 / 2
# Floor division
5 // 2
The floor division operator was added in Python 3; you should be aware if working in Python 2 that the standard division operator (
/
) acts like floor division for integers and like true division for floating-point numbers.
x = 0.000005
y = 5e-6
print(x == y)
print(0.1 + 0.2 == 0.3)
Floating-point precision is limited, which can cause equality tests to be unstable
message = "what do you like?"
print(message)
response = 'spam'
print(response)
# length of string
print(len(response))
# Make upper-case. See also str.lower()
print(response.upper())
# Capitalize. See also str.title()
print(message.capitalize())
# concatenation with +
print(message + response)
# multiplication is multiple concatenation
print(5 * response)
# Access individual characters (zero-based indexing)
print(message[0])
# index range is checked
print(message[59])
a = 32423
print('el valor de a es ', a)
print(f'a vale {a}')
valor = input('introduce una cadena')
print('la candena introducida es ', valor)
result = (4 < 5)
print(result)
True
andFalse
must be capitalized!
Leap years can be ignored
# How many hours are in a year?
print(24 * 365)
# How many minutes are in a decade?
print(60 * 24 * (365 * 10))
# How many seconds old are you?
print(60 * 60 * 24 * (365 * 23))
Type Name | Example | Description |
---|---|---|
list |
[1, 2, 3] |
Ordered collection |
tuple |
(1, 2, 3) |
Immutable ordered collection |
dict |
{'a': 1, 'b': 2, 'c': 3} |
Unordered (key,value) mapping (ordered in Python 3.7+) |
set |
{1, 2, 3} |
Unordered collection of unique values |
l = [2, 3, 5, 7]
# Length of a list
print(len(l))
# Append a value to the end
l.append(11)
print(l)
# Addition concatenates lists
print(l + [13, 17, 19])
# sort() method sorts in-place
l = [2, 5, 1, 6, 3, 4]
l.sort()
print(l)
l = [1, 'two', 3.14, [0, 3, 5]]
print(l)
l = [2, 3, 5, 7, 11]
print(l[0])
print(l[1])
print(l[-1])
print(l[0:3])
print(l[:3])
print(l[::2]) # equivalent to l[0:len(l):2]
l[0] = 100
print(l)
t = (1, 2, 3)
print(t)
t = 1, 2, 3
print(t)
print(len(t))
print(t[0])
t[1] = 4
t.append(4)
numbers = {'one': 1, 'two': 2, 'three': 3}
# Access a value via the key
print(numbers['two'])
# Set a new key:value pair
numbers['ninety'] = 90
print(numbers)
numbers = {'one': 1, 'two': 2, 'three': 3}
- Albert Einstein - 03/14/1879
- Benjamin Franklin - 01/17/1706
- Ada Lovelace - 12/10/1815
- Donald Trump - 06/14/1946
- Rowan Atkinson - 01/6/1955
# Create a dictionary with the following birthday information
birthdays = {'Albert Einstein': '03/14/1879',
'Benjamin Franklin': '01/17/1706',
'Ada Lovelace': '12/10/1815',
'Donald Trump': '06/14/1946',
'Rowan Atkinson': '01/6/1955'}
# Check if Donald Trump is in our dictonary
print('Donald Trump' in birthdays)
# Get Albert Einstein's birthday
print(birthdays['Albert Einstein'])
if
-elif
-else
¶x = -15
if x == 0:
print(x, 'is zero')
elif x > 0:
print(x, 'is positive')
else:
print(x, 'is negative')
for
¶n = [2, 3, 5, 7]
for e in n:
print(e)
m = range(5) # m = [0, 1, 2, 3, 4]
for i in m:
print('hola')
Please avoid Matlab-like for statements with range
n = [2, 3, 5, 7]
for e in range(len(n)):
print(n[e])
for a in n[:3]:
print(a)
while
¶i = 0
while i < 10:
print(i)
i += 1
Be careful with while loops
import time
def cabecera():
mensaje = 'Este programa está escrito por Juan Gómez'
mensaje += '. Copyright ' + time.strftime('%d-%m-%Y')
return mensaje
print(cabecera())
def cabecera_mejorada(autor):
mensaje = 'Este programa está escrito por '
mensaje += autor
mensaje += '. Copyright ' + time.strftime('%d-%m-%Y')
return mensaje
print(cabecera_mejorada('Juan Gómez'))
print(cabecera_mejorada('Alfonso Hernández'))
def fibonacci(n):
l = []
a = 0
b = 1
while len(l) < n:
l.append(a)
c = a + b
a = b
b = c
return l
print(fibonacci(10))
print(fibonacci(3))
def fibonacci(n, start=0):
l = []
a = 0
b = 1
while len(l) < n:
if a >= start:
l.append(a)
c = a + b
a = b
b = c
return l
print(fibonacci(10))
print(fibonacci(10, 5))
## Keyword arguments
print(fibonacci(start=5, n=10))
def fibonacci(n, start=0):
"""Build a Fibonacci series with n elements starting at start
Args:
n: number of elements
start: lower limit. Default 0
Returns:
A list with a Fibonacci series with n elements
"""
l = []
a = 0
b = 1
while len(l) < n:
if a >= start:
l.append(a)
c = a + b
a = b
b = c
return l
Example input: "cool" output: "looc"
A mutation is simply a mistake that occurs during the creation or copying of a nucleic acid, in particular DNA.
Because nucleic acids are vital to cellular functions, mutations tend to cause a ripple effect throughout the cell.
Although mutations are technically mistakes, a very rare mutation may equip the cell with a beneficial attribute.
In fact, the macro effects of evolution are attributable by the accumulated result of beneficial microscopic mutations over many generations.
The simplest and most common type of nucleic acid mutation is a point mutation, which replaces one base with another at a single nucleotide.
By counting the number of differences between two homologous DNA strands taken from different genomes with a common ancestor, we get a measure of the minimum number of point mutations that could have occurred on the evolutionary path between the two strands.
This is called the 'Hamming distance'.
It is found by comparing two DNA strands and counting how many of the nucleotides are different from their equivalent in the other string.
Example:
GAGCCTACTAACGGGAT
CATCGTAATGACGGCCT
^ ^ ^ ^ ^ ^^
Given a number, determine if it is prime
Given a number, determine what the nth prime is
# Reverse a string
cadena1 = 'cool'
cadena2 = ''
for c in cadena1[-1::-1]:
cadena2 = cadena2 + c
print(cadena2)
cadena1 = 'hola mundo'
cadena2 = ''
for c in cadena1[-1::-1]:
cadena2 = cadena2 + c
print(cadena2)
cadena = 'cool'
def invertir_cadena(cadena_entrada):
cadena_salida = ''
for c in cadena_entrada[-1::-1]:
cadena_salida += c
return cadena_salida
print(invertir_cadena(cadena))
print(invertir_cadena('Hola mundo'))
# Hamming distance
c1 = 'GAGCCTACTAACGGGAT'
c2 = 'CATCGTAATGACGGCCT'
def hamming(dna_1, dna_2):
l = len(dna_1)
hamming = 0
for i in range(l):
if dna_1[i] != dna_2[i]:
hamming += 1
return hamming
print(hamming(c1, c2))
print(hamming('TAGAG', 'TAGAA'))
# Prime number
number = 4
def is_prime(number):
is_prime = True
for x in range(2, number):
if (number % x) == 0:
is_prime = False
return is_prime
is_prime(number)
# Nth Prime
def n_prime(nth):
n = 2
primes = []
while len(primes) < nth:
if is_prime(n):
primes.append(n)
n += 1
return primes[-1]
print(n_prime(6))
print(n_prime(1))
import
Statement¶import functions # without .py extension
print(functions.fibonacci(5))
import functions as f
print(f.fibonacci(5))
from functions import fibonacci
print(fibonacci(5))
The best way to import libraries is included in their official help
import math
import numpy as np
from scipy import linalg, optimize
import pandas as pd
import matplotlib as mpl
import matplotlib.pyplot as plt
import sympy
It is very conservative and requires limiting lines to 79 characters. We use all lines to a maximum of 119 characters. This is the default behaviour in PyCharm.
Skip validation in one line by adding following comment:
# nopep8
import numpy as np
x = np.arange(1, 10)
print(x)
print(x ** 2)
y = x.reshape((3, 3))
y
print(y.T)
a = np.array([[1, 0], [0, 1]])
b = np.array([[4, 1], [2, 2]])
print(np.dot(a, b))
Arrays enable you to express batch operations on data without writing any for loops. This is usually called vectorization:
But:
sometimes it's difficult to move away from the for-loop school of thought
import pandas as pd
df = pd.DataFrame({'label': ['A', 'B', 'C', 'A', 'B', 'C'],
'value': [1, 2, 3, 4, 5, 6]})
print(df)
print(df['label'])
print(df['value'].sum())
print(df.groupby('label').sum())
import matplotlib.pyplot as plt
x = np.linspace(0, 10) # range of values from 0 to 10
y = np.sin(x) # sine of these values
plt.plot(x, y); # plot as a line
scipy.fftpack
: Fast Fourier transformsscipy.integrate
: Numerical integrationscipy.interpolate
: Numerical interpolationscipy.linalg
: Linear algebra routinesscipy.optimize
: Numerical optimization of functionsscipy.sparse
: Sparse matrix storage and linear algebrascipy.stats
: Statistical analysis routinesfrom IPython.display import display
from sympy import symbols
# Pretty printing
from sympy import init_printing
init_printing()
x, y = symbols('x y')
expr = x + 2*y
display(expr)
Derivative of $$sin(x)e^x$$
from sympy import diff, sin, exp, pprint
out = diff(sin(x)*exp(x), x)
display(out)
Compute $$\int(e^x\sin{(x)} + e^x\cos{(x)})\,dx$$
from sympy import integrate, cos
out = integrate(exp(x) * sin(x) + exp(x) * cos(x), x)
display(out)