<jupyter_start><jupyter_text>IPython Magic Commands IPython has a system of commands we call 'magics' that provide effectively a mini command language that is orthogonal to the syntax of Python and is extensible by the user with new commands. Magics are meant to be typed interactively, so they use command-line conventions, such as using whitespace for separating arguments, dashes for options and other conventions typical of a command-line environment.Magics come in two kinds:Line magics: these are commands prepended by one % character and whose arguments only extend to the end of the current line.Cell magics: these use two percent characters as a marker (%%), and they receive as argument both the current line where they are declared and the whole body of the cell.<jupyter_code># brings up a documentation pane with an overview of IPython's feature
?
# quick reference guide
%quickref
# use the ! operator to run system shell commands
!ping www.google.com
# several ways to interactively access help documentation
help
# help module for magic commands
%magic
# list of all available magic commands
%lsmagic
# bring up the help module for a specific command
%timeit?
# the ? syntax also works for any generic object
x = 5
x?
# run a python script from within the notebook
%run hello.py
# time the execution of a statement
import numpy as np
%timeit np.linalg.eigvals(np.random.rand(100,100))
# list all environment variables or specific variables
%env SYSTEMROOT
# print the cache of previously executed commands
%history
# print the call signature for any object
import turtle
t = turtle.Turtle
t?
# print the docstring for a class/callable object
%pdoc turtle.Turtle
# print all interactive variables
%who
# same as who but more information
%whos
# reset the namespace
%reset<jupyter_output><empty_output><jupyter_text>Quick tour of Python This is a collection of various statements, features, etc. of IPython and the Python language.  Much of this content is taken from other notebooks so I can't take credit for it, I just extracted the highlights I felt were most useful.Code cells are run by pressing shift-enter or using the play button in the toolbar.<jupyter_code>a = 10
print(a)
import math
x = math.cos(2 * math.pi)
print(x)<jupyter_output><empty_output><jupyter_text>Import the whole module into the current namespace instead.<jupyter_code>from math import *
x = cos(2 * pi)
print(x)<jupyter_output><empty_output><jupyter_text>Several ways to look at documentation for a module.<jupyter_code>print(dir(math))
help(math.cos)<jupyter_output><empty_output><jupyter_text>Variables<jupyter_code>x = 1.0
type(x)
# dynamically typed
x = 1
type(x)<jupyter_output><empty_output><jupyter_text>Operators<jupyter_code>1 + 2, 1 - 2, 1 * 2, 1 / 2
# integer division of float numbers
3.0 // 2.0
# power operator
2 ** 2
True and False
not False
True or False
2 > 1, 2 < 1, 2 > 2, 2 < 2, 2 >= 2, 2 <= 2
# equality
[1,2] == [1,2]<jupyter_output><empty_output><jupyter_text>Strings<jupyter_code>s = "Hello world"
type(s)
len(s)
s2 = s.replace("world", "test")
print(s2)
s[0]
s[0:5]
s[6:]
s[:]
# define step size of 2
s[::2]
# automatically adds a space
print("str1", "str2", "str3")
# C-style formatting
print("value = %f" % 1.0) 
# alternative, more intuitive way of formatting a string 
s3 = 'value1 = {0}, value2 = {1}'.format(3.1415, 1.5)
print(s3)<jupyter_output><empty_output><jupyter_text>Lists<jupyter_code>l = [1,2,3,4]

print(type(l))
print(l)
print(l[1:3])
print(l[::2])
l[0]
# don't have to be the same type
l = [1, 'a', 1.0, 1-1j]
print(l)
start = 10
stop = 30
step = 2
range(start, stop, step)

# consume the iterator created by range
list(range(start, stop, step))
# create a new empty list
l = []

# add an elements using `append`
l.append("A")
l.append("d")
l.append("d")

print(l)
l[1:3] = ["b", "c"]
print(l)
l.insert(0, "i")
l.insert(1, "n")
l.insert(2, "s")
l.insert(3, "e")
l.insert(4, "r")
l.insert(5, "t")

print(l)
l.remove("A")
print(l)
del l[7]
del l[6]

print(l)<jupyter_output><empty_output><jupyter_text>Tuples<jupyter_code>point = (10, 20)
print(point, type(point))
# unpacking
x, y = point

print("x =", x)
print("y =", y)<jupyter_output><empty_output><jupyter_text>Dictionaries<jupyter_code>params = {"parameter1" : 1.0,
          "parameter2" : 2.0,
          "parameter3" : 3.0,}

print(type(params))
print(params)
params["parameter1"] = "A"
params["parameter2"] = "B"

# add a new entry
params["parameter4"] = "D"

print("parameter1 = " + str(params["parameter1"]))
print("parameter2 = " + str(params["parameter2"]))
print("parameter3 = " + str(params["parameter3"]))
print("parameter4 = " + str(params["parameter4"]))<jupyter_output><empty_output><jupyter_text>Control Flow<jupyter_code>statement1 = False
statement2 = False

if statement1:
    print("statement1 is True")
elif statement2:
    print("statement2 is True")
else:
    print("statement1 and statement2 are False")<jupyter_output><empty_output><jupyter_text>Loops<jupyter_code>for x in range(4):
    print(x)
for word in ["scientific", "computing", "with", "python"]:
    print(word)
for key, value in params.items():
    print(key + " = " + str(value))
for idx, x in enumerate(range(-3,3)):
    print(idx, x)
l1 = [x**2 for x in range(0,5)]
print(l1)
i = 0
while i < 5:
    print(i)
    i = i + 1
print("done")<jupyter_output><empty_output><jupyter_text>Functions<jupyter_code># include a docstring
def func(s):
    """
    Print a string 's' and tell how many characters it has    
    """
    
    print(s + " has " + str(len(s)) + " characters")
help(func)
func("test")
def square(x):
    return x ** 2
square(5)
# multiple return values
def powers(x):
    return x ** 2, x ** 3, x ** 4
powers(5)
x2, x3, x4 = powers(5)
print(x3)
f1 = lambda x: x**2
f1(5)
map(lambda x: x**2, range(-3,4))
# convert iterator to list
list(map(lambda x: x**2, range(-3,4)))<jupyter_output><empty_output><jupyter_text>Classes<jupyter_code>class Point:
    def __init__(self, x, y):
        self.x = x
        self.y = y
        
    def translate(self, dx, dy):
        self.x += dx
        self.y += dy
        
    def __str__(self):
        return("Point at [%f, %f]" % (self.x, self.y))
p1 = Point(0, 0)
print(p1)
p2 = Point(1, 1)

p1.translate(0.25, 1.5)

print(p1)
print(p2)<jupyter_output><empty_output><jupyter_text>Exceptions<jupyter_code>try:
    print(test)
except:
    print("Caught an expection")
try:
    print(test)
except Exception as e:
    print("Caught an exception: " + str(e))<jupyter_output><empty_output>
{'fraction_non_alphanumeric': 0.13237100737100738, 'fraction_numerical': 0.02718058968058968, 'mean_word_length': 4.784191829484902, 'pattern_counts': {'":': 0, '<': 65, '<?xml version=': 0, '>': 64, 'https://': 0, 'lorem ipsum': 0, 'www.': 1, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'chain_length': '15', 'dir': 'jupyter-structured-clean-dedup', 'id': '125660', 'license': 'MIT', 'n_tokens_mistral': 2410, 'n_tokens_neox': 2303, 'n_words': 735, 'path': 'assets/notebooks/01-setup.ipynb', 'repo_name': 'halkypi/lh', 'size': '6512'}