10/16/18

Python-Taking User input, Type Conversion & Formatting Output



Taking User Input

num1=input("Enter First Number:") # Takes data in String format input:10
num2=input("Enter Second Number:") # Takes data in String format  input:20
print(num1+num2) # concatenates strings output: 1020

############################

num1=int(input("Enter First Number:"))
num2=int(input("Enter Second Number:"))
print(num1+num2)

##########################
num1=input("Enter First Number:")
num2=input("Enter Second Number:")
print(int(num1)+int(num2))



Type Conversion Example-1

num1=input("Enter Decimal Number1:") #10.5
num2=input("Enter Decimal Number2:") #10.6
print(num1+num2) #Concatenates 10.510.6

###############################################

num1=float(input("Enter Decimal Number1:"))
num2=float(input("Enter Decimal Number2:"))
print(num1+num2)

#################################################
num1=input("Enter Decimal Number1:")
num2=input("Enter Decimal Number2:")
print(float(num1)+float(num2))

Type Conversion Example-2

num1=input("Enter Decimal Number1:") #10.5
num2=input("Enter Decimal Number2:") #10.6
print(num1+num2) #Concatenates 10.510.6

###############################################

num1=float(input("Enter Decimal Number1:"))
num2=float(input("Enter Decimal Number2:"))
print(num1+num2)

#################################################
num1=input("Enter Decimal Number1:")
num2=input("Enter Decimal Number2:")
print(float(num1)+float(num2))


Type Conversion Example-3

#################################
num1=input("Enter a Float Number:") #10.5
num2=input("Enter a Integer Number:") #5
print(int(num1)+float(num2)) #ValueError: invalid literal for int()


Formatting Output

name,age,sal = "John",24,10000.35

#Approach1
print(name,age,sal)

#Approach2
print("Name is:", name)
print("Age is:", age)
print("Sal is:", sal)

#Approach3 : using  %  Here type is imp
print("Name:%s  age:%d  salary:%g" %(name, age, sal))

#Approach3 : using  {} Here value is imp
print("Name:{}  age:{}  salary:{}".format(name, age, sal))

#Approach4 : using  {} Here value is imp
print("Name:{1}  age:{2}  salary:{2}".format(name, age, sal))







0 comments:

Post a Comment