Study Guide

6.2.6 Adding to a Value CodeHS Answers

6.2.6 Adding to a Value CodeHS Answers

The most common answer is:

num1 = 10
num2 = int(input())
def add_sum():
sum = num1+num2
print(sum)
add_sum()

This code snippet aims to add num2 (entered by the user) to num1 and print the result. However, to make the function more reusable and avoid using global variables inside the function, you might consider passing num1 and num2 as parameters to the function.

Here’s how we can improve the code:

num1 = 10
num2 = int(input("Enter a number to add to 10: "))

def add_sum(number1, number2):
    total_sum = number1 + number2
    print(total_sum)

add_sum(num1, num2)

This version of the program:

  • Prompts the user to input a number, which is converted to an integer and stored in num2.
  • Defines a function add_sum that takes two parameters, adds them together, and prints the result.
  • Calls the add_sum function with num1 and num2 as arguments.