def run(): """Common Dictionary""" my_dict = {} for num in range(1, 101): if num % 3 != 0: my_dict[num] = num**3 print('***Lista Común***') print(my_dict) """Dictionary Comprehension""" my_dict_comp = {num: num**3 for num in range(1, 101) if num % 3 != 0} print('\n***Dictionary Comprehension***') print(my_dict_comp) """Common Dictionary Challenge""" my_dict2 = {} # I use round to limit the number of decimal places in # the root of the value. for num in range(1, 1001): my_dict2[num] = round(square_root(num), 3) print('\n***Diccionario Común del Reto***') print(my_dict2) """Dictionary Comprehension Challenge""" my_dict_comp2 = {num: round(square_root(num), 3) for num in range(1, 1001)} print('\n***Dictionary Comprehension***') print(my_dict_comp2)
def cosine_similarity(a, b): length = len(a) if len(a) > len(b) else len(b) numerator = sum( [get(a, index, 0) * get(b, index, 0) for index in range(length)]) denominator = square_root( sum([value**2 for value in a]) * sum([value**2 for value in b])) return numerator / denominator
def getEuclideanDistance(training_instance, test_instance, number_of_features): squared_distance = 0 # print test_instance # print training_instance for i in range(number_of_features): squared_distance += pow((test_instance[i] - training_instance[i]), 2) distance = square_root(squared_distance) return distance
def is_prime(num): if num <= 1: return False # Check from 2 to n-1 for i in range(2, square_root(num)): if num % i == 0: return False; return True
print("-------------------------------") circle_radius = float(5) circle_area = pi * (circle_radius ** 2) print("Circle radius: " + str(circle_radius) + "\nCircle area: " + str(circle_area)) # Trying to import a module that isn't available causes an importError # import some_module <- code had to be commented # You can import a module or object under a different name using # the "as" keyword. This is mainly used when a module or object # has a long or confusing name. print("\n") from math import sqrt as square_root print(square_root(100)) # Exercise: # What is the output of this code? print("\n") def func(x): res = 0 for i in range(x): res += i # print(res) return res print(func(4)) # Output: 6
def circular(x: float) -> float: return 1 - square_root(1 - x**2)
# bool True | False bool(0) = False, bool(42) = True, bool(-1) = True # Bool operator can be used to determine if a list/array is empty in if and while loops statements # bool ([]) = False, bool([1,2,3]) = True, bool("False") = True because list is not empty # Convert float to int k = int(4.0) # int n = 10 P = factorial(n) / factorial(n - k) print("Number of purmutaions, where order matters to alarm code: ") print(P) print("Square root of 81 is ") print(square_root(81)) # Relational Operators, can be used to compare objects # ==, !=, <, >, <=, >= # * * * Remember that in Python you indent 4 spaces * * * # Contidional Statements nicoAge = 42 chuyAge = 43 lupeAge = 46 if chuyAge < lupeAge: print("Chuy is younger than Lupe!") elif nicoAge < chuyAge: print("Nico is younger than chuy!") else: print("Hector's age is between Chuy's and Lupe's")
from math import sqrt as square_root print(square_root(24234234))
def project_to_distance(point_x, point_y, distance): dist_to_origin = math.square_root(point_x**2 + point_y**2) scale = distance / dist_to_origin print point_x * scale, point_y * scale
import random value = random.randint(1, 100) print(value) from math import pi, sqrt print(pi) print(sqrt(25)) from math import sqrt as square_root print(square_root(25))
Traceback (most recent call last): File "<pyshell#280>", line 1, in <module> x = int(input("Enter floating number :")) ValueError: invalid literal for int() with base 10: '3.43' >>> x = float(input("Enter floating number :")) Enter floating number :3.43 >>> x 3.43 >>> >>> >>> # importing a module >>> >>> import math >>> math.pi 3.141592653589793 >>> math.sqrt(9) 3.0 >>> >>> from math import sqrt >>> sqrt(25) 5.0 >>> >>> from math import sqrt as square_root >>> square_root(36) 6.0 >>> >>> import sys >>> sys.path # shows the system path ['', 'C:\\Users\\rshende\\AppData\\Local\\Programs\\Python\\Python37-32\\Lib\\idlelib', 'C:\\Users\\rshende\\AppData\\Local\\Programs\\Python\\Python37-32\\python37.zip', 'C:\\Users\\rshende\\AppData\\Local\\Programs\\Python\\Python37-32\\DLLs', 'C:\\Users\\rshende\\AppData\\Local\\Programs\\Python\\Python37-32\\lib', 'C:\\Users\\rshende\\AppData\\Local\\Programs\\Python\\Python37-32', 'C:\\Users\\rshende\\AppData\\Local\\Programs\\Python\\Python37-32\\lib\\site-packages'] >>>
def project_to_distance(point_x, point_y, distance): dist_to_origin = math.square_root(point_x ** 2 + point_y ** 2) scale = distance / dist_to_origin print point_x * scale, point_y * scale
from math import sqrt as square_root #importing sqrt function from math module as square_root num=int(input("Enter number:")) print ("Square root is:%s" %(square_root(num))) #calculating Square root using sqrt funtion of math module #calling sqrt function using other name.
# Basic import. import math print(math.sqrt(64)) # Import a module with a alias. import math as m print(m.sqrt(64)) # Import only a part of a module, to the actual namespace. from math import sqrt print(sqrt(64)) # Import a module function with a alias. from math import sqrt as square_root print(square_root(64)) # Import all the parts of the module to the actual namespace. from math import * print(factorial(5)) """ Custom module imports and usage. """ # The custom modules use all the module options, like: import modules.customModule modules.customModule.print_hello() import modules.customModule as custom custom.print_hello()
import random for i in range(5): value = random.randint(2, 10) print(value) from math import pi print(pi) from math import sqrt as square_root print(square_root(4))
from math import sqrt as square_root print(square_root(3))
# getrandbits(...) # getrandbits(k) -> x. Generates an int with k random bits. # After full import can now use any function the module. In our case "random". We call our getrandbits function. # You call the functions in the module by <module>.<function> print("this is a random number from 8 bits:", random.getrandbits(8)) # If we want to selectively import just specific variables/objects/functions rather than a whole module, we can do so by using from <module> import <object> # In this example we import the constant pi from the math module from math import pi print("pi from our math module is:", pi) # We can also import modules and or their objects and rename them to make names more explanatory to our liking by using from <module> import <object> as <name> # Or in the module case import <module> as <name> from math import sqrt as square_root print ("Square root of 100 is:", square_root(100)) # Importing today's date from datetime and printing it. from datetime import date, datetime print("Today's date is:", date.today()) print("Today is as per unix weekday number: ", datetime.weekday(date.today())) # Third Party modules are commonly installed via PyPI, Python Package Index. # The best way to install these packages are through an application called pip. # pip comes with most installation of python and is run in the command line. # pip install <library_name> # You can micro manage versions of modules and create virtual environments to store them in. pip grows quite comprehensive and complex. ################################################# # # # Functions #
docstring() def var_fun(): print('This is a function that is printed as a variable.') printDoc = var_fun() # You can treat functions as normal variables printDoc def do_twice(func): # A function can be used as an argument func() func() do_twice(func) print(random.randint(1, 6)) print(pi) print(cos(65)) print(square_root(25)) try: print(6 / 0) except ZeroDivisionError: # If an error happens in the try block, it is cought by the except block print('Unable to divide by 0.') try: value = 5 print(value + ' = value') except (ValueError, TypeError): # You can have multiple exceptions using parenthasis and commas. print('Error') try: print(9 / 0) except: # You can have an except block without any exception. This will catch all exceptions.
#import random #value=random.randint(1,100) #print value #from math import pi ,sqrt #print pi #print sqrt(100) from math import sqrt as square_root print square_root(25)
def _f(): from math import sqrt as square_root return square_root(4)
import random # fully for i in range(5): value = random.randint(1, 6) print(value) from math import pi #just one print(pi) from math import sqrt, cos #various import math print(math.cos == cos) from math import sqrt as square_root #import as a diferent name print(square_root(100)) from math import sqrt as square_root, cos as cosine, tan as tangent print(square_root(49)) print(cosine(0)) print(tangent(45)) print(dir(math)) import math as m print(math.sqrt(25))
return x else: return y num = func3(4, 5) print(num) func4 = func3 num = func4(6, 7) print(num) def func5(x, y): return x + y def func6(func, x, y): return func(func(x, y), func(x, y)) print(func6(func5, 4, 5)) for i in range(5): print(random.randint(1, 6)) print(pi) print(square_root(16))
# Soal 2 : Fill in the blanks to import only the sqrt and cos functions from the math module: # ____ math import _____ cos # Jawaban 2 : from math import sqrt, cos # ================================================== # # Materi 3 : Modules #3 # import some_module # Error no module named some_module # Soal 3 : What error is caused by importing an unknown module? # Jawaban 3 : ImportError # ================================================== # # Materi 4 : Modules #4 from math import sqrt as square_root print(square_root(100)) # Soal 4 : What is the output of this code? # import math as m # print(math.sqrt(25)) # Error name math is not defined # Jawaban 4 : An error occurs # ================================================== #
import random #importing a module for number in range(5): value=random.randint(1,6) print(value) from math import pi, cos # importing only 2 function from math module print(pi) # i.e pi and cos print(cos(90)) #Using 'as' to give function a different name or alias from math import sqrt as square_root #importing a specific function under print(square_root(100)) #different name #Importing all functions in a module from math import *
from math import sqrt as square_root def sqrt(): return'I live to drink soda! print(int(square_root(400)) #I am (random range of numbers) and super (Happy, mad or glad) about it! from random import randrange, choice lst = ['Happy', 'Mad', 'Glad'] number = (randrange(1, 51, 2)) print("I am {} and super {} about it!".format(number, choice(lst)))
import random from math import pi, sqrt as square_root # import some_module for i in range(5): value = random.randint(1, 6) print(value) # print(sqrt(pi)) print(square_root(pi))
def do_twice(func, x, y): return func(func(x, y), func(x, y)) a = 5 b = 10 print(do_twice(addNumbers, a, b)) #addNumbers was defined earlier #returns 30 #Module import import random for i in range(5): value = random.randint(1, 5) print(value) #Partial module import from math import pi, sqrt print(pi) print(sqrt(5)) #Import module or sub-module under a different name from math import sqrt as square_root print(square_root(7)) #Types of modules: Ones you create, ones you download, ones that come with Python #Standard modules: string, re, datetime, math, random, os, multiprocessing, #subprocess, socket, email, json,doctest, unittest, pdb, argparse, and sys #Some of the standard modules are written in Python and others in C #To install a library, use pip: pip install library_name
print "I will now count my chickens" print "Hens", 25 + 30 / 6 #'/' higher precedence print "Roosters", 100 - 25 * 3 % 4 # precendence order / > % > - print "I will now count the eggs:" print 3 + 2 + 1 - 5 + 4 % 2 - 1 / 4 + 6 print "Is it true that 3 + 2 < 5 - 7" print 3 + 2 < 5 - 7 print "What is 3 + 2 ?", 3 + 2 print "What is 5 - 7 ?", 5 - 7 print "Oh!! That's why its false" print "How about some more" print "Is it greater", 5 > -2 print "Is it greater than equal", 5 >= -2 print "Is it less than equal", 5 <= -2 from math import sqrt as square_root y = square_root(25) print "Square root of 25:", y print "24/5:", 24 / 5 print "24/5.0:", 24 / 5.0 print "24.0/5:", 24.0 / 5