Table of Contents

Add 5 to a User Input Number

Example Description
Python code: Adds 5 to user input using a function. Displays id() before and after the call to check memory location change.

Introduction:

This Python code shows how to add 5 to a user input number using a function. It also displays the id() of the argument before and after the function call to check if the parameter is assigned a new memory location.

Code:

#Function to add 5 to a user input number
#The requirements are listed below:
 #1. Display the id()of argument before function call.
 #2. The function should have one parameter to accept the argument
 #3. Display the value and id() of the parameter.
 #4. Add 5 to the parameter
 #5. Display the new value and id()of the parameter to check whether the parameter is assigned a new memory location or not.
def incrValue(num): 
 #id of Num before increment
 print("Parameter num has value:",num,"\nid =",id(num)) 
 num = num + 5 
 #id of Num after increment
 print("num incremented by 5 is",num,"\nNow id is ",id(num)) 
number = int(input("Enter a number: "))
print("id of argument number is:",id(number)) #id of Number
incrValue(number)

Logic:

  1. The code defines a function named incrValue that takes a parameter num.
  2. It first displays the value and id() of the parameter before incrementing it by 5.
  3. Then, it displays the new value and id() of the parameter to check if it has been assigned a new memory location.
  4. The main part of the code prompts the user to enter a number
  5. Then displays the id() of the argument, and calls the incrValue function with the number as the argument.

Output:

Enter a number: 10

> id of argument number is: 140732724484144

> Parameter num has value: 10

> id = 140732724484144

> num incremented by 5 is 15

> Now id is 140732724484304