Variables works like containers in computer memory
that can be used to store values. Variable's name is a label for that memory
location (container). Variables can store different values, but one at a time. it's
value can be changed during the program execution.
In Python, a variable does not need to be declared before
assigning a value to it. We don't need to specify the datatype of a variable,
they can allocate memory space based on the type of value which will be
assigned to it.
Assignment operator is used to store value in a variable.
Variable must be on the left hand side of the operator. The value of the right
hand side of the assignment operator is assigned to the left hand side variable
of the operator.
The following statement will create a variable
(container) with the name “num”. It stores the value 10 which is assigned to
“num” variable using assignment (=) operator.
num=10
Here, 10 is an integer value which is assigned into num.
So, num is an int type variable.
type() is a built-in function and it returns the type of
given object.
type(num) This statement will return an int.
We can assign single value to multiple variables
num1=num2=num3=10
We can also assign multiple value to multiple variables
num1, num2,
num3=10, 5, 9
Python supports different types of data types such as
numeric, string, list, boolean etc. The int, float and complex are numeric data
types.
Output data can be displayed to the standard output
device like monitor from the computer memory using the built-in function
print().
Python code for adding two numbers
# 5 is assigned to num1, num1 is an integer variable
num1=5
num1=5
#
10 is assigned to num2, num2 is an integer variable
num2=10
num2=10
# the result of num1 + num2 is also an int value which is stored into sum
sum=num1+num2
#print() display the value of sum to the screen
print(sum)
User input data can be entered into the computer memory from standard input device like keyboard. Python uses a built-in function “input()” to take user input from keyboard or other input devices. It always returns a string. If we want a numeric type, then we need to convert the string to the int value using the built-in function int().
Python code for adding two numbers by user input
Example 1
#take an input from user and assigned it into num1
num1=input("Enter 1st number:")
#take an input from user and assigned it into num2
num2=input("Enter 2nd number:")
#convert string into int datatype using the function int() and the result of num1 + num2 is also an int value which is stored into sum
sum =
int(num1) + int(num2)
print("Sum
=", sum)
Example 2
#convert string into int datatype using the function int() at the time of user input
num1=int(input("Enter 1st number:"))
num2=int(input("Enter 2nd number:"))
sum = num1 +
num2
print(“Sum=”, sum)
No comments:
Post a Comment
please do not enter any spam link in the comment box