Wednesday, September 16, 2020

Python-Variables (input() and print())

 Variables represent the label to the storage location, whose value is manipulated during program execution.

In Python we can create the variable and assign the value to it. There is no need to explicitly define the data type of the variable.

For example

x=10 

In this case x is the variable name and its value is 10 and data type of variable x is int

type(<<variable>>) is used to find the data type of a variable


eg type(x) will return the datatype of x variable (<class ,'int'>)


Dynamic Typing

In Python type of a variable can be changed which is called the Dynamic typing

eg x=10

print(x)    # it will print 10

x="Hello India"

print(x)     # it will print Hello world

Multiple assignments

In Python, we can assign the same value to multiple variables

eg x=y=z=1 

In this case,   x,y,z are variables and all are having value =1

eg x,y=10,12

In this case, x=10 and y=12

eg x,y=y,x

In this case, values are swapped means x has 12 and y has 10 value

Input and Output 

input() function is used to get the input from the user to a variable. By default input() returns a value of String type. But in Python, we can use int() and float() to read values as integer and float type respectively.

eg

name=input("Enter your name")

In this case, name is the variable and when this statement is executed then it will read the value in String format.

# Write A Progam to Enter 2 numbers and print the sum of these 2 values
num1=int(input("Enter first number"))
num2=int(input("Enter sec number"))
print("Sum=" ,num1+num2)
output
Enter first number10
Enter sec number20
Sum= 30

print() 

print() function is used to send the output to the standard output device in most of the cases it is Monitor.

The full syntax of print() is:

print(*objects, sep=' ', end='\n', file=sys.stdout, flush=False)

print() Parameters

  • objects - object to the printed. * indicates that there may be more than one object
  • sep - objects are separated by sep. Default value' '
  • end - end is printed at last
  • file - must be an object with write(string) method. If omitted it, sys.stdout will be used which prints objects on the screen.
  • flush - If True, the stream is forcibly flushed. Default valueFalse

Note: sependfile, and flush are keyword arguments. If you want to use sep argument, you have to use:


Examples

print("Hello World") # output will be Hello World
Course="Python"
print(Course) # output will be Python
print("Course=",Course) # output wlll be Course=Python
num=20
print(num) # output will be 20
print("num=",num) # output will be num=20
print("Hello", end=",")
print("World") # output will be Hello,World
a = 5
print("a =", a, sep='00000') # output will be a =000005
print("a =", a, sep='0', end='') # output will be a =05

0 comments:

Post a Comment