Contents
- binaryToDecimal.py
- demo_str.py
- escape_sequences.py
binaryToDecimal.py 1/3
[top][prev][next]
# Converts a binary number into a decimal.
# Iterates over the exponents.
# Exercise: implement two ways:
# --> iterate over the binary string from the last character to the first
# --> iterate over the binary string from the first character to the last
# By CSCI111 (in progress)
import test
def main():
print("This program converts a binary number into a decimal number.")
binNum = input("Enter a binary number: ")
print(binNum, "has a decimal value of", binaryToDecimal(binNum))
def testBinaryToDecimal():
"""
tests the binaryToDecimal function
"""
test.testEqual( binaryToDecimal("0"), 0)
test.testEqual( binaryToDecimal("1"), 1)
test.testEqual( binaryToDecimal("10"), 2)
test.testEqual( binaryToDecimal("110"), 6)
test.testEqual( binaryToDecimal("1101"), 13)
test.testEqual( binaryToDecimal("10110"), 22)
test.testEqual( binaryToDecimal("000"), 0)
test.testEqual( binaryToDecimal("0110"), 6)
def binaryToDecimal(binaryNum):
"""
Converts binary number into a decimal number
Pre: binaryNum should be a string containing only 0s and 1s
Post: convert binaryNum into a decimal value and return that value
as an integer
"""
decimal = 0
for i in range(len(binaryNum)):
# find the values of 2
# then multiply by the character at
newn = 2 ** i
decimal += newn * int(binaryNum[i])
return decimal
testBinaryToDecimal()
#main()
demo_str.py 2/3
[top][prev][next]
# Demonstrate long strings and escape sequences
# by Sara Sprenkle
string = """This is a long string.
Like, really long.
Sooooo loooooong"""
print(string)
print("\n") # how many blank lines does this print?
print("To print a \\, you must use \"\\\\\"")
escape_sequences.py 3/3
[top][prev][next]
# Practice with escape sequences
# By CS111
# Display To print a tab, you must use '\t'.
print("To print a tab, you must use \'\\t\'")
print("To print a tab, you must use '\\t'")
print('To print a tab, you must use \'\\t\'')
# how many blank lines does this print?
print("\n")
# Display I said, "How are you?"
print("I said, \"How are you?\"")
print('I said, "How are you?"')
Generated by GNU Enscript 1.6.6.