Previous Index Next

Reading input from Keyboard

The input function reads data that has been entered by the keyboard and returns that data, as a string.

Reading String

# Get the user's name. 
name = input("Enter your name: ")  

# Print a greeting to the user. 
print("Hello", name) 

Output

Enter your name: Saksham
Hello Saksham

Reading Integer

If we input a number than it returns as string. To convert string number to int we will use int() function that converts a string to an integer.

# Get the user's age.
age = int(input("What is your age? "))

# Display the age.
print("Age:", age)

Output

What is your age? 16
Age: 16

Reading Floating Point

Similarly, if we input a floating number than it returns as string. To convert string number to float we will use float() function that converts a string to float number.

# Get the length of rectangle.
length = float(input('Enter length '))

# Get the width of rectangle.
width = float(input('Enter width '))

# Calculate the area and assign the result to area variable.
area = length * width

# Display the area.
print('Area of rectangle is', area)

Output

Enter length 12.6
Enter width 6.2
Area of rectangle is 78.12

Garbage collection

Look at the following code:

amount = 10 #Line 1
amount = 5  #Line 2
print(amount)

When you assign a value to a variable, the variable will reference that value until you assign it a different value. For example,  The statement in Line 1 creates a variable named amount and assigns it the value 10.

garbage collection

Then, the statement in Line 2 assigns a different value, 5, to the amount variable.

Following figure shows how this changes the amount variable.

garbage collection

The old value, 10, is still in the computer’s memory, but it can no longer be used because it isn’t referenced by a variable.

When a value in memory is no longer referenced by a variable, the Python interpreter automatically removes it from memory. This process is known as garbage collection.

Reassigning a Variable to a Different Type

A variable in Python can refer to items of any type. For example, when you assign an integer value to a variable and in the next statement you can reassign the variable to a new value of different types.

>>> x = 200
>>> print(x)
200
>>> x = 'Alex Joseph'
>>> print(x)
'Alex Joseph'

Previous Index Next