In this article, we would discuss how to write/execute your first Python program. First, we will discuss input() function which is used to get the input from the user. Later, modules will be imported for arithmetic operations. Lastly, print() function – to display the results.
We have used Python v3.7.4. Ubuntu users get the latest stable version of Python installed by default. But for some reason, if its not there then you may want to check the article here.
Also, to check the version of Python installed, open the terminal and issue –
Your first Python program
#This is your first Python program """Three quotes are used for multi-line comments""" print("Hello World!") x=input("Enter number x: ") y=input("Enter number y: ") conc=x+y print("x & y as string: ", conc) #It prints concatenated values print("\n") a=int(input("Enter number a: ")) b=int(input("Enter number b: ")) add=a+b print("a & b as integers: ", a+b) #It prints the sum of two variables a and b print("\n") from math import sqrt p=int(input("Enter a number to get Square Root of: ")) r=sqrt(p) print("The square root of the number provided: ", r) #sqrt() - square root function
We will explain our code next.
Though it is not mandatory, but we must mention what our code is all about. Hence, we put comments in our code. Therefore, if its a single-line comment then put # in the beginning of the line. Otherwise, for multi-line comments – our comment must start and end with three quotes – “””.
print(“Hello World!”) – prints the message Hello World!
By default, input() function takes the values as string. So, we asked the user to input two values for variables x & y. And, then stored the summation of values in variable conc. Since, input() function treats any value as string. Hence, it will print the concatenated values.
print(“\n”) – to print the next line.
Now, we will make the input() function to take integer values by preceding the function with int(). Enter the values of a and b. This time around, it will print the summation of values provided.
Lastly, we imported sqrt() function from a module named – math. Thereafter, user enters a value to get its square root. Variable p stores the value of input number. And, the variable r stores the result from sqrt() function. Again, print() function prints the desired result.
Execute your Python program
Open a text editor and copy – paste the above code. Save the file as first-code.py. .py is a Python extension.
Thereafter, open a terminal. And, use cd command to head to the directory where our file was saved.
And, issue –
User will be asked to enter values. Final outcome would resemble, although values would differ –
Hello World! Enter number x: 12 Enter number y: 65 x & y as string: 1265 Enter number a: 45 Enter number b: 85 a & b as integers: 130 Enter a number to get Square Root of: 49 The square root of the number provided: 7.0
In conclusion, we have discussed how to write your first Python program.