User blog:Granpa/Python 3.6



I strongly recommend installing Anaconda (Python distribution). It comes with numpy and scipy preinstalled.

Anaconda also comes with Spyder which makes it much easier to find and correct errors.

Comments

 * 1) comments follow a pound sign

Sounds
To play a sound when your program is finished use:

import winsound duration = 1000 # milliseconds freq = 440 # hz winsound.Beep(freq,duration)

Time
To time your program use:

import time StartTime=time.time EndTime=time.time print ('Time in seconds:', EndTime-StartTime)
 * 1) put the rest of your program here

Exit
To exit your program at any point just use:

raise SystemExit

Math
3+5 =8 3-5 =-2 3*5 =15 3/5 = 0.6 5//3 = 1 # Floor -5//3 = -2 # (Rounding toward negative infinity) round(1.8) = 2 # (Rounding toward nearest integer) round(1.5) = 2 # (Rounding toward even) 3%5 = 3 # Mod 3**5 = 243 ~5 = -6 # -x-1 (Inverts bits) 1<<2 = 4 # (Shifts bits to the left) 4>>2 = 1 # (Shifts bits to the right)

Rounding towards negative infinity means that the equation  is always true and that the equation   is valid for both positive and negative values of.

Back to top

Variables


Back to top

Ordered lists
External link: https://rushter.com/blog/python-lists-and-tuples/

Back to top

Input and output
name = "john" age = 36 print(name, "is", age, "years old") # default separater is a single space. default end is new line print("this is printed on a new line") print("But we can change the def", "ault separator and default end", sep="", end="") print("This is not printed on a new line") print("a \t bx \t c \n 12345678901234567890") # \t is tab and \n is new line. print( r 'a\tbx\tc\n12345678901234567890') # r = raw text. Slashes are treated like ordinary text. your_input = input("please enter your input: ")

john is 36 years old this is printed on a new line But we can change the default separator and default endThis is not printed on a new line a      bx      c 12345678901234567890 a\tbx\tc\n12345678901234567890 please enter your input:

Back to top

Loops


for num in range(1000, 2000, 100): # range is an iterator not a list or array
 * print (num) # prints 1000 to 1900 in steps of 100

num = 0 while num < 100000000: # Thats 100,000,000. It runs in about 10 seconds
 * num = num + 1

Back to top

Conditional statements


young = age < 10

old = age > 65

middle_age = (45 < age < 65)

if young:                # dont forget the colon at the end
 * print (name, "is young")

elif old:
 * print (name, "is old")

elif middle_age:
 * pass # Do nothing

else:
 * print (name, "is neither young nor old nor middle age")

Back to top

Functions


def convert_to_celcius(fahrenheit):
 * """Converts fahrenheit to celcius""" # documentation that is printed out when we use help("convert_to_celcius")
 * return (fahrenheit-32)*5/9

print (convert_to_celcius(212))

Back to top

Importing modules
There is nothing fancy about a module. Its just a program containing function definitions. The program is executed when it is imported unless it was previously imported. You can easily create your own modules.

After importing a module you can use help("module name") to get info.
 * Template:Help("time")
 * Template:Help("math")

dir(module_name) # returns a list of all the functions in the module. Easier to read if converted to an array.

import time start = time.time time.sleep(15) # delay for 15 seconds end = time.time print(end - start) # time in seconds

import math x = math.sqrt(9) # x = sqrt(9) wont work. You must use math.sqrt

import math as mt x = mt.sqrt(9)

from math import sqrt x = sqrt(9) # no need for math.sqrt since sqrt has been imported into the current namespace

import random rand1 = random.randint(0,999999) # random integer between 0 and 999,999

Back to top

Classes
Tutorial

Calling methods is very similar to calling functions in a module. Instead of module.function(arguments) you use class.method(arguments).

str.capitalize("string") # returns the string with first letter capitalized

In a perfect world modules and classes would be the same thing because every module would correspond to exactly one class of object. But we dont live in that world.

type(any_object) # returns the class of the object

When we call a method, the object itself is passed as the first parameter (called "self").

class Person:
 * def __init__(self, name, birthday):
 * self.name = name
 * self.birthday = birthday


 * def age(self):
 * today = datetime.date.today
 * age = today.year - self.birthdate.year
 * return age

person1 = Person("Bill", datetime.date(1981, 12, 27) )

Back to top

Text files
with open("TextFile.txt", "r") as file:
 * contents = file.read

with open("TextFile.txt", "r") as file:
 * List_of_lines = file.readlines

with open("TextFile.txt", "w") as output_file:
 * output_file.write(contents)

Back to top

Database
Creating:

import sqlite3 con = sqlite3.connect('test.db') cur = con.cursor cur.execute('CREATE TABLE test(name TEXT, age INTEGER)') cur.execute('INSERT INTO test VALUES("John", 33)') cur.execute('INSERT INTO test VALUES("Alice", 21)') x=["Bob", 18] cur.execute('INSERT INTO test VALUES(?, ?)', x) con.commit # changes are not committed until this command cur.execute('SELECT * FROM test WHERE age > 5 ORDER BY name') whole_table = cur.fetchall print (whole_table) con.close

Updating"

import sqlite3 con = sqlite3.connect('test.db') cur = con.cursor cur.execute('DELETE FROM test WHERE name = "John"') cur.execute('UPDATE test SET age = 99 WHERE name = "Alice"') # if there is more than one Mary then they both get updated cur.execute('SELECT * FROM test WHERE age > 5 ORDER BY name') whole_table = cur.fetchall print (whole_table) con.close

Back to top

Pandas
Tutorial and Cheatsheet

pandas = panels of data (multi-dimensional data)

A pandas dataframe (spreadsheet) is normally created from a list or a list of lists. We could create a dataframe from an array but then all the data would have to be of the same type.

Working with dataframes is faster than working with lists because dataframes are two dimensional numpy arrays. Each data type is stored in a separate block of memeory. All the integers are together in one block. All the floats are together in one block...etc.

numpy dtypes that are also accepted in pandas: [numpy.generic, numpy.number,  [[numpy.integer,     [[numpy.signedinteger,       [numpy.int8,        numpy.int16,        numpy.int32,        numpy.int64,        numpy.int64,        numpy.timedelta64,      [numpy.unsignedinteger,       [numpy.uint8,        numpy.uint16,        numpy.uint32,        numpy.uint64,        numpy.uint64]]]], [numpy.inexact, numpy.floating,      [numpy.float16, numpy.float32, numpy.float64, numpy.float128, [numpy.complexfloating, [numpy.complex64, numpy.complex128, numpy.complex256]]]]]], [numpy.flexible, numpy.character, [numpy.bytes_, numpy.str_, [numpy.void, [numpy.record]]]], numpy.bool_, numpy.datetime64, numpy.object_]]

Pandas also adds two dtypes: categorical and datetime64[ns, tz]

Back to top

Internet
The following code prints each line of the webpage minus most of the html markup.

tag = False quote = False import urllib.request with urllib.request.urlopen("https://en.wikipedia.org/wiki/Hiroshi_Sakagami") as webpage: for line in webpage: out = "" line = line.strip line = line.decode('utf-8') if line == "": print (line) elif line[0:7] == "": line = "" else: for c in line: if c == '<' and not quote: tag = True elif c == '>' and not quote: tag = False elif (c == '"' or c == "'") and tag:                  quote = not quote                 elif not tag:                   out = out + c              if out != "":                print(out)

x=input("press enter when done")

Back to top

Numpy Arrays
numpy arrays are fast because they work with continuous blocks of memory.

numpy.random.randint(low, high, size) # returns array of random integers that are less than "high"

import numpy as np x = np.array(1,2,3],[4,5,6) print (x)

1 2 3] [4 5 6

Math operations + and * operate elementwise and create a new matrix.

To modify an existing array use += and *=

For matrix multiplication use @

The identity matrix can be created easily with numpy.eye(n):

print (np.eye(4))

1. 0. 0. 0.] [0. 1. 0. 0.] [0. 0. 1. 0.] [0. 0. 0. 1.

The inverse of matrix m is:

np.linalg.inv(m)

Back to top

Scipy
tutorial

To import two subpackages you would use:

from scipy import subpackage1, subpackage2

import scipy as sp from scipy import constants print (constants.physical_constants["alpha particle mass"]) # produces the following tuple:

(6.64465723e-27, 'kg', 8.2e-35)

Back to top

Sympy
Galgebra tutorial

Back to top

Matplotlib
Tutorial The Matplotlib API

Bizarrely, in matplotlib.pyplot states are preserved across function calls.

Line or scatter plot
If we had wanted a log log plot we would have used:

ax=plt.gca ax.set_xscale('log') ax.set_yscale('log')

Bar graph


Bar graph:

import numpy as np import matplotlib.pyplot as plt

fig=plt.gcf

fig.set_size_inches(14.4,1.3*9.6)

data = [ 0,   5,   1,   16,   20,   2,   26,   26,   30,   32] positions = np.arange(10) width = 0.75

ax=plt.gca ax.set_axisbelow(True) ax.set_xscale('linear') ax.set_yscale('linear')

plt.grid(which='major', axis='both', color='black', linestyle='-') plt.minorticks_on plt.grid(which='minor', axis='both', color='#CCCCCC', linestyle='--')

plt.axis([0, 10, 0, 35]) p1 = plt.bar(positions, data, width)

plt.ylabel('y-axis label') plt.title('Title')

plt.savefig("File.name2.png", dpi=100) plt.show

See also: subplots

Back to top

Jupyter
Tutorial

Back to top

Intel® Distribution for Python
Math Kernel Library

Numba

https://developer.nvidia.com/how-to-cuda-python

Back to top