Python Input

In this tutorial you will learn:

  • Input Function
  • Input in Python 2.7
  • Input in Python 3.6
  • Making a simple Calculator

Input Function

This is an important function in programming languages almost all programming languages offer some kind of input function to take values from the user.

Input in Python 2.7

Python 2.7 is a bit different from 3.6 and it has a different function for input which is called raw input function. Raw input function takes input from the user and stores it into a variable which can be used while the program is running.

Example:

  1. firstName = raw_input("Your First Name: ")
  2. lastName  = raw_input("Your Last Name: ")
  3. organization = raw_input ("Your Organization: ")
  4. print("Your details are: ")
  5. print("Full Name: ", firstName," ",lastName)
  6. print("Your organization: ", organization)

Input in Python 3.6

In Python 3.6 the input function was changed from raw input to input. It works in exactly the same way that it takes values from user which are typed and returns a value. In order to get a certain type from it we need to type case the values.

Example:

  1. num1 = int ( input ("Enter first number") )
  2. num2 = int ( input ("Enter second number") )
  3. sum = num1 + num2
  4. print("Addition of two number is: ", sum)
  5. num1 = float ( input ("Enter first number") )
  6. num2 = float ( input ("Enter second number") )
  7. subtraction = num1 - num2
  8. print("Subtraction of two floating point numbersis: ", subtraction)

Making a simple Calculator

Now let’s make a simple calculator using Python. It will have functionality to add, subtract, multiply and divide. In order to develop this program we need to think logically and write everything step by step. So let’s list down the steps that we need to make a calculator and then write the code along with it.

1. The first step is to take input from the user asking which operation needs to be performed and then ask for the first and second numbers.

  1. selection = int(input("\n\nEnter selection ( 1 Multiply \n 2 Divide  \n 3 Subtract \n 4 Add ): "))
  2. num1 = float(input("Enter first number: "))
  3. num2 = float(input("Enter second number: "))

2. Second step is to write the functions for performing the arithmetic operations such as multiply, divide, subtract and add.

  1. def multiply(x, y):
  2.    return x * ys
  3. def divide(x, y):
  4.    return x / y
  5. def subtract(x, y):
  6.    return x - y
  7. def add(x, y):
  8.    return x + y

3. Third step is to perform the operation based on the selection and show the result.

  1. if selection == 1:
  2.    print(num1,"*",num2,": ", multiply(num1,num2))
  3. elif selection == 2:
  4.    print(num1,"/",num2,": ", divide(num1,num2))
  5. elif selection == 3:
  6.    print(num1,"+",num2,": ", add(num1,num2))
  7. elif selection == 4:
  8.    print(num1,"-",num2,": ", subtract(num1,num2))

Add new comment