Variables and Data types in Python

Python is an all-rounder programming language which deals with several types of basic fundamentals, these are going to use to develop Python programs which include variable, identifiers, data types, strings arrays, etc..

Let us understand one by one as follow:

Python Identifiers:

A name which represents Variable, class, Function, Method name or Object which is used for identification purpose is called as Identifier

  • Identifiers can be in Lowercase(a to z),
  • Uppercase(A to Z), and digits(0 to 9)
  • It can be an Underscore( _ )

Ex: valid examples

 myClass
 classTest
Num_1 

Invalid examples

1_var
ca$h=10

Just see the below example

python-identifier-error

Some Rules for Python Identifiers :

  • Where the identifier does not include any special characters like $,%,&, *,etc..
  • Identifier names never start with Digits
    identifier-never-starts-with-digits
  • Python Identifiers are the case sensitive
    case-sensitive-identifier
  • There is no length limit for Python Identifiers
    identifier-no-lenght-limit
  • Even though there is no length limit for identifiers we should not use unnecessarily too lengthy identifiers
  • In Python there are some reserved words are there which we cannot use to declare the variables
    identifiers-reserved-words
  • If any variable starts with _x is called a protected variable
  • If any variable starts with two underscores __x is called a private variable
  • If any variable starts with two underscores and ends with two variables is called as Magic variable __x__

Python keywords :

The words which are used to represent the syntax and Structure of the python language is called as Keywords or Python Reserved words.

  • Keywords are case sensitive
  • there are 33 keywords in Python language
  • All the keywords except True, False and None are in the lowercase

The list of Keywords are as follows :

False class finally is return
None continue for lambda try
True def from nonlocal while
and del global not with
as elif if or yield
assert else import pass
break except in raise
  • All the keywords contain only alphabet symbols
  • let us see some examples:

true-error

  • Python is a dynamically typed language and hence it does not require any int, float, complex type of reserved words.
  • There is a keyword module in Python, we can import them as shown below:

    import keyword
    keyword.kwlist​

    If you enter the above command it will list out all the keywords which are present in the keyword module

    kw-list

Mutability in Python

Introduction to Python Datatypes

Data type: It represents the type of data stored in a variable which is used in our program is called as Datatype.

Python is a Dynamically typed programming language and hence we are not required to define the types of the Data explicitly

Based on the assigned value the type will be considered by the python virtual machine, and also there will be a function called type(a) which represent the data type of a.

example:

  • Int type
a=10

data-type-int

  • Boolean type
b=True​

data-type-boolean

  • Float type
    c=10.5​
    data-type-float

Different data types available in Python

There are 14 types of Data types are present in the Python

int float complex string boolean
list tuple set frozenset bytes
bytes array dict range none
Note: Everything in the Python is an Object

There are three inbuilt functions in the Python :

Consider an example where we are assigning a value to an a=10

  • And if we want to know the type of a, we will use type(a) and then it will display the data type of a
  • And if we want to know the address of a that means where it is located then we will use id(a)
  • And if we want to print the value of a, we will use print(a)
    a=10
    type(a)
    id(a)
    print(a)​

inbuilt-functions

Python Bytes and Bytearray

Integer/int Datatype

The numbers without any decimal point then it is called an integer or some times we can call it the whole number.

In python 3 versions there no limit to how long an integer value can be and hence we can use long integer values. long-int

We can represent these integral values in Four types

Decimal Form(base 10): In this form, we are going to use the numbers between 0 to 9 like and this is also called a default number system.

a=986
a=123

Binary Form(base 2): In this form, we are going to use the number between 0 to 1, by default all the numbers in the Python are going to considered as a binary number, for example, if you represent the a value as

a=1111

Then it will consider the a value as one thousand one hundred eleven only so to represent this value in the binary format we need to prefix it with 0b

a=0b1111

in the below image you can see the difference between a=1111 and a=0b1111

binary-form

Octal Form( base 8) : In this format, we are going to use the numbers between 0 to 7 and literal value should start with zero followed by small o or capital o.

a=0o123

octal-form

And also it will throw an error if we use a number more than 7

octal-form-error

Hexadecimal Form(base 16): In this format, we are going to use the numbers between 0to 9, and alphabets between A to F including lower case also.

Here the values of

  • A=10
  • B=11
  • C=12
  • D=13
  • E=14
  • F=15

And the numbers should be prefixed with 0 and either uppercase X or lowercase x

a=0x123
a=0x1556
a=0xface
a=0xbeef
a=0xzoo

hexa-form

Python Datatype summary

Float Datatype

The numbers with Decimal points are called as float datatypes

float-data-types

We can represent the float values only in the decimal form and we cannot represent them in Integral form, binary form, octal form, and hexadecimal form as shown below:

f=1.23
f=0b1.111
f=0o123.456
f=0x12357

float-errors

if f=1.2e3 which is nothing but 1.2*10^3 this type of representation is called as scientific notation or exponential form and it is applicable only for floating points

f=1.2e3

exponantial-float

In this format, we can represent the bigger values as well, as it will consume, less space

f=15.63e10

exponantial-floating-form

Python None Datatype

Complex Datatype

Complex Data type is the special Datatype which is present in the Python programming language, which can be used to develop

  • Scientific application
  • Arithmetic applications
  • Electrical engineering applications

Let us see how to represent the complex data type or the Syntax of complex data type

a+bj : where a is the real part and b is the imaginary part and j=j^2=-1

x=10+20j

complex-data-type

x=10+20i

complex-data-type-error

And from the above example consider x=10+20j and if you want to print the real value then you can give the command as

x=10+20j
print(x.real)

real-part

Similarly, if you want to print the imaginary number

x=10+20j
print(x.imag)

imaginary-number

In the real part and the imaginary part, we can use decimal points

x=10+20j
x=10.5+20j
x=10.5+20.6j

And also in the real part, we can use either binary form, octal form, hexadecimal form but in the imaginary part we should represent only it in the Decimal form

x=10+20j
x10.5+20.6j
x=0b1111+20j
x=0b111+0b1111

errors-in-complex

We can also perform arithmetic operations by using this syntax

x=10+20j
y=20+30j
x+y=?
x*y=?

complex-arithmetic-operations

Python Special characters

Boolean Datatype

Boolean Data type is the one which is used to represent in the numerical form and the constant value of boolean Data type is True and False where T and F are always should be in the uppercase.

b=True
b=true

boolean-form

consider the below example

a=10
b=20
c=a>b
print(c)
print(type(c))

boolean-operations

Example: 2: internally the True values will be 1 and the False valve will be 0and hence if we perform the below operation

print(True+True)
print(True-False)

true-plus-true

python-operator

String Datatype

A sequence of the character itself is called a string data type, the string will be represented either by single quotes or double quotes.

example:

s= "chercher.tech"
print(type(s))

string-data-type

single-quote-string-data-type

And in python, there is no char data type, even if we write a single character in single quotes or double quotes, it will represent it as string data type only.

s='a'
print(type(s))
s="a"
print(type(s))

single-chr-string-data-type

We can also represent the String in the triple quotes as well

s="""a"""
print(type(s))

triple-quotes-string-data-type

We can also define multiple line strings but here single, single quote or single double quotes will not support and hence we need to use three times single quotes or three times double quotes.

s='cher
      cher
      tech'

multi-line-string

s="""cher
        cher
        tech"""
print(type(s))
s='''cher
       cher
       tech'''

successfull-multi-line-data-type

If you want to print any string which is included in the single quotes or in the double quotes then see the following example

s='classes by "chercher tech" is very good'
print(s)

In the above example, if you want to print the chercher.tech in the double quotes then you have to include the whole sentence in the single quote

double-quotes-within-single-quotes

In the same way, if you want to print the chercher.tech in the single quotes then you have included the whole sentence in the double quotes

s=" classes by 'chercher.tech' is very good"
print(s)

single-quotes-within-double-quotes

Let us consider another one example, in this, I want to print two parts, one in single quotes and another one in double quotes so for this I want to include the whole sentence in either single thripple quotes or double triple quotes.

s="""classes for "python" from 'chercher.tech' are very good"""
print(s)
s='''classes for "python" from 'chercher.tech' are very good'''
print(s)

single-double-quotes-within-tripple-quotes

Index:

The index is used to access the character of the string, the value of the first character of the index is always zero (0), let us consider an example as following

s="dhanvik"
print(s[0])=?
print(s[1])=?
print(s[4])=?

In the above example the value of d=0,h=1,a=2,n=3,v=4,i=5,k=6 and if you print the value of above character

index-values

In the above example, the index value is up to 6 and if I am going to print as below then you will get an index error

print(s[100])

index-error

One more very important thing is that, python will provide support for both positive indexing and negative indexing, that means from backward direction index value will start from -1 so the value of k=-1,i=-2,v=-3,n=-4,a=-5,h=-6,d=-7

s="dhanvik"
print(s[-1])=?
print9s[-5])=?

negative-indexing

Slice operator :

In string we have an operator is called Slice, which is nothing but a part of a string, in some cases, if we want to print a part of that string or a slice of that string then we will use this operator.

The syntax of the slice operator is s[begin : End], where s may be any string, though we have written end in the syntax, it will always return a substring or Slice by considering end-1.

Let us consider an example, here s="abcdefghiklmnopqrstuvwxyz"

and you also know that the index value will start from zero and hence a=0, b=1, and c=3, etc... z=25.

example:1

s="abcdefghiklmnopqrstuvwxyz"
print(s[3:9])

Then the above example will return from the third index to 9-1, that means up to 8 index

slice-indexing-one

example:2

s="abcdefghiklmnopqrstuvwxyz"
print(s[ :9])

In the above example am going to mention only the end argument and begin argument is empty, so in this case, it will going to consider by default from the beginning itself

slice-indexing-two

example:3

s="abcdefghiklmnopqrstuvwxyz"
print(s[3: ])

In the same way, as shown in example 2, m going to mention only the beginning argument and leaving the end argument as empty, then by default it will consider till the end of the string

slice-indexing-three

Example:4

s="abcdefghiklmnopqrstuvwxyz"
print(s[ : ])

In the above example, I am not going to specify either the beginning valve or the end value, so by default, it will consider from 0 to 25 and print the whole string

slice-indexing-four

Example:5

s="abcdefghiklmnopqrstuvwxyz"
print(s[3:100])

In the above example, I mentioned both the arguments, but here am giving the end argument as 100 which more than the index value, but still it won't give any indexing error instead of that it will consider the default end value and print the string.

slice-indexing-five

example:6

s="abcdefghiklmnopqrstuvwxyz"
print(s[5:1])

In example 6, I am giving a beginning argument as 5 and end argument as 1, as we after 5, one will not occur and hence it will print empty

slice-indexing-six

Use of Slice Operator:

In the previous section, you learned how the slice operator will work, now let us see where we can use this slice operator.

Consider an example s="dhan"

But you want to print the first of the above string in the upper case, here the first character index value is zero and the next one is 1, so

s="dhan"
output=s[0].upper()+s[1: ]
print(output)

Here I created a new file called sample1.py and saved in my project folder and then executing through command prompt

slice-application

Now the output will be as follow:

sluce-app-output

In the same way, if I want to print the last character of the string dhan in the uppercase then I have to use the following syntax

s="dhan"
output=s[0:len(s)-1]+s[-1].upper()
print(output)

where the length of the string is 5 and I want to print the first four character in lower case, so I have given as s[0:len(s)-1] and using the add operator next I want to print the last character in the upper case, as we know that python will support for negative indexing hence I am going to mention as s[-1].upper() and then I am going to print the output

slice-app-two

slice-app-two-output

We can also print the first and the Last character in the Uppercase

s="dhan"
output=s[0].upper()+s[1:len(s)-1]+s[-1].upper()
print(output)

slice-app-three

slice-app-output-three

Operations on String

Python provides us some easy operations to perform on the string like concatenation and repetition operation.

Concatenation:

concatenation is nothing but adding or joining two strings, but those two arguments must be of string type and we are going to use Plus(+) symbol as concatenation operator.

s="dhan"+"vik"
print(s)
s="dhan"+"10"
print(s)
s="dhan"+10
Print(s)

concatenation-operation

Repetition Operator:

Some times we want to write the same text multiple times, instead of writing it manually we can use the repetition operator to repeat the same text as many times as you want to print.

Here we are using the Multiplication operator or a star operator to repeat the text, to perform this operation, one argument should be a string and another one must be an int data type

s="cherchertech."*3
print(s)

repetition-operator

repetition-operator-two

consider the below example:

string-string-repetation

So if we use two arguments as string type then it will throw an error as shown above.

We can also use this operator to print as follow:

print("#"*10)
print("chercher.tech")
print("#"*10)

repetition-opr-three

repetition-opr-out-three

Note: Important conclusions:
The Following Datatypes are called as Fundamental Datatypes
Int
Float
Bool
Complex
String
Long Datatypes are available only in Python-2 but not in the Python-3
There is no Char Datatype in Python, Char values can be represented by using the String type

Type Casting

The process of converting a variable from one type to another type is called type casting or type conversion, this can be done by using python default functions such as

  • int()
  • float()
  • bool()
  • str()
  • complex()

Int():

  • We can convert Float data type to int data type by using the int() function
    float=10.32
    int(10.32)
    ​

    conv-float-to-int

  • If in the same way, if we try to convert complex Data type to int data type, then we are going to get a type error
    f=10+20
    int(10+20)
    ​

    conv-com-int

  • But we can convert boolean data type to int data type because by default the boolean values for True are 1 and False is 0
    b=True
    int(True)
    b=False
    int(False)
    ​

    conv-bool-int

  • We can also convert string to the int data type but it should be in the integral format with base-10
    s="15"
    int("15")​

    conv-str-int-one

  • If the string contains the binary form then it won't convert it to int data type
    s='0b1111'
    int('0b1111')​

    conv-binary-to-int

  • If we try to convert float value into an int, then also we are going to get an error
    s="10.5"
    int("10.5")​

    conv-floattype-str-into-int

    Float():

  • Converting other types to Float data type by using the Float() function
  • We can convert several types of int values into the float data type, just follow the below image
    i=15
    float(15)
    i=0b1111
    flost(0b1111)
    i=0xface
    float(0xface)
    ​

    conv-int-to-float

  • Next, converting complex number to float type is not possible
    c=10+20j
    float(10+20j)
    ​

    conv-comp-float

  • We can Convert boolean data type to float data type easily
    b=True
    float(True)
    b=False
    float(False)​

    conv-bool-to-float

  • Converting string to float is possible only when the string internally should contain either the float value or int value only in base-10
    s="10"
    float("10")
    s="20.6"
    float("20.6")
    s="dhan"
    float("dhan")
    s="0xface"
    float("0xface")

    conv-str-float

Complex():

  • here we can convert int, float, boolean data types to complex data types by using the real value as shown below
    i=15
    complex(15)
    b=0b1111
    complex(0b1111)
    f=10.6
    complex(10.6)
    b=True
    complex(True)
    b=False
    complex(False)
    ​

    conv-all-type-to-comp

  • To convert the string into complex data type, the string internally should contain either int value or float value but it should contain base-10 form
    s="10"
    complex("10")
    s="10.5"
    complex("10.5")
    s="0b1111"
    complex("0b1111")​

    <img src="../images/python-programming/conv-string-to-comp.

Comment / Suggestion Section
Point our Mistakes and Post Your Suggestions