math functions
Playing around with math functions like squaring a number, square root, and changing a number from floating point to integer. I add various methods to do the same tasks.
import math print("Here are the numbers") numbers = [] num = 0 while num <= 20: numbers.append(num) num += 1 print(numbers) print('') print('Here are the numbers squared') squares = [] num = 0 while num <= 20: squares.append(num ** 2) num += 1 print(squares) print("\n another method takes 6 lines down to 1 lines") print("\n method 2a: {}".format(list(x * x for x in range(20)))) print("\n method 2a even squares: {}".format(list(x * x for x in range(20) if x % 2 == 0))) print("\n method 2b odd squares: {}".format(list(x * x for x in range(20) if x % 2 != 0))) print("\n Here are the numbers square roots of the squared numbers") sq_root = [] num = 0 while num <= 20: sq_root.append(math.sqrt(squares[num])) num += 1 print(sq_root) print('they returned floating point from sqrt') print('\n Here are the numbers square roots of the squared numbers converted to integer') # Method 1 of square root sq_root = [] num = 0 while num <= 20: sq_root.append(int(math.sqrt(squares[num]))) num += 1 print("Method 1 of square root: {}".format(sq_root)) # Method 2 of square root single line replacing 6 print("Method 2 of square root: {}".format(list(int(math.sqrt(squares[num])) for num in range(21))))
Here are the numbers [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20] Here are the numbers squared [0, 1, 4, 9, 16, 25, 36, 49, 64, 81, 100, 121, 144, 169, 196, 225, 256, 289, 324, 361, 400] another method takes 6 lines down to 1 lines method 2a: [0, 1, 4, 9, 16, 25, 36, 49, 64, 81, 100, 121, 144, 169, 196, 225, 256, 289, 324, 361] method 2a even squares: [0, 4, 16, 36, 64, 100, 144, 196, 256, 324] method 2b odd squares: [1, 9, 25, 49, 81, 121, 169, 225, 289, 361] Here are the numbers square roots of the squared numbers [0.0, 1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0, 8.0, 9.0, 10.0, 11.0, 12.0, 13.0, 14.0, 15.0, 16.0, 17.0, 18.0, 19.0, 20.0] they returned floating point from sqrt Here are the numbers square roots of the squared numbers converted to integer Method 1 of square root: [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20] Method 2 of square root: [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20] Process finished with exit code 0