Software Construction


"""
Compute Pythagoras' Theorem

written by d.brotherston@unsw.edu.au as a COMP(2041|9044) lecture example
translated from perl written by andrewt@cse.unsw.edu.au
"""

import math

x = float(input("Enter x: "))
y = float(input("Enter y: "))

pythagoras = math.sqrt(x**2 + y**2)

print(f"Square root of {x} squared + {y} squared is {pythagoras}")

"""
Read numbers until end of input (or a non-number) is reached
Then print the sum of the numbers

written by d.brotherston@unsw.edu.au as a COMP(2041|9044) lecture example
translated from perl written by andrewt@cse.unsw.edu.au
"""

from sys import stdin

sum = 0

for line in stdin:
    try:
        sum += int(line)
    except ValueError as e:
        print(e)

print(f"Sum of the numbers is {sum}")

"""
Simple example reading a line of input and examining characters
written by d.brotherston@unsw.edu.au as a COMP(2041|9044) lecture example
"""

try:
    line = input("Enter some input: ")
except EOFError:
    print("could not read any characters")
    exit(1)

n_chars = len(line)
print(f"That line contained {n_chars} characters")

if n_chars > 0:
    first_char = line[0]
    last_char = line[-1]
    print(f"The first character was '{first_char}'")
    print(f"The last character was '{last_char}'")

"""
Reads lines of input until end-of-input
Print "snap!" if two consecutive lines are identical

written by d.brotherston@unsw.edu.au as a COMP(2041|9044) lecture example
translated from perl written by andrewt@cse.unsw.edu.au
"""

last = None

while True:
    try:
        curr = input("Enter line: ")
    except EOFError:
        print()
        break

    if curr == last:
        print("Snap!")
        break

    last = curr

"""
Create a string of size 2^n by concatenation
written by d.brotherston@unsw.edu.au as a COMP(2041|9044) lecture example
"""

import sys

if len(sys.argv) != 2:
    print(f"Usage: {sys.argv[0]}: <n>")
    exit(1)

n = 0
string = "@"

while n < int(sys.argv[1]):
    string *= 2
    # or `string += string`
    # or `string = string + string`
    n += 1

print(f"String of 2^{n} = {len(string)} characters created")