In [15]:
# P5: fractions demo
>>> from fractions import Fraction
>>> f = Fraction(3, 4)
f
Out[15]:
In [16]:
#P12: Complex number input
>>> z = complex(input('Enter a complex number: ')) #2+3j is valid, 2 + 3j is invalid
z
Out[16]:
In [19]:
#P12: Checking if a number is a factor of another
def is_factor(a, b):
if b % a == 0:
return True
else:
return False
# try it out
print(is_factor(4, 1024))
print(is_factor(4, 21))
In [1]:
#P14: Find the factors of an integer
'''
Find the factors of an integer
'''
def factors(a):
for i in range(1, a+1):
if a % i == 0:
print(i)
if __name__ == '__main__':
a = input('Your Number Please: ')
a = float(a)
if a > 0 and a.is_integer():
factors(int(a))
else:
print('Please enter a positive integer')
In [14]:
#P15: Format example
>>> item1 = 'apples'
>>> item2 = 'bananas'
>>> item3 = 'grapes'
>>> print('At the grocery store, I bought some {0} and {1} and {2}'.format(item1, item2, item3))
In [20]:
#P16: Multiplication table printer
'''
Multiplication table printer
'''
def multi_table(a):
for i in range(1, 11):
print('{0} x {1} = {2}'.format(a, i, a*i))
if __name__ == '__main__':
a = input('Enter a number: ')
multi_table(float(a))
In [29]:
#P18: Fahrenheit to Celsius conversion
>>> F = 98.6
>>> (F - 32) * (5 / 9)
Out[29]:
In [32]:
#P18: Celsius to Fahrenheit
>>> C = 37
>>> C * (9 / 5) + 32
Out[32]:
In [35]:
#P19: Unit conversion
'''
Unit converter: Miles and Kilometers
'''
def print_menu():
print('1. Kilometers to Miles')
print('2. Miles to Kilometers')
def km_miles():
km = float(input('Enter distance in kilometers: '))
miles = km / 1.609
print('Distance in miles: {0}'.format(miles))
def miles_km():
miles = float(input('Enter distance in miles: '))
km = miles * 1.609
print('Distance in kilometers: {0}'.format(km))
if __name__ == '__main__':
print_menu()
choice = input('Which conversion would you like to do?: ')
if choice == '1':
km_miles()
if choice == '2':
miles_km()
In [38]:
#P21: Roots of a quadratic equation example
>>> a = 1
>>> b = 2
>>> c = 1
>>> D = (b**2 - 4*a*c)**0.5
>>> x_1 = (-b + D)/(2*a)
>>> print(x_1)
>>> x_2 = (-b - D)/(2*a)
>>> print(x_2)
In [40]:
#P21: Quadratic Equation Root calculator
'''
Quadratic Equation root calculator
'''
def roots(a, b, c):
D = (b*b - 4*a*c)**0.5
x_1 = (-b + D)/(2*a)
x_2 = (-b - D)/(2*a)
print('x1: {0}'.format(x_1))
print('x2: {0}'.format(x_2))
if __name__ == '__main__':
a = input('Enter a: ')
b = input('Enter b: ')
c = input('Enter c: ')
roots(float(a), float(b), float(c))