263 KiB
263 KiB
In [1]:
!python --versionPython 3.8.16
In [2]:
x = 3
print(x, type(x))3 <class 'int'>
In [3]:
print(x + 1) # Addition
print(x - 1) # Subtraction
print(x * 2) # Multiplication
print(x ** 2) # Exponentiation4 2 6 9
In [4]:
x += 1
print(x)
x *= 2
print(x)4 8
In [5]:
y = 2.5
print(type(y))
print(y, y + 1, y * 2, y ** 2)<class 'float'> 2.5 3.5 5.0 6.25
In [6]:
t, f = True, False
print(type(t))<class 'bool'>
In [7]:
print(t and f) # Logical AND;
print(t or f) # Logical OR;
print(not t) # Logical NOT;
print(t != f) # Logical XOR;False True False True
In [8]:
hello = 'hello' # String literals can use single quotes
world = "world" # or double quotes; it does not matter
print(hello, len(hello))hello 5
In [9]:
hw = hello + ' ' + world # String concatenation
print(hw)hello world
In [10]:
hw12 = '{} {} {}'.format(hello, world, 12) # string formatting
print(hw12)hello world 12
In [11]:
print(f'{hello}, {world} {12}')hello, world 12
In [12]:
s = "hello"
print(s.capitalize()) # Capitalize a string
print(s.upper()) # Convert a string to uppercase; prints "HELLO"
print(s.rjust(7)) # Right-justify a string, padding with spaces
print(s.center(7)) # Center a string, padding with spaces
print(s.replace('l', '(ell)')) # Replace all instances of one substring with another
print(' world '.strip()) # Strip leading and trailing whitespaceHello HELLO hello hello he(ell)(ell)o world
In [13]:
xs = [3, 1, 2] # Create a list
print(xs, xs[2])
print(xs[-1]) # Negative indices count from the end of the list; prints "2"[3, 1, 2] 2 2
In [14]:
xs[2] = 'foo' # Lists can contain elements of different types
print(xs)[3, 1, 'foo']
In [15]:
xs.append('bar') # Add a new element to the end of the list
print(xs) [3, 1, 'foo', 'bar']
In [16]:
x = xs.pop() # Remove and return the last element of the list
print(x, xs)bar [3, 1, 'foo']
In [17]:
nums = list(range(5)) # range is a built-in function that creates a list of integers
print(nums) # Prints "[0, 1, 2, 3, 4]"
print(nums[2:4]) # Get a slice from index 2 to 4 (exclusive); prints "[2, 3]"
print(nums[2:]) # Get a slice from index 2 to the end; prints "[2, 3, 4]"
print(nums[:2]) # Get a slice from the start to index 2 (exclusive); prints "[0, 1]"
print(nums[:]) # Get a slice of the whole list; prints ["0, 1, 2, 3, 4]"
print(nums[:-1]) # Slice indices can be negative; prints ["0, 1, 2, 3]"
nums[2:4] = [8, 9] # Assign a new sublist to a slice
print(nums) # Prints "[0, 1, 8, 9, 4]"[0, 1, 2, 3, 4] [2, 3] [2, 3, 4] [0, 1] [0, 1, 2, 3, 4] [0, 1, 2, 3] [0, 1, 8, 9, 4]
In [18]:
animals = ['cat', 'dog', 'monkey']
for animal in animals:
print(animal)cat dog monkey
In [19]:
animals = ['cat', 'dog', 'monkey']
for idx, animal in enumerate(animals):
print('#{}: {}'.format(idx + 1, animal))#1: cat #2: dog #3: monkey
In [20]:
nums = [0, 1, 2, 3, 4]
squares = []
for x in nums:
squares.append(x ** 2)
print(squares)[0, 1, 4, 9, 16]
In [21]:
nums = [0, 1, 2, 3, 4]
squares = [x ** 2 for x in nums]
print(squares)[0, 1, 4, 9, 16]
In [22]:
nums = [0, 1, 2, 3, 4]
even_squares = [x ** 2 for x in nums if x % 2 == 0]
print(even_squares)[0, 4, 16]
In [23]:
d = {'cat': 'cute', 'dog': 'furry'} # Create a new dictionary with some data
print(d['cat']) # Get an entry from a dictionary; prints "cute"
print('cat' in d) # Check if a dictionary has a given key; prints "True"cute True
In [24]:
d['fish'] = 'wet' # Set an entry in a dictionary
print(d['fish']) # Prints "wet"wet
In [31]:
import traceback
try:
print(d['monkey']) # KeyError: 'monkey' not a key of d
except Exception as e:
traceback.print_exc()Traceback (most recent call last):
File "/var/folders/zv/bzxgq5_j5f9gkpm84rg80kph0000gn/T/ipykernel_31837/1743455973.py", line 3, in <module>
print(d['monkey']) # KeyError: 'monkey' not a key of d
KeyError: 'monkey'
In [32]:
print(d.get('monkey', 'N/A')) # Get an element with a default; prints "N/A"
print(d.get('fish', 'N/A')) # Get an element with a default; prints "wet"N/A wet
In [33]:
del d['fish'] # Remove an element from a dictionary
print(d.get('fish', 'N/A')) # "fish" is no longer a key; prints "N/A"N/A
In [34]:
d = {'person': 2, 'cat': 4, 'spider': 8}
for animal, legs in d.items():
print('A {} has {} legs'.format(animal, legs))A person has 2 legs A cat has 4 legs A spider has 8 legs
In [35]:
nums = [0, 1, 2, 3, 4]
even_num_to_square = {x: x ** 2 for x in nums if x % 2 == 0}
print(even_num_to_square){0: 0, 2: 4, 4: 16}
In [36]:
animals = {'cat', 'dog'}
print('cat' in animals) # Check if an element is in a set; prints "True"
print('fish' in animals) # prints "False"
True False
In [37]:
animals.add('fish') # Add an element to a set
print('fish' in animals)
print(len(animals)) # Number of elements in a set;True 3
In [38]:
animals.add('cat') # Adding an element that is already in the set does nothing
print(len(animals))
animals.remove('cat') # Remove an element from a set
print(len(animals)) 3 2
In [39]:
animals = {'cat', 'dog', 'fish'}
for idx, animal in enumerate(animals):
print('#{}: {}'.format(idx + 1, animal))#1: fish #2: dog #3: cat
In [40]:
from math import sqrt
print({int(sqrt(x)) for x in range(30)}){0, 1, 2, 3, 4, 5}
In [41]:
d = {(x, x + 1): x for x in range(10)} # Create a dictionary with tuple keys
t = (5, 6) # Create a tuple
print(type(t))
print(d[t])
print(d[(1, 2)])<class 'tuple'> 5 1
In [43]:
import traceback
try:
t[0] = 1 # TypeError: 'tuple' object does not support item assignment
except Exception as e:
traceback.print_exc()Traceback (most recent call last):
File "/var/folders/zv/bzxgq5_j5f9gkpm84rg80kph0000gn/T/ipykernel_31837/743935956.py", line 3, in <module>
t[0] = 1 # TypeError: 'tuple' object does not support item assignment
TypeError: 'tuple' object does not support item assignment
In [44]:
def sign(x):
if x > 0:
return 'positive'
elif x < 0:
return 'negative'
else:
return 'zero'
for x in [-1, 0, 1]:
print(sign(x))negative zero positive
In [45]:
def hello(name, loud=False):
if loud:
print('HELLO, {}'.format(name.upper()))
else:
print('Hello, {}!'.format(name))
hello('Bob')
hello('Fred', loud=True)Hello, Bob! HELLO, FRED
In [46]:
class Greeter:
# Constructor
def __init__(self, name):
self.name = name # Create an instance variable
# Instance method
def greet(self, loud=False):
if loud:
print('HELLO, {}'.format(self.name.upper()))
else:
print('Hello, {}!'.format(self.name))
g = Greeter('Fred') # Construct an instance of the Greeter class
g.greet() # Call an instance method; prints "Hello, Fred"
g.greet(loud=True) # Call an instance method; prints "HELLO, FRED!"Hello, Fred! HELLO, FRED
In [47]:
import numpy as npIn [48]:
a = np.array([1, 2, 3]) # Create a rank 1 array
print(type(a), a.shape, a[0], a[1], a[2])
a[0] = 5 # Change an element of the array
print(a) <class 'numpy.ndarray'> (3,) 1 2 3 [5 2 3]
In [49]:
b = np.array([[1,2,3],[4,5,6]]) # Create a rank 2 array
print(b)[[1 2 3] [4 5 6]]
In [50]:
print(b.shape)
print(b[0, 0], b[0, 1], b[1, 0])(2, 3) 1 2 4
In [51]:
a = np.zeros((2,2)) # Create an array of all zeros
print(a)[[0. 0.] [0. 0.]]
In [52]:
b = np.ones((1,2)) # Create an array of all ones
print(b)[[1. 1.]]
In [53]:
c = np.full((2,2), 7) # Create a constant array
print(c)[[7 7] [7 7]]
In [54]:
d = np.eye(2) # Create a 2x2 identity matrix
print(d)[[1. 0.] [0. 1.]]
In [55]:
e = np.random.random((2,2)) # Create an array filled with random values
print(e)[[0.00480263 0.8985954 ] [0.19113444 0.57867786]]
In [56]:
import numpy as np
# Create the following rank 2 array with shape (3, 4)
# [[ 1 2 3 4]
# [ 5 6 7 8]
# [ 9 10 11 12]]
a = np.array([[1,2,3,4], [5,6,7,8], [9,10,11,12]])
# Use slicing to pull out the subarray consisting of the first 2 rows
# and columns 1 and 2; b is the following array of shape (2, 2):
# [[2 3]
# [6 7]]
b = a[:2, 1:3]
print(b)[[2 3] [6 7]]
In [57]:
print(a[0, 1])
b[0, 0] = 77 # b[0, 0] is the same piece of data as a[0, 1]
print(a[0, 1]) 2 77
In [58]:
# Create the following rank 2 array with shape (3, 4)
a = np.array([[1,2,3,4], [5,6,7,8], [9,10,11,12]])
print(a)[[ 1 2 3 4] [ 5 6 7 8] [ 9 10 11 12]]
In [59]:
row_r1 = a[1, :] # Rank 1 view of the second row of a
row_r2 = a[1:2, :] # Rank 2 view of the second row of a
row_r3 = a[[1], :] # Rank 2 view of the second row of a
print(row_r1, row_r1.shape)
print(row_r2, row_r2.shape)
print(row_r3, row_r3.shape)[5 6 7 8] (4,) [[5 6 7 8]] (1, 4) [[5 6 7 8]] (1, 4)
Warning:
Output truncated. This notebook contains too many cells to display efficiently.