Search
Different namespaces in Python:
Python variable scope: A scope is the portion of a program from where a namespace can be accessed directly without any prefix.
At any given moment, there are at least three nested scopes.
When a reference is made inside a function, the name is searched in the local namespace, then in the global namespace and finally in the built-in namespace.
# Python program processing # global vs local variable count = 5 def some_method(): count = 10 print(count) return some_method() print(count)
# local function shadowing a built-in one. # REALLY BAD PRACTICE # You should NEVER shadow a built-in function. def abs(val): print("My abs() function") if val >= 0: return val else: return -val print(abs(-5))
PREFERRED SOLUTION: USE/WRITE YOUR OWN MODULE INSTEAD OF SHADOWING BUILT-IN FUNCTIONS!
main.py
import mymath print(abs(-4)) print(mymath.abs(-4))
mymath.py
def abs(val): print("My abs() function") if val >= 0: return val else: return -val
mymath
def cos(x): """Returns an approximate value of cos(x). :param x: float, input value for which the cosine function is computed :return: float, approximate value of cos(x) """ def sin(x): """Returns an approximate value of sin(x). :param x: float, input value for which the sine function is computed :return: float, approximate value of sin(x) """
$\cos(x)=1-\frac{x^2}{2}+\frac{x^4}{24}$
$\sin(x)=x-\frac{x^3}{6}+\frac{x^5}{120}$
get_trig_series(lst)
"""Return lists of cosines and sines of the values in the input list :param lst: list of floats, input values for this cos and sin functions are to be computed :return: list of floats, approximate cosines :return: list of floats, approximate sines Example: >>> cs, sn = get_trig_series([0, 0.1]) >>> print(cs, sn) [1.0, 0.9950041666666667] [0.0, 0.09983341666666667] """
import random rng = random.Random() # integer in range [1,6] dice_throw = rng.randrange(1,7) # odd integer in range [1, 199] odd_number = rng.randrange(1,200,2) # float drawn uniformy from a range [0, 1) float_0_1 = rng.random() # randomly shuffle list shuffled_card_list = rng.shuffle(card_list)
# Simulate throwing a dice 6000 times. # Produce a list (of length 6) with frequency of each outcome (1-6).
import math # constants math.pi math.e # square root of 9 math.sqrt(9) # degrees <-> radians conversion math.radians(90) math.degrees(3.14) # sin, cos, tan, ... math.sin(math.radians(90)) # inverse trigonometric functions math.asin(1.0) # natural logarithm math.log(math.e) # base-10 logarithm math.log10(1000)