Python/C3/Basic-datatypes-and-operators/English
Visual Cue | Narration |
---|---|
Show Slide 1
Containing title, name of the production team along with the logo of MHRD |
Hello friends and welcome to the tutorial on 'Basic Data types and operators' in Python. |
Show Slide 2
Learning objectives |
At the end of this tutorial, you will be able to,
|
First we will explore python data structures in the domain of numbers. There are three built-in data types in python to represent numbers. | |
Show Slide 3
'numbers' |
These are:
|
ipython | Let us first invoke our ipython interpreter |
a = 13
a |
Lets first talk about int. |
type(a)
<type 'int'> |
Now, we have our first int variable a. If we now see |
a.<Tab> | This means that 'a' is a type of int. There are lot of functions associated with the int datatype, to manipulate it in different ways. These can be explored by doing, |
b = 99999999999999999999
b |
int datatype can hold integers of any size lets see this by an example. |
p = 3.141592
p |
As you can see, even when we put a value of 9 repeated 20 times, python did not complain. This is because python's int data-type can hold integers of any size.
Let us now look at the float data-type. Decimal numbers in python are represented by the float data-type |
c = 3.2+4.6j | If you notice the value of output of p isn't exactly equal to p. This is because computer saves floating point values in a specific format. There is always an approximation. This is why we should never rely on equality of floating point numbers in a program.
The last data type in the list is complex number |
c.<Tab> | it's just a combination of two floats the imaginary part being defined by j notation instead of i. Complex numbers have a lot of functions specific to them. Let us look at these |
c.real
c.imag |
Lets try some of them |
abs(c) | c.real gives the real part of the number and c.imag the imaginary.
We can get the absolute value using the function |
Pause the video here, try out the following exercise and resume the video. | |
Show Slide 4
Assignment 1 |
Find the absolute value of 3+4j <pause> Switch to your terminal for solution |
Continue from paused state Switch to the terminal
abs(3+4j) |
Thus we get the absolute value of the expression.
Let us do 1 more exercise of a similar type. Pause the video here, try out the following exercise and resume the video. |
Show Slide 5
Assignment 2 |
What is the datatype of number 999999999999999999? Is it not int? |
Show Slide 6
Solution 2 |
The solution is on your screen. The data type of this number is long though it is an integer. Big integers are internally stored in python as Long datatype.
Python also has Boolean as a built-in type. To Try it out, just type |
Switch to terminal
t = True |
note that T in true is capitalized. |
f = not t
f f or t f and t |
You can apply different Boolean operations on t now for example |
a=False
b=True c=True |
The results are self explanatory.
What if you want to apply one operator before another. Well you can use parenthesis for precedence. Lets write some piece of code to check this out. |
(a and b) or c | To check how precedence changes with parenthesis, we will try two expressions and their evaluation. The first one |
a and (b or c) | This expression gives the value True where as the expression |
gives the value False.
Let's now look at some operators available in Python to manipulate these data types. | |
23 + 74 | Python uses '+' sign for addition |
23 - 56 | '-' sign for subtraction |
45*76 | '*' (star) sign for multiplication |
384/16
8/3 8.0/3 |
'/'(back slash) for division |
Note that, when we did 8/3 the first case results in an integer output as both the operands are integer however when 8.0/3 is used the answer is float as one of the operands is float. | |
87 % 6 | Let us move ahead with the operators. '%' (percentage) sign for modulo operation |
7**8 | and two stars for a exponent. |
a=73
a*=34 |
In case one wishes to use the current value of variable in which the result is stored in the expression, one can do that by putting the operator before equal to. |
a=a*34 | The above expression is same as |
a/=23 | and |
a=a/23 | is same as |
Pause the video here, try out the following exercise and resume the video. | |
Show Slide 7
Assignment 3 |
Using python find sqaure root of 3. |
Show Slide 8
Solution 3 |
The solution is on your screen. 3**0.5 gives the square root of 3. |
Show Slide 9
Assignment 4 |
Now, Is 3**1/2 and 3**0.5 same? <Pause> |
Continue from paused state Switch to the terminal
3**0.5 3**1/2 |
Switch to your terminal for solution Let us try both these operations. |
As you can see,the first operation gives an integer, whereas the second one gives a float. Hence,though both mean the same,they give different outputs.
Let us now discuss sequence data types in Python. Sequence data types are those in which elements are kept in a sequential order and all the elements are accessed using index numbers. | |
Show Slide 10
Introducing sequence datatype |
The sequence datatypes in Python are
The list type is a container that holds a number of other objects, in the given order. |
Switch to terminal
num_list = [1, 2, 3, 4] num_list |
We create our first list by typing |
var_list = [1, 1.2, [1,2]]
var_list |
Items enclosed in square brackets separated by comma constitutes a list. Lists can store data of any type in them.
We can have a list something like |
greeting_string="hello" | Lets look at another sequence data type, strings |
k='Single quote'
l="Let's see how to include a single quote" m="Let's see how to include both" |
greeting_string is now a string variable with the value "hello"
Python strings can actually be defined in three different ways |
num_tuple = (1, 2, 3, 4, 5, 6, 7, 8) | As you can see, single quotes are used as delimiters usually.
When a string contains a single quote, double quotes are used as delimiters. When a string quote contains both single and double quotes, triple quotes are used as delimiters. The last in the list of sequence data types is tuple. To create a tuple we use normal brackets '(' unlike '[' for lists. |
num_list[2]
num_list[-1] greeting_string[1] greeting_string[3] greeting_string[-2] num_tuple[2] num_tuple[-3] |
Because of their sequential property there are certain functions and operations we can apply to all of them. The first one is accessing.
They can be accessed using index numbers |
num_list+var_list
a_string="another string" greeting_string+a_string t2=(3,4,6,7) num_tuple+t2 |
Indexing starts from 0, from left to right and from -1 when accessing lists in reverse. Thus num_list[2] refers to the third element 3. and greetings [-2] is the second element from the end , that is 'l'.
Addition gives a new sequence containing both sequences |
len(num_list)
len(greeting_string) len(num_tuple) |
len function gives the length |
3 in num_list
'H' in greeting_string 2 in num_tuple |
We can check the containership of an element using the 'in' keyword |
max(num_tuple)
min(greeting_string) |
We see that it gives True and False accordingly.
Find maximum using max function and minimum using min |
sorted(num_list) | Get a sorted list |
j=[1,2,3,4,5,6] | As a consequence of their order, we can access a group of elements in a sequence, together. This is called slicing and striding.
First lets discuss Slicing, Given a list |
j[1:4] | Lets say we want elements starting from 2 and ending in 5.
For this we can do |
j[:4] | The syntax for slicing is, sequence variable name, square bracket, first element index, colon, second element index. The last element however is not included in the resultant list |
j[1:]
j[:] |
If first element is left blank default is from beginning and if last element is left blank it means till the end. |
new_num_list=[1,2,3,4,5,6,7,8,9,10]
new_num_list[1:8:2] [2, 4, 6, 8] |
This effectively is the whole list.
Striding is similar to slicing except that the step size here is not one. Let us see an example |
new_num_list[1]=9
greeting_string[1]='k' |
The, colon two, added in the end signifies all the alternate elements. This is why we call this concept striding because we move through the list with a particular stride or step. The step in this example being 2.
We have talked about many similar features of lists, strings and tuples. But there are many important features in lists that differ from strings and tuples. Lets see this by example. |
new_tuple[1]=5 | As you can see while the first command executes with out a problem there is an error on the second one.
Now lets try |
i=34
d=float(i) d |
Its the same error. This is because strings and tuples share the property of being immutable. We cannot change the value at a particular index just by assigning a new value at that position.
We have looked at different types but we need to convert one data type into another. Well lets one by one go through methods by which we can convert one data type to other |
dec=2.34
dec_con=int(dec) dec_con |
Python has built in functions int, float and complex to convert one number type data structure to another. |
com=2.3+4.2j
float(com) com |
As you can see the decimal part of the number is simply stripped to get the integer. |
lst=[3,4,5,6]
tup=tuple(lst) lst tupl=(3,23,4,56) lst=list(tupl) tupl |
In case of complex number to floating point only the real value of complex number is taken.
Similarly we can convert list to tuple and tuple to list |
somestring="Is there a way to split on these spaces."
somestring.split() |
However converting a string to a list and a list to a string is an interesting problem. Let's say we have a string |
otherstring="Tim,Amy,Stewy,Boss" | This produces a list with the string split at whitespace. Similarly we can split on some other character. |
otherstring.split(',') | How do we split on comma , simply pass it as argument |
l1=['List','joined','on','commas']
','.join(l1) |
join function does the opposite. Joins a list to make a string. |
l2=['Now','on','spaces']
' '.join(l2) |
Thus we get a list joined on commas. Similarly we can do spaces. |
Note that the list has to be a list of strings to apply join operation.
Pause the video here, try out the following exercise and resume the video. | |
Show Slide 11
Assignment 5 |
Check if 3 is an element of the list [1,7,5,3,4]. In case
it is change it to 21. |
Continue from paused state Switch to the terminal
l=[1,7,5,3,4] 3 in l l[3]=21 l |
Switch to the terminal for solution |
Let us solve one more exercise. Pause the video here, do the exercise and resume the video. | |
Show Slide 12
Assignment 6 |
Convert the string "Elizabeth is queen of england" to "Elizabeth is queen" |
Continue from paused state Switch to the terminal
s="Elizabeth is queen of england" stemp=s.split() ' '.join(stemp[:3]) |
Switch to the terminal for solution |
As you can see, we have easily removed the unwanted words. | |
Show Slide 13
Summary slide |
This brings us to the end of the tutorial. In this tutorial, we have learnt to,
|
Show Slide 14
Self assessment questions slide |
Here are some self assessment questions for you to solve
2. Split this string on whitespaces string="Split this string on whitespaces" |
Show Slide 15
Solution of self assessment questions on slide |
And the answers,
Enumerated list ends without a blank line; unexpected unindent. string.split() |
Show Slide 16
Acknowledgment slide |
Hope you have enjoyed this tutorial and found it useful. Thank You. |