User Input in Python

python-user-input-ipcisco

Python User Input

In python programming, sometimes we need inputs from the users. In other words, we ask something to the user of the program and wait some characters from him/her. Then, we use these inputs in the other parts of the program. In this lesson, we will focus on this Python user input. We will learn, how to get an input from a user with python programming.

 

To get an input from the user, we use input() method. This is true for higher versions of Python. If you are using Python 2.7 or lower, this method is raw_input(). But, here we will use the new version of this method.

 

So, why we need any input from the user? Basically, we can use this function in many areas and for many questions. We can ask a username, a password basically. We can ask age, sex, profession, address etc. We can ask for a character, for a number, for anything that we can write with keyboard. This is limited with your imagination and with your program.

 

Let’s given an example for input method in python and learn it better. We can start by asking a username ana a password like many programs ask at their beginning.

 

user = input("What is Your Username:")
pwd = input("What is Your Password:")
print("Username is: " + user)
print("Password is: " + pwd)
What is Your Username: Gokhan

 

What is Your Password: Kosem

 

What is Your Username: Gokhan
What is Your Password: Kosem
Username is: Gokhan
Password is: Kosem

 

python-user-input-ipcisco

 

Now, let’s do another user input example. With this example, let’s get a number from the user, and print its square.

 

number = input("Please Enter A Number:")
number=int(number)
Square = number * number
print("The square of your number is {}".format(Square))

 

The program will ask us;

 

Please Enter A Number:

 

If we enter 9, the output will be:

 

Please Enter A Number:9
The square of your number is 81

 

user-input-in-python-ipcisco

 

Now, with another example, let’s get three input form the user.

 

name = input("Please Enter Your Name:")
age = input("Please Enter Your Age:")
age=int(age)
profession = input("Please Enter Your Profession:")
print("{} is an {} years old {}.".format(name,age,profession))

 

The code will ask us the questions and the final output of this code will be like below:

 

Please Enter Your Name:Gokhan
Please Enter Your Age:37
Please Enter Your Profession:Network Engineer
Gokhan is an 37 years old Network Engineer.

 

Getting user input is a widely used methods in python programming. Especially in advanced python programs, you will need this python user input function too much. So, you can increase example about this important method of python.

Back to: Python Programming Course

Leave a Reply

Your email address will not be published. Required fields are marked *

Python Programming Course

Collapse
Expand