Contents
- function_example.py
- module_example.py
- pick4.py
- print_examples.py
- random_test.py
- sum5.py
function_example.py 1/6
[top][prev][next]
# Examples using built-in functions
# Sara Sprenkle
x = 6.817454321
#x = 5.6512542
print("We start with x having value", x)
# Call the function round with input x
# Then, save output of function call in variable roundx
roundx = round(x)
print("x rounded to the nearest int:", roundx)
round2 = round(x, 1)
print("x rounded to the nearest tenth:", round2)
a = round(x, 2)
print("x rounded to the nearest hundredth:", a)
roundx = round(x, 3)
print("x rounded to the nearest thousandth:", roundx)
print(round(x, 4))
print("-"*40)
print("x is of", type(x))
module_example.py 2/6
[top][prev][next]
# Example of importing a module
# by Sara Sprenkle
# Alternative: could import math
# Would then need to prepend all constants, functions with math.
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))
pick4.py 3/6
[top][prev][next]
# Simulate the VA Pick4 Lottery game
# by CSCI111, 9.21.2012
# import random module
from random import *
print("The winning Pick 4 lottery number is ", end='')
for i in range(4):
ranNum = randint(0,9)
print(ranNum, end='')
print()
# Why doesn't the following code work as an alternative correct solution?
#print(randint(0,9999))
print_examples.py 4/6
[top][prev][next]
# Examples calling the print function
# Sara Sprenkle for CSCI111
print("Hi", "there", "class", sep='; ')
print("Put on same", end='')
print("line")
random_test.py 5/6
[top][prev][next]
# Demonstrating random module
# by Sara Sprenkle
import random
NUM_RANDOM = 5
print("This program generates", NUM_RANDOM,"random numbers.")
# Demonstrates that it's a pseudo-random number generator
# If using the same seed, then 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(1, 10))
sum5.py 6/6
[top][prev][next]
# This program adds up 5 numbers from the user.
# By CS111, 09.19.2012
print("This program adds up 5 numbers given by the user.")
total = 0
for i in range(1, 6): # alternatively, for i in range(5)
num = eval( input("Enter a number: ") )
total = num + total
print("The total of the given numbers is", total)
Generated by GNU enscript 1.6.4.