In this post, we will be investigating the input mechanism or linguistic structure in Python programming language. Simply, we will be writing the python program to take input from user and print them on the output screen.
With reference to Python language, it is quite similar to take input from the user as the C# programming language with a slight difference.
Python program to take input from user
name = input("What is your name? ") print("Hello " + name)
Note: In order to execute this program, save it with a suffix of .py, for example, HelloWorld.py –
Ctrl+F5(for Visual Studio Code IDE). According to different Integrated Development Environments (IDEs), the process to run the program may differ, no need to worry about it.
What is your name? DroxElement Hello DroxElement
First we have took a variable as name where the input() (which acts as the input source from the user to the program) is assigned as shown in the program above.
name = input("What is your name?")
After using the input(), we encountered the print() that prints the specified message in the output screen.
print("Hello " + name)
But there is one dilemma, that is the input() only takes the input in the form of string data type so in order to perform the mathematical calculations with the integer values we have to perform the type conversion of string carried value to the integer data type.
The process of type conversion can be illustrated in the program below.
first_num = input("Enter first number: ") second_num = input("Enter second number: ") #Addition Sum = int(first_num) + int(second_num) print(Sum)
For the program as above, first we took two variables first_num and second_num where both the variables are assigned with the input() that means the first_num variable will hold a data in the string form and second_num as well.
After that, we encountered the comment as we know comments starts with the special character known as hash “#“.
........... ........... #Addition ...........
Then we have a variable as Sum where we have done the type conversion of the two variables from string to integer.
Sum = int(first_num) + int(second_num)
The function int(first_num) converted the value or data hold by the variable first_num from string data type to integer data type and similar goes with the second_num variable.
And the desired output for the program with the type conversion as mentioned above is shown below.
Enter first number: 5 Enter second number: 2 7
We can perform type conversion from any data type to any other data type with the syntax as mentioned above. Some of the functions used for the type conversion is listed as below.
Conversion to Integer --> int(.....) Conversion to Character --> char(.....) Conversion to Double --> double(.....)
That’s it for this article, I hope you found this informative. Now, take this program to any of the IDE as per your desire and embellish or practice it a bit.
Also Read: Python Program with Arithmetic Operators