Contents
- ./function_example.py
- ./module_example_from_import.py
- ./module_example_import.py
- ./print_examples.py
- ./random_test.py
./function_example.py 1/5
[top][prev][next]
# Examples using built-in functions
# Sara Sprenkle
#x = 6.817454321
x = 5.60123
print("We start with x having value", x)
# Call the function round with input x
# and save the output of function call in variable roundedXInt
roundedXInt = round(x)
print("x rounded to the nearest int:", roundedXInt)
roundedXTenth = round(x, 1)
print("x rounded to the nearest tenth:", roundedXTenth)
a = round(x, 2)
print("x rounded to the nearest hundredth:", a)
# demonstrating that the variable name doesn't matter,
# but good names make the code easier to understand
roundx = round(x, 3)
print("x rounded to the nearest thousandth:", roundx)
print(round(x, 4)) # not saving returned value in a variable
print("-"*40)
print("x is of", type(x))
./module_example_from_import.py 2/5
[top][prev][next]
# Example of importing a module, using the from version of import
# by Sara Sprenkle
# With the from import, you don't need to prepend the names
from math import *
i = 1j
# The equation e^(i pi) + 1 = 0
# with import math statement
# shouldbezero = math.e ** (i * math.pi) + 1
shouldbezero = e ** (i * pi) + 1
print("e^(i pi) + 1 equals", shouldbezero)
# practice using functions from modules
print("100^(1/2) =", sqrt(100))
./module_example_import.py 3/5
[top][prev][next]
# Example of importing a module
# by Sara Sprenkle
# Need to prepend all constants and functions with math.
import math
i = 1j
# The equation e^(i pi) + 1 = 0
# with from math import * statement
# shouldbezero = e ** (i * pi) + 1
shouldbezero = math.e ** (i * math.pi) + 1
print("e^(i pi) + 1 equals", shouldbezero)
# practice using functions from modules
print("100^(1/2) =", math.sqrt(100))
./print_examples.py 4/5
[top][prev][next]
# Examples calling the print function
# Sara Sprenkle for CSCI111
print("Hi", "there", "class", sep='; ')
# By default end is "\n" --> called "the new line character"
# means, put the next displayed text on the next line.
print("Put on same", end='') # make end the empty string
print("line")
# make end a space instead:
print("Put on same", end=' ')
print("line")
something = 7
print("The result is ", something, ".", sep = "")
./random_test.py 5/5
[top][prev][next]
# Demonstrating random module
# by Sara Sprenkle
import random
NUM_RANDOM = 8
print("This program generates", NUM_RANDOM, "random numbers.")
# Demonstrates that it's a pseudo-random number generator
# If using the same seed, the program generates the same list of
# "random" numbers.
# The following function call sets the seed.
#random.seed(1)
for x in range(NUM_RANDOM):
print(random.random())
#print(random.randint(0, 10))
Generated by GNU Enscript 1.6.5.90.