4.Basic Python Data Types-Numbers and Strings,Type conversions

Every value in Python has a datatype. Since everything is an object in Python programming, data types are actually classes and variables are instance (object) of these classes.
There are various data types in Python. Some of the basic types are listed below.

Python Numbers
Integers, floating point numbers and complex numbers fall under Python numbers category. They are defined as int, float and complex classes in Python.

We can use the type() function to know which class a variable or a value belongs to. Similarly, the isinstance() function is used to check if an object belongs to a particular class.

Integers can be of any length, it is only limited by the memory available.

A floating-point number is accurate up to 15 decimal places. Integer and floating points are separated by decimal points. 1 is an integer, 1.0 is a floating-point number.

Complex numbers are written in the form, x + yj, where x is the real part and y is the imaginary part. Here are some examples.
>>>a=5
>>>b=4.5
>>>c=3+2j
>>>type(a) 
<class 'int'>
>>>type(b) 
<class 'float'>
>>>type(c) 
<class 'complex'>
>>>isinstance(a,int)
True
>>> b = 0.1234567890123456789 # note that b is truncated to 15 decimal places
 b 0.12345678901234568

You can also delete the reference to a number object by using the del statement
>>>del a
Here are some examples of numbers.

int

float

complex

10

0.0

3.14j

100

15.20

45.j

-786

-21.9

9.322e-36j

080

32.3+e18

.876j

-0490

-90.

-.6545+0J

-0×260

-32.54e100

3e+26J

0×69

70.2-E12

4.53e-7j

Binary,Hexa decimal and octal values can also be assigned to variable with prefix 0b,0x and 0o
>>>x=0b1100
>>>x
12
>>>x=0xc
>>>x
12
>>>x=0o12
>>>x
10

Python Strings
String is sequence of Unicode characters. We can use single quotes or double quotes to represent strings. Multi-line strings can be denoted using triple quotes, ''' or """.
>>>s = "This is a string" 
>>>print(s)
This is a string
 s = '''A multiline 
    string''' 
>>>print(s)
A multiline 
string
slicing operator [ ] can be used with strings to extract characters from  Strings, however they are immutable ie; we cannot change the characters.
>>>S="Python"
>>>S[2:5]    # extract characters 2-4
>>>tho
>>>S[2]='d' # this will generate error because string is immutable
>>>S*2
PythonPython
Note: More about strings and string functions will be discussed later.

Boolean Data Type
The boolean data type is either True or False. In Python, boolean variables are defined by the True and False keywords
.>>> a = True
 >>> type(a)
 <class 'bool'>
 >>> b = False 
>>> type(b) 
<class 'bool'>

The output <class 'bool'> indicates the variable is a boolean data type.

Note the keywords True and False must have an Upper Case first letter. Using a lowercase true returns an error.
>>> c = true 
Traceback (most recent call last):
 File "<input>", line 1, in <module> 
NameError: name 'true' is not defined

None Type

None is used to represent the absence of a value.

Eg x=None
 
Conversion between data types
We can convert between different data types by using different type conversion functions like int(), float(), str(), etc.
>>> float(5) 
5.0
Conversion from float to int will truncate the value (make it closer to zero).
>>> int(10.6) 
10 
>>> int(-10.6)
 -10 
The round() function rounds a float to the nearest int
>>>round(10.6)
11
Conversion to and from string must contain compatible values.
>>> float('2.5') 
2.5 
>>> str(25)
 '25' 
>>> int('1p') 
Traceback (most recent call last): 
 File "<string>", line 1, in <module>",
ValueError: invalid literal for int() with base 10: '1p'
Converting integer to character
>>>chr(65)
'A'
Converting single character to integer value
>>ord('A')
65
Convert integer to octal string
>>>oct(12)
0o14
Convert integer to hexadecimal string
>>>hex(12)
0xc
Convert integer to binary
>>>bin(12)
0b1100

Integers and floating point numbers can be converted to the boolean data type using Python's bool() function. An int, float or complex number set to zero returns False. An integer, float or complex number set to any other number, positive or negative, returns True.
>>> zero_int = 0 
>>> bool(zero_int) 
False
>>> pos_int = 1 
>>> bool(pos_int) 
True
>>> neg_flt = -5.1 
>>> bool(neg_flt) 
True

Type coercion ( old version 2.x)
Now that we can convert between types, we have another way to deal with integer division. 
Suppose we want to calculate the fraction of an hour that has elapsed. The most obvious expression,
minute / 60, 
does integer arithmetic, so the result is always 0, even at 59 minutes past the hour.

One solution is to convert minute to floating-point and do floating-point division:

>>> minute = 59
>>> float(minute) / 60
0.983333333333

Alternatively, we can take advantage of the rules for automatic type conversion,which is called type coercion. For the mathematical operators, if either operand is a float, the other is automatically converted to a float:
>>> minute = 59
>>> minute / 60.0
0.983333333333
By making the denominator a float, we force Python to do floating-point division.

Summary

Python provides a rich set of basic data types that allow for versatile and powerful data manipulation. Understanding these fundamental types is crucial for writing effective and efficient Python code.

Comments

Popular posts from this blog

Python For Machine Learning - CST 283 - KTU Minor Notes- Dr Binu V P

KTU Python for machine learning Sample Question Paper and Answer Key Dec 2020

46.Classes and Objects in Python- Accessors and mutators