Reading user input in Python is simple with the
We will create a python program to accept the width and height of a rectangle and calculate the area and perimeter.
Writing our code directly in Python idle console is easy but less useful. To use our program stand-alone, we have to save our code as a python file. Here are the steps.
I will use
Reading user input in Python is simple with the
something = input("Please enter something: ")
The input function accepts a string argument to print on the screen when prompting user input.
>>> something = input("Please enter something: ")
Please enter something: Learning Python
>>> something
'Learning Python'
Note that when you use
width = float(input('Please enter the width: '))
height = float(input('Please enter the height: '))
area = width * height
perimeter = 2 * (width + height)
print("Your rectangles area is: ", area )
print("Your rectangles perimeter is: ", perimeter )
The first two lines accept the width and height of the rectangle. Lines 3 and 4 calculate the area and perimeter.
Lines 4 and 5 print the calculated values on the screen using the
To run the program, click
Please enter the width: 24
Please enter the height: 10
Your rectangles area is: 240.0
Your rectangles perimeter is: 68.0
We can use the
shape = input('Please enter the shape you want to calculate the area of: ')
Now we can use the user-entered shape to prompt further inputs necessary to do our calculation.
width = float(input('Please enter the width of your %s: ' %(shape )))
height = float(input('Please enter the height of your %s: ' %(shape )))
Similarly, let's apply the same to our screen prints.
print('Your %s area is: %s' %(shape, area))
print('Your %s perimeter is: %s' %(shape, perimeter))
Here is the complete code.
shape = input('Please enter the shape you want to calculate the area of: ')
width = float(input('Please enter the width of your %s: ' %(shape )))
height = float(input('Please enter the height of your %s: ' %(shape )))
area = width * height
perimeter = 2 * (width + height)
print('Your %s area is: %s' %(shape, area))
print('Your %s perimeter is: %s' %(shape, perimeter))
Please enter the shape you want to calculate the area of: Rectangle
Please enter the width of your Rectangle: 24
Please enter the height of your Rectangle: 10
Your Rectangle area is: 240.0
Your Rectangle perimeter is: 68.0
Python uses C-style formatting to format strings. The % is used to format a variable or a tuple of variables.
In my code example, I have
The shape value replaces the first
Here are some primary placeholders we commonly use: