|
Numbers |
Did you know that you can use the Python Shell like a calculator? Try typing in these and other arithmetic expressions (skip the comments that start with "#"):
>>> 1 + 2 # addition 3 >>> 10 - 1 # subtraction 9 >>> 2 * 3 # multiplication 6 >>> 5 / 3 # division (floating-point, keeping the part after the decimal point) 1.6666666666666667 >>> 5 // 3 # integer division (losing the part after the decimal point) 1 >>> 5 % 3 # integer remainder 2 >>> 5 ** 2 # exponentiation 25 >>> (2 + 3) * 4 # parentheses can be used to group operations 20 >>> _ # The underscore is a special variable that holds the last evaluated value 20 >>> _ // 5 # The underscore can be used in expressions ... 4 >>> _ # ... and then the value in the underscore changes. 4 >>> abs(-1) # absolute value 1 >>> round(5 / 3) # rounding a number to the nearest integer 2 >>> round(5 / 3, 2) # rounding a number to two decimal places (note inaccuracy) 1.6699999999999999 >>> print(round(5 / 3, 2)) # Printing such rounded values often "cleans up" appearance. 1.67 >>> import random # The random module allows a number of pseudorandom functions. >>> random.random() # return a random floating point number >= 0 and < 1 0.32409680723441237 >>> random.randint(1, 6) # return a random integer in the given range 4 >>> list = [1, 2, 3, 4, 5, 6] >>> random.choice(list) # choose a random element from a list 6 >>> random.shuffle(list) # shuffle a list >>> list [4, 2, 3, 5, 6, 1] >>> import math # The math module has important math functions. >>> (math.sqrt(5) + 1) / 2 # sqrt is short for "square root" 1.6180339887498949 >>> math.sin(math.pi) # sine and pi (note inaccuracy) 1.2246467991473532e-16 >>> math.cos(math.pi) # cosine and pi -1.0 >>> math.degrees(math.pi) # convert from radians to degrees 180.0 >>> math.radians(180) # convert from degrees to radians 3.1415926535897931 >>> math.log(math.e) # natural log and e 1.0 >>> math.log10(100.0) # base 10 logarithm 2.0
This just a sample of what is available for working with numbers. Don't be concerned if you don't understand what some of these are. Just know that most commonly used operations and functions are available in Python. There are other mathematical functions, other random number distributions, and even fractions and imaginary numbers. For now, these examples should cover most of what a programmer needs.
Try using Python as a calculator for other purposes. Remember that you can assign your results to variables, and reuse those results by placing variables in future expressions.
Further reference from the Python website:
© 2009 Todd Neller