Vocab
Random
Flow Control
Concepts
Programming
100

What is a variable in Python?

a variable is a named item, such as x or num_people, that holds a value.

100

Convert to decimal:
1 1 0 1 (base 2)

1 1 0 1 = 13

100

Write a while loop that prints numbers 1 through 5.

i = 1

while i <= 5:

    print(i)

    i += 1

100

What is the difference between a string and an integer in Python?  

Strings are characters, and integers are numbers.

100

Write a program using inputs age (years), weight (pounds), heart rate (beats per minute), and time (minutes), respectively. Output the average calories burned for a person.
Formula: Calories = (Age x 0.2757) + (Weight x 0.03295) + (Heart Rate x 1.0781) — 75.4991) x Time / 8.368 

Output each floating-point value with two digits after the decimal point, which can be achieved as follows:
print(f"Calories: {calories:.2f} calories")

Ex: If the input is:

49 155 148 60

then the output is:

Calories: 736.21 calories

# Get user input

age = int(input())

weight = int(input())

heart_rate = int(input())

time = int(input())

# Calculate calories using the given formula

calories = (((age * 0.2757) + (weight * 0.03295) + (heart_rate * 1.0781) - 75.4991) * time) / 8.368

# Output with two decimal places

print(f"Calories: {calories:.2f} calories")


200

Define function in programming.

A program may perform the same operation repeatedly, causing a large and confusing program due to redundancy. Program redundancy can be reduced by creating a grouping of predefined statements for repeated operations, known as a function.

200

Construct a flowchart for the following code segment:
age = int(input("Enter your age: "))

if age >= 18:

    print("You can vote.")

else:

    print("You are not eligible to vote.")

look at their submissions

200

Write a for loop that prints each item in the list ["apple", "banana", "cherry"].

fruits = ["apple", "banana", "cherry"]

for item in fruits:

  print(item)

200

What are parameters and how do they work?

Parameters are variables defined within the parentheses of a function's definition. They serve as placeholders for the values (arguments) that will be passed into the function when it is called. Parameters allow functions to be flexible and operate on different data without needing to be rewritten for each specific case.
Ex:

    def greet(name, age):

        print(f"Hello, {name}! You are {age} years old.")

    greet("Alice", 30)

 

200

Given the user inputs, complete a program that does the following tasks:

  • Define a set, fruits, containing the user inputs: my_fruit1, my_fruit2, and my_fruit3.
  • Add the user inputs, your_fruit1 and your_fruit2, to fruits.
  • Add the user input, their_fruit, to fruits.
  • Add your_fruit1 to fruits.
  • Remove my_fruit1 from fruits.

Observe the output of each print statement carefully to understand what was done by each task of the program.

Note: For testing purposes, sets are printed using sorted() for comparison, as in the book's examples.

Ex: If the input is:

apple peach lemon apple pear plum

the output is:

['apple', 'lemon', 'peach'] 

['apple', 'lemon', 'peach', 'pear'] 

['apple', 'lemon', 'peach', 'pear', 'plum']

['apple', 'lemon', 'peach', 'pear', 'plum'] 

['lemon', 'peach', 'pear', 'plum']

my_fruit1 = input()

my_fruit2 = input()

my_fruit3 = input()

your_fruit1 = input()

your_fruit2 = input()

their_fruit = input()

# 1. Define a set, fruits, containing my_fruit1, my_fruit2, and my_fruit3

fruits = {my_fruit1, my_fruit2, my_fruit3}

print(sorted(fruits))

# 2. Add your_fruit1 and your_fruit2 to fruits

fruits.add(your_fruit1)

fruits.add(your_fruit2)

print(sorted(fruits))

# 3. Add their_fruit to fruits

fruits.add(their_fruit)

print(sorted(fruits))

# 4. Add your_fruit1 to fruits (again)

fruits.add(your_fruit1)

print(sorted(fruits))

# 5. Remove my_fruit1 from fruits

fruits.remove(my_fruit1)

print(sorted(fruits))

300

What is a loop, and name two types.

A loop is a program construct that repeatedly executes the loop's statements (known as the loop body) while the loop's expression is true; when the expression is false, execution proceeds past the loop. Each time through a loop's statements is called an iteration.

ex: while, for

300

Determine the output of the following code:

my_str = "The cat in the hat" 

print(my_str[0:3])

The slice contains characters in positions 0, 1, and 2: "The".

300

Write code using an if-elif-else structure that checks if a number is positive, negative, or zero.

  if number > 0:
    return "Positive"
  elif number < 0:
    return "Negative"
  else:
    return "Zero"

300

What does the return keyword do in a function? Give an example scenario.

The return keyword in Python is used to send a value back from a function to the part of the program that called it. It ends the function's execution and gives the result for further use.

Ex:

def get_area(length, width):

    return length * width


area = get_area(5, 3)

print("Area:", area)


Without return, a function might only print something or perform an action, but it won’t give back a result that can be stored or used elsewhere in your program. 


 

300

Write a program that takes a date as input and outputs the date's season in the northern hemisphere. The input is a string to represent the month and an int to represent the day.

Ex: If the input is:

April 11

the output is:

Spring

In addition, check if the string and int are valid (an actual month and day).

Ex: If the input is:

Blue 65

the output is:

Invalid 

The dates for each season in the northern hemisphere are:
Spring: March 20 - June 20
Summer: June 21 - September 21
Autumn: September 22 - December 20
Winter: December 21 - March 19

# Dictionary of months with their maximum number of days

month_days = {

    "January": 31,

    "February": 29,  # accounting for leap years, for simplicity

    "March": 31,

    "April": 30,

    "May": 31,

    "June": 30,

    "July": 31,

    "August": 31,

    "September": 30,

    "October": 31,

    "November": 30,

    "December": 31

}

# Read input

month = input()

day = int(input())

# Check if input is a valid month and day

if month not in month_days or day < 1 or day > month_days[month]:

    print("Invalid")

else:

    # Determine the season

    if (month == "March" and day >= 20) or month in ["April", "May"] or (month == "June" and day <= 20):

        print("Spring")

    elif (month == "June" and day >= 21) or month in ["July", "August"] or (month == "September" and day <= 21):

        print("Summer")

    elif (month == "September" and day >= 22) or month in ["October", "November"] or (month == "December" and day <= 20):

        print("Autumn")

    else:

        print("Winter")

400

What is an index?

An index is an integer matching a specific position in a string's sequence of characters.

400

Create a list of numbers from 1 to 10 using a loop.

numbers = []  # Initialize an empty list to store the numbers
# Loop from 1 to 10 (range(1, 11) generates numbers from 1 up to, but not including, 11)
for i in range(1, 11):
    numbers.append(i)  # Add each number to the list
print(numbers)

400

Write a program whose input is two integers. Output the first integer and subsequent increments of 5 as long as the value is less than or equal to the second integer.

Ex: If the input is:

-15 10

the output is:

-15 -10 -5 0 5 10 

Ex: If the second integer is less than the first as in:

20 5

the output is:

Second integer can't be less than the first.

For coding simplicity, output a space after every integer, including the last. End the output with a newline.

# Get two integers from user

start = int(input())

end = int(input())

# Check if second integer is less than the first

if end < start:

    print("Second integer can't be less than the first.")

else:

    current = start

    while current <= end:

        print(current, end=' ')

        current += 5

    print()  # For ending the line

400

What is the difference between a while loop and a for loop in Python?

For loop is used to iterate over a sequence of items. While loop is used to repeatedly execute a block of statements while a condition is true.

400

Write a program that gets a list of integers from input, and outputs negative integers in descending order (highest to lowest).

Ex: If the input is:

10 -7 4 -39 -6 12 -2

the output is:

-2 -6 -7 -39 

For coding simplicity, follow every output value by a space. Do not end with newline.

# Get list of integers from input

numbers = list(map(int, input().split()))

# Filter negative numbers and sort in descending order

negatives = sorted([num for num in numbers if num < 0], reverse=True)

# Print the result with a space after each number, no newline at the end

for num in negatives:

    print(num, end=' ')

500

What is the difference between a list and a dictionary?

A list is a mutable container, meaning the size of the list can grow or shrink and elements within the list can change. A list is also a sequence; thus, the contained objects maintain a left-to-right positional order.

A dictionary is another type of container object that is different from sequences such as strings, tuples, and lists. Dictionaries contain references to objects as key-value pairs — each key in the dictionary is associated with a value, much like each word in an English language dictionary is associated with a definition.

500

Write a function that returns the reverse of a string.

def rev_string(x):

  return x[::-1] #Slice the string starting at the end of the string and move backwards. 

mystmt = rev_string("We will all get 100 tomorrow.")

print(mystmt)

500

Many user-created passwords are simple and easy to guess. Write a program that takes a simple password and makes it stronger by replacing characters using the key below, and by appending "!" to the end of the input string.

i becomes 1

a becomes @

m becomes M

B becomes 8

s becomes $

Ex: If the input is:

mypassword

the output is:

Myp@$$word!

Hint: Python strings are immutable, but support string concatenation. Store and build the stronger password in the given password variable.

# Get user input

weak_password = input("Enter a password to strengthen: ")

# Create a new, stronger password by building it character by character

strong_password = ""

# Define character replacement rules

for char in weak_password:

    if char == 'i':

        strong_password += '1'

    elif char == 'a':

        strong_password += '@'

    elif char == 'm':

        strong_password += 'M'

    elif char == 'B':

        strong_password += '8'

    elif char == 's':

        strong_password += '$'

    else:

        strong_password += char

# Append "!" to the end

strong_password += '!'

# Output the result

print("Stronger password:", strong_password)

500

What is file I/O in Python? What are the steps to read from a file?

The process of interacting with files on a computer's file system. This interaction involves reading data from files (input) and writing data to files (output), allowing programs to store and retrieve information persistently.

- Open the file: Use the built-in open() function, providing the file path and the desired mode. For reading, the mode is typically 'r' (read mode) or 'rt' (read text mode, which is the default).
- Read the content: Once the file is open, various methods can be used to read its content:

- read(): Reads the entire content of the file as a single string.

- readline(): Reads a single line from the file.

- readlines(): Reads all lines from the file and returns them as a list of strings.

- Iteration: The file object itself can be iterated over to read lines one by one, which is memory-efficient for large files.

500

Write a function driving_cost() with parameters miles_per_gallon, dollars_per_gallon, and miles_driven, that returns the dollar cost to drive those miles. All items are of type float. The function called with arguments (20.0, 3.1599, 50.0) returns 7.89975.

The main program's inputs are the car's miles per gallon and the price of gas in dollars per gallon (both float). Output the gas cost for 10 miles, 50 miles, and 400 miles, by calling your driving_cost() function three times.

Output each floating-point value with two digits after the decimal point, which can be achieved as follows:
print(f"{your_value:.2f}")

Ex: If the input is:

20.0 3.1599

the output is:

1.58 7.90 63.20

Your program must define and call a function:
def driving_cost(miles_per_gallon, dollars_per_gallon, miles_driven)

def driving_cost(miles_per_gallon, dollars_per_gallon, miles_driven):

    # Calculate and return the cost

    return (miles_driven / miles_per_gallon) * dollars_per_gallon

def main():

    # Get input values

    mpg = float(input())

    dpg = float(input())

    # Call driving_cost for specified distances and print results

    print(f"{driving_cost(mpg, dpg, 10.0):.2f}")

    print(f"{driving_cost(mpg, dpg, 50.0):.2f}")

    print(f"{driving_cost(mpg, dpg, 400.0):.2f}")

# Run the main function

main()

M
e
n
u