Python programming basics- typecasting

 Typecasting is the process of converting a variable’s datatype to another datatype. It can be done implicitly in python.

How to know the datatype of a variable in python???

Here, is the clue…

A keyword ‘type()’  is used to find the data type.

Examples are given  below.

 a  =  4

 b  =  5.7

 c  = ‘s’

 d  = “String”

print(“The data type of the variable a is:”,type(a))

print(“The data type of the variable b is:”,type(b))

print(“The data type of the variable c is:”,type(c))

print(“The data type of the variable d is:”,type(d))


 For eg, if you are using a variable in  ‘int’ datatype, but the output needs in float.

  a  =  12

  b  =  5

  c  =  a / b

  print(“The value is”,c)


Next, explicit type conversion in python is given below…..

This can be done by using keywords.

  • ·       int()
  • ·       float()
  • ·       str()

Converting int to float :

It is the most used conversion. It mainly used in mathematical expressions.

Eg:

 a = 12

 b = 23.6

 c = float(a) + b

 print(“The sum is:”,c)

 


Converting float to int:

This can be done by int() method.

Eg:

 a = 3.45

 b = int(a)

print(“The converted int  value is:”,b)


 Converting int, float numbers to string is not that much applicable.  

Python programming basics- How to get inputs in run time???

 Python is one of the most important programming languages nowadays. This post includes the declaration, how to get the input for a variable.

let us, declare a python variable. As we already know, the variable's name should have some rules. It should start with an alphabet or _(underscore) character. It also includes numbers.

Eg:

Num1 is valid.

1Num is not valid.

#Assign a value to variable Num1

Num1 = 10

Next, Multilple assignments in single line can be achieved by,

#Assigning multiple variables with its values.

Num1,num2,sum = 10, 20 ,0

Here, Num1 is assigned with the value 10, Num2 is assigned with value 20 and sum is assigned with value 0.

#How to assign values to variables and simple addition

num1,num2,sum = 10 , 20 , 0

sum = num1 + num2

print(“The sum of two numbers are:”,sum)


#How to get the input from run time

num = int(input(“Enter the first number”))

num1 = int(input(“Enter the second number”))

sub = num - num1

print(“The subtracted value is”,sub)


 If you want to use float variables, you can use float keywords, instead of int.

Eg:

A = float(input(“Enter the value”))

#How to get string value at run time

St = input(“Enter the customer id”)

print(“The customer id is:”, st)  


These are the simple ways to get inputs for various types of variable.