Friday

Learn Python Easy way - User Input

Let us learn how user input is received in Python

Let us do the most basic exercise

x = input()
3
print(x)
3



When we assign a variable to the function input() that is enough for Python to wait for the user input and collect any input and store it in that variable.

This works well in a Python Shell, but we will be at a loss if we run this as part of a Pytho script, because we will not understand what the Python script is expecting from us. Therefore we need to add some explainatory text for the user to understand what he is supposed to do.

x = input("input any number : ")
input any number : 44
print("The number you entered is: " +x)
The number you entered is: 44

Now  we will try to add the numbers received from the user

a =  input("Enter any number: ")
b =  input("Enter another number: ")
print("The sum of the numbers you have entered is: " , a+b)

The Shell interaction produces following result

a = (input("Enter any number: "))
Enter any number: 44
b = (input("Enter another number: "))
Enter another number: 67
print("The sum of the numbers you have entered is: " , a+b)
The sum of the numbers you have entered is:  4467

Notice that the sum of 44 and 67 is displayed as 4467, obviously Python is treating these numbers as text string. To let Python Know that we intend to expect integer numbers from the user, append int to the lines

a = int (input("Enter any number: "))
b = int (input("Enter another number: "))

print("The sum of the numbers you have entered is: " , a+b)

Now we can expect correct output

The sum of the numbers you have entered is:  111

So far so good, we could do this in the Python Shell. How about creating a Python script file and running that script in the Python Shell?

Save the following code anywhere on your desktop as .py file, and then open it from within the Python Shell, and then click on Run - Run Module (or press F5)

name = input("Enter your name : ")
age = input("Enter your age : ")
print("Hello " + name + ", so you are " + age + " years old

You will see this interaction in your Python shell

Enter your name : Ishan
Enter your age : 9
Hello Ishan, so you are 9 years old !

Featured Post

Creating Games in Scratch for ICSE Class 6

An Introduction to Creating Games in Scratch  for ICSE Class 6 Hello friends, I hope you have already read the previous post on An Int...