Type Conversion, Number System, input()
Type Conversion:
In Python all datatypes are classes.
int
float
str
bool
float
str
bool
complex
... more
In python we can convert datatypes using functions. If we want to add two numbers one is int and another is str, like 5 + '3'
5 + int ('3') --> returns 8.
Similarly, we can convert other data types.
similar functions float (), str (), bool (), complex () all these are type conversion functions.
Conversion functions doesn't work with mixed cases such as
a = '123x'
int(a) ==> this will generate type error as there are characters.
also, b = '3.14' --> str
int (b) ==> this will also generate error as there is non-digit. (.)
a = 35
b = bool(a)
this will result True.
Any non-zero number is True in this case.
a = 3.5
b = bool(a)
This would be True as well.
a = '3.5'
b = float(a)
This will be converted to 3.5 as in case of float (.) is allowed only once, no other non-digit is not allowed.
str to anytime of conversion can work as there is not any special formatting. ***
Number System
Binary - 1 and 0
Octal - 0 to 7
Decimal - 0 to 9
Hexadecimal - 0 to 9 and A to F
>>> a = 25
>>> bin(a)
'0b11001'
>>> oct(25)
'0o31'
>>> hex(25)
'0x19'
>>> d = 0b11001
>>> print(d)
25
Binary number - 0b, Octal - 0o, 0x - Hexadecimal.
Python provides flexibility to directly store numbers with different conversion system using functions such as bin() , Oct() and Hex(). They return numbers as str.
Similary we have function to convert unicode to char and vice versa.
>>> chr(66)
'B'
>>> ord('b')
98
>>> ord('B')
66
>>>
here chr convert number into the character and ord convert character into the Unicode (Similar to ASCII in C).
input()
In python we take input from user using input () function which is builtin.
As per help definition
input(prompt='', /)
Read a string from standard input. The trailing newline is stripped.
The prompt string, if given, is printed to standard output without a
trailing newline before reading input.
If the user hits EOF (*nix: Ctrl-D, Windows: Ctrl-Z+Return), raise EOFError.
On *nix systems, readline is used if available.
>>> a = int(input("Enter a number"))
Enter a number10
>>> a
10
>>>
Here input function returns str type, so it needs to be converted to required type using type conversion function.
Comments
Post a Comment