Numbers and Casting


In this blog of python series, we will discuss about different types of numbers used in python language, their conversion, random number, and casting.



There are three numeric data types in Python.

  • int
  • float
  • complex
Variables of numeric types are created when we assign value to them.


  • Int or integer is a whole number, positive or negative, without decimal of unlimited length.  eg: x = 10, x =  -20, x = -34563, x = 9989899

  • Float or floating-point number is a number, positive or negative containing one or more decimals.    eg: x = 1.0, x = -9.90, x = 23.4532 . Float are also scientific numbers with an 'e' to indicate power of 10.  eg: 35e3 = 35 * 10^3, 23e-2 = 0.23

  • Complex numbers are written with a "j" as an imaginary part. eg: x = 3+ 5j, x = -3j


#Number Conversion

Numbers in python can be converted from one type into another type using the following methods:

  • int()
  • float()
  • complex()

Our assigned numbers:


Conversion from int to float and float to int

Conversion form int and float to complex



A complex number cannot be converted into int or float.



#Random Number


Python doesn't have a random() function for creating a random number, but python has a built-in module called "random" which makes the random numbers.



The output is a random number between 1 and 9. The upper value(10) is not included.


The output is a random number between 10 and 99. The upper value(100) is not included.
If we want we can make random() function for convenience, but a certain function can be of certain number.


This is  a function for selecting numbers between 1 and 100. (Do not worry about function, we will have a clear discussion on further blogs.)


#Casting


When we want to specify a type of a variable, python casting comes into play. As, Python is Object-Oriented Language and as such it uses classes to define data types including its primitive types.
Casting of python is therefore done using constructor form,

  • int() - It constructs an integer number form an integer literal, a float literal(round off) or a string literal(whole number)

  • float() - It constructs a float number from an integer, a float or a string( a float or an integer)

  • str() - It constructs a string from a wide variety of data types including strings, integer literals and float literals.












 


Comments

Popular posts from this blog

Python Syntax, Comment and Variable

Python Booleans

Getting Started With Python