%matplotlib inline
int('110100100', base=2) # Convert binary integer to base 10 integer
bin(337) # Convert base 10 integer to binary integer
This supports exact rational arithmetic.
from math import factorial
from fractions import Fraction
total = Fraction(0, 1)
for i in range(25):
total += Fraction(1, factorial(i))
print(total)
help(print)
print("MTH", 337) # Note that the commas between arguments are not printed
The "sep" keyword specifies a string to insert between the arguments to print
print(1,2,3,4,sep='potato')
print(1,2,3,4,sep='potato, ')
for i in range(5):
print(i)
The "end" keyword specifies what to print at the end (the default is a new line)
for i in range(5):
print(i, end=' ')
def find_epsilon():
n = 1
x = 2**(-n)
while 1 + x != 1:
n += 1
x = 2**(-n)
return 1 - n, 2**(1 - n)
find_epsilon()
for char in "abcde":
print("Letter is", char)
if char == "c":
print("Found it!")
break
for i in range(10):
if i % 2 == 0:
continue
print(i)
One way to find the largest float. However, this doesn't tell us where the error occurs.
n = 1
while True:
x = 2.**n
n += 1
A better way prints out the values of $n$, so we can find out where the error occurs.
n = 1
while True:
print(n, end=' ')
x = 2.**n
n += 1
Better still is to handle the error using a try-except statement.
n = 1
while True:
try:
x = 2.**n
n += 1
except:
print(n - 1)
break
For example, suppose we want to create a list of squared integers.
squares = []
for i in range(1, 11):
squares.append(i**2)
squares
A simpler and more elegant way to do the same thing uses a "list comprehension" as shown below.
[i**2 for i in range(1, 11)]
List comprehensions can be used on other sequences such as strings.
Adding two strings using "+" concatenates them together.
["letter" + i for i in "abcdefg"]