In this example we will see a program that would print the value contained by a variable.
The example given below would print the value stored in the variable
mynum = 7 print(mynum)
- The first line is a comment. Like other languages, comments in python are not the part of our programs. They are included in the programs just to make the program more readable.
- In the second line we have declared a variable named ‘mynum’ and assigned it a value 7.
- In the third line we have used the print function and have passed the variable mynum as argument.
Note: A variable can contain only one value at a time. However, the value can be an integer number, a floating point number, a character or a string(Series of characters).
Let us see this example for different types of values
For string value:
message = "Where there is a will, there is a way" print(message)
Where there is a will, there is a way
For float value:
num = 4.1 print(num)
Taking user input
This example would take a value from the user.
mynum = int(input("Enter a number")) print(mynum)
When this program executes, the user would see a message “Enter a number”. When the user press enter after entering the number, the number would be displayed on the output screen.
The input function in python is used to take input from the user. The input function always returns a string. If the user enters a number instead, then we will get that number in the string form. Suppose if the user enter 7, we would get ‘7’ (Number in the string form). That is why we have put input() function inside the int() function. The int function casts or converts the string in the integer form.
When this program runs, the user would see a message-“Enter a number”. When the user enter the number, the number is returned in string form. The int() function then convert the returned number in integer form and then the number is stored in the variable ‘mynum’. It would then be printed by using the print function.