Contents
- binaryToDecimal.test.py
- non_function_vars.py
- pick4num_wfunctions.py
- pick4winner.py
- practice1.py
- practice2.py
- practice3.py
binaryToDecimal.test.py 1/7
[top][prev][next]
# Converts a binary number into a decimal
# Modify to verify that the inputted number is valid.
# Added test functions that programmatically test if the function is behaving
# appropriately.
# By CSCI111
import sys
def main():
# Read in the binary number as a string -- why?
num = input("Enter the binary #: ")
# --------- Validate the user input ----------
if not isBinary(num):
print(num, "is not a valid binary number. Please try again.")
sys.exit()
decVal = binaryToDecimal(num)
print("The decimal value for", num, "is", decVal)
def binaryToDecimal(binnum):
"""
Converts the binary number to a decimal number
Precondition: binary, a string that is a binary number
Postcondition: returns the decimal value of the binary number
"""
# accumulate the decimal value in this variable
decVal = 0
# go through the positions in the string
for pos in range(len(binnum)):
# num[pos] is a string; need to convert to an int
bit = int(binnum[pos])
# calculate which "place" the current bit is at
place = 2**(len(binnum)-pos-1)
# add to the decimal value
decVal += place * bit
return decVal
def isBinary(candidate):
"""
Precondition: candidate is a string
Postcondition: returns True iff candidate is a valid binary string
"""
# check that it has all digits (no letters)
if not candidate.isdigit():
return False
# Make sure that the inputted number only contains 0s and 1s
for digit in candidate:
if digit != "0" and digit != "1":
return False
return True
def testIsBinary():
"""
Test the isBinary function.
Displays the correctness or incorrectness of the function.
Does not return anything.
"""
# ----------- Test where the result should be True ---------
testBinaryTrue = ["0", "1", "10", "1001", "10000"]
for test in testBinaryTrue:
result = isBinary(test)
if result:
print(test, "successfully identified as binary")
else:
print("**ERROR! **", test, "considered not binary")
# ----------- Test where the result should be False ---------
testBinaryFalse = ["a", "3", "-100", "123"]
for test in testBinaryFalse:
result = isBinary(test)
if not result:
print(test, "successfully identified as not binary")
else:
print("**ERROR! **", test, "considered binary")
# ------------ Alternatively, have a list of inputs and expected ----
# Question: How difficult is it to verify additional test cases?
inputs = [ "0", "1", "10", "1001", "10000", "a", "3", "-100", "123"]
expectedResults = [ True, True, True, True, True, False, False, False, False]
for pos in range(len(inputs)):
testInput = inputs[pos]
if isBinary(testInput) != expectedResults[pos]:
print("Error on isBinary(", testInput, ")")
print("Expected", expectedResults[pos], "but got", isBinary(testInput))
def testBinaryToDecimal():
"""Test the binaryToDecimal function.
Displays the correctness or incorrectness of the function.
Nothing is returned."""
paramInputs = ["0", "1", "10", "1001", "10000"]
expectedResults = [ 0, 1, 2, 9, 16]
for index in range(len(paramInputs)):
paramInput = paramInputs[index]
expectedResult = expectedResults[index]
actualResult = binaryToDecimal(paramInput)
if actualResult != expectedResult:
print("**ERROR! **", paramInput, "should be", expectedResult)
print("Instead, got", actualResult)
else:
print("Success on binary to decimal conversion for", paramInput, "-->", actualResult)
testIsBinary()
testBinaryToDecimal()
non_function_vars.py 2/7
[top][prev][next]
# Using variables that aren't part of any function.
# Not covered in class, but may be of interest to some students.
# by Sara Sprenkle
# create variables that aren't part of any function
non_func = 2
non_func_string = "aardvark"
def main():
func()
print(non_func)
print(non_func_string)
def func():
print("In func: nf =", non_func)
print("In func: nfs =", non_func_string)
# Question: what happens when we try to assign the variables that
# aren't part of a function a value?
# non_func = 7
# non_func_string = "zebra"
# Answer:
main()
non_func = 6
non_func_string = "dog"
print(non_func)
print(non_func_string)
main()
pick4num_wfunctions.py 3/7
[top][prev][next]
# Simulate Pick 4 lottery game - selecting ping pong balls at random
# Modified to figure out if the user entered the winning number
# By CSCI111
from random import *
import sys
# define constants that are easy to change so that our
# program is flexible
NUM_PICKS = 4
MIN_VALUE = 0
MAX_VALUE = 9
NUMFORMAT="####"
pick4winner.py 4/7
[top][prev][next]
# Simulate Pick 4 lottery game - selecting ping pong balls at random
# Modified to figure out if the user entered the winning number
# By CSCI111
from random import *
# define constants that are easy to change so that our
# program is flexible
NUM_PICKS = 4
MIN_VALUE = 0
MAX_VALUE = 9
NUMFORMAT="####"
def main():
pickedNum = input("What is your pick? (Format: " + NUMFORMAT + ") ")
###### handle bad input ######
if len(pickedNum) != NUM_PICKS:
print("Error: incorrect number of digits")
print("You need", NUM_PICKS, "digits")
sys.exit()
###### TODO: handle other bad input ######
winningNum = winNumGenerator()
print("The winning number is", winningNum)
# determine if the input number is a winner
if winningNum == pickedNum:
print("Congratulations! You are very lucky and rich!")
print("We should be friends!")
else:
print("Bummer. You probably should spend your money more wisely.")
def winNumGenerator():
# Generate a winning number, with 4 numbers between 0 and 9
# Returns the winning number
# accumulate the random number
winningNum = ""
for x in range(NUM_PICKS):
# create the random number and make it a string
randnum = str(randint(MIN_VALUE, MAX_VALUE))
# concatenate the newly generated number to the end of the
# winning number
winningNum = winningNum + randnum
return winningNum
practice1.py 5/7
[top][prev][next]
# Exercising your knowledge of variable scope.
#
def main():
num = eval(input("Enter a number to be squared: "))
squared = square(num)
print("The square is", squared)
def square(n):
return n * n
main()
practice2.py 6/7
[top][prev][next]
# Exercising your knowledge of variable scope.
def main():
num = eval(input("Enter a number to be squared: "))
squared = square(num)
print("The square is", squared)
print("The original num was", n)
def square(n):
return n * n
main()
practice3.py 7/7
[top][prev][next]
# Exercising your knowledge of variable scope.
def main():
num = eval(input("Enter a number to be squared: "))
squared = square(num)
print("The square is", computed)
print("The original num was", num)
def square(n):
computed = n*n
return computed
main()
Generated by GNU Enscript 1.6.6.