System Scripting Lab 07

Python Control Flow & Functions

Setup

mkdir lab07
cd lab07
idle3

Exercise 1: Arithmetic Calculator

# Get user inputs
num1 = int(input("Enter a number: "))
num2 = int(input("Enter another number: "))
operator = input("Enter one of +, -, *, /: ")

# Perform operation using if
if operator == "+":
    result = num1 + num2
elif operator == "-":
    result = num1 - num2
elif operator == "*":
    result = num1 * num2
elif operator == "/":
    result = num1 / num2
else:
    print("Invalid operator")
    exit()

# Output result
print(f"{num1} {operator} {num2} = {result}")

Key Concept: Use if/elif for decision making.

Exercise 2: Equation Evaluation

# Input values
x = int(input("Enter x: "))
y = int(input("Enter y: "))

# Calculate expression
result = (x + y) * (x + y)

# Conditional output
if result < 60:
    print(f"Output: ({x} + {y})^2 = {result} is less than 60")
elif 60 <= result <= 70:
    print("Output: 65")
else:
    print(f"Output: ({x} + {y})^2 = {result}")

Key Concept: Multiple conditions using ranges.

Exercise 3: Continuous Sum Script

equal_count = 0

while True:
    num1 = int(input("Enter first number: "))
    num2 = int(input("Enter second number: "))

    if num1 == num2:
        print("Bingo equal numbers")
        equal_count += 1

        if equal_count == 2:
            print("It was fun calculating for you")
            break
    else:
        print("Sum:", num1 + num2)

Key Concept: Loop control + counters.

Exercise 4: Random Number Generator Function

import random

# Function to generate 6 random numbers
def generate_numbers(start, end):
    for _ in range(6):
        print(random.randint(start, end), end=" ")
    print()

# User input
times = int(input("How many times to run: "))
start = int(input("Enter start of range: "))
end = int(input("Enter end of range: "))

# Loop execution
for i in range(times):
    print(f"Run {i+1}: ", end="")
    generate_numbers(start, end)

Key Concept:

Exercise 5: Guess Length Game

import random

# Function to guess length
def guess_length(text):
    actual_length = len(text)

    for attempt in range(1, 13):
        guess = random.randint(1, 20)
        print(f"Attempt {attempt}: Guess = {guess}")

        if guess == actual_length:
            print(f"Success! Length is {actual_length}")
            return

    print("Failed to guess the length in 12 attempts")

# User input
text = input("Enter a word/sentence (max 20 chars): ")

# Validate length
if len(text) > 20:
    print("Input too long")
else:
    guess_length(text)

Key Concept:

Key Exam Tips