Friday, 28 June 2019

Errors in Python

In python, there are three types of errors; syntax errors, logic errors and exceptions.


You may like the following posts:
Syntax Errors in Python

Wednesday, 26 June 2019

Tuple

Tuple data type:

A tuple is a collection of elements/items of different data types is called tuple.
A tuple is similar to list. Elements are separated by comma operator and enclosed within parentheses ().

Difference between list and tuple isList elements can be modified as it is mutable. Whereas tuple elements can not be modified as it is immutable. So tuple is treated as a read-only list.

Syntax:
Variable=(item1,item2,….)

Example:
t=(10,-20,10,2.4,”raj”,”$”,True)

Individual elements of the tuple can be referenced using square braces as a[0],a[1]

Ex:

a=(10,20,30,40)#collection of items like arrays
a=(10,-20,12.5,'Ravi',"Sita") # A tuple may have different types like objects
a=(10,-20,10)  #duplication
a[1]=30 # Error
print(a[0]) à 10
a=(10,20,30,40)
print(a):-> (10,20,30,40)
print(a[1:3]) :-20,30
print(a[-1]):->40
print(a*2):-> 10,20,30,40,10,20,30,40


Ex1:
a=(10,20,30)
a[0]=40 #error as it is immutable

A tuple can be modified when we list is initialised in a tuple
Example:
>>> t=(2,3,[4,5])
>>> t[0]
2
>>> t[1]
3
>>> t[1]=7
>>>t[1]
7
>>> t[2]
[4, 5]
>>> t[2][0]=6
>>> print(t)
(2, 7, [6, 5])
>>> 

Creating a tuple with one element within parentheses is not enough. We should give comma separator to indicate it is tuple.
Ex:
>>> a=("ravi")
>>> type(a)
<class 'str'>
>>> a=("ravi",)
>>> type(a)
<class 'tuple'>

Individual elements can be accessed by using square brackets [ ].
>>> a=(10,20,30)
>>> a[0]
10
>>> a[1]
20
>>> a(0) # Error as to access any element we should use [ ]

Packing and unpacking tuples:
A tuple can also be created without using parentheses. This is called packing tuples
Ex:
>>> t=3,4,6,"ravi"
>>> print(t)
(3, 4, 6, 'ravi')

Unpacking:
>>> a,b,c,d=t
>>> a
3
>>> b
4
>>> c
6
>>> d
'ravi'
>>> a,b,c=t # Error because no of elements and no of variable should be matched.

1.  Slicing operation in Tuple:

We can access a range of items in a tuple by using the slicing operator (:)

Example:
a=(2,3,4,5)
print(a[1:3])
output:
(3,4)

2. Concatenation of tuple

We can use + operator to combine two tuples. This is called concatenation.
Ex:
>>> a=(2,4,6) #tuple a is created
>>> b=(7,2.4,8,True) #tuple b is created
>>> print(a+b)
(2, 4, 6, 7, 2.4, 8, True)

Ex2:
a=(10,20,30)
print(type(a)) #<class 'tuple'>
print(a)#(10, 20, 30)
print(id(a))#59342480
a=a+(40,)
print("after concatenation")
print(a)#(10, 20, 30, 40)

print(id(a))#66274000

3. Repeating the tuple elements

We can also repeat the elements in a tuple for a given number of times using the * operator.
Both + and * operations result in a new tuple
Example:
>>> a=(4,6,7)
>>> print(a*3)
(4, 6, 7, 4, 6, 7, 4, 6, 7)

4. Deleting the tuple

We can not change or delete the tuple elements. But deleting a tuple entirely is possible using the keyword ‘del’
Example:
a=(6,8,2,3)
>>> type(a)
<class 'tuple'>
>>> print(a)
(6, 8, 2, 3)

>>> del a[1] #Error
>>>a.remove(8) #Error
>>> del a # Valid, entire tuple a is deleted


5.  Converting into Tuple:

a=("ravi")# string
print(type(a))
b=str(a)
print(type(b))
c=tuple(b)#converting from string to tuple
print(type(c))
"""
<class 'str'>
<class 'str'>
<class 'tuple'>

"""

Tuple Membership:
We can test if an item exists in a tuple or not, using the keywords :
in, not in

>>> t=('c','a','t')
>>> print('a' in t)
True
>>> print(a in t) #Error
>>> print('t' in t)
True
>>> print('j' not in t)
True
>>> print('a' not in t)
False

#To get the nth element from last of a tuple using positive and -ve index
a=("r","a","j","e","n","d","r","a")
print(type(a))#tuple
#get 4th element of the tuple by index
n=a[3]
print(n)#e
#get 4 :nth element from last by negative index
print(a[-4])#n

Advantages of tuple over list:

Since tuples are similar to lists, both of them are used in similar situations.
We generally use tuple for different data types (Heterogeneous) and list for homogeneous (same data type)

Difference between Lists and Tuples


List
Tuple
        The elements of a list are mutable
elements of a tuple are immutable
        When we need to change the data in future, list would be a right data type.
When we do not want to change the data over time, the tuple is a preferred data type
        When we are iterating (in looping statements) elements, performance is slow
Iterating over the elements of a tuple is faster .
         The elements of list are enclosed in square bracket.
         Ex: a=[10,20,30,40]
Elements of a tuple are enclosed in parenthesis
Ex: a=(10,20,30,40)




Since tuples are immutable, tuple is faster than list so there is a slight performance

Assignments:

(1.) a = (1, 2, 4, 3), which of the following is incorrect?
a) print(a[3])
b) a[3] = 45
c) print(max(a))
d) print(len(a))

Answer: b

(2.) What will be the output?

>>>t=(1,2,4,3)
>>>t[1:-1]
a) (1, 2)
b) (1, 2, 4)
c) (2, 4)
d) (2, 4, 3)


Answer: c

(3.)  What will be the output?

>>>t = (1, 2)
>>>2 * t
a) (1, 2, 1, 2)
b) [1, 2, 1, 2].
c) (1, 1, 2, 2)
d) [1, 1, 2, 2].

Answer: a

Next topicSet data type
Previous topic:  List

Related video Click here to see related videos

You may like the following topics:
What is Ordered List
What is Immutable?
What is Sequences in Python

Example program on float data type

Example program on Float:

m=20
p=40
c=76
tot=m+p+c
avg=tot/3
print(avg)
45.333333333333336
print("%.2f"%avg)
45.33
print("%.2f" % round(avg,2))
45.33

You may like the following posts:


PVM

 PVM will automatically be used when we run the python program. PVM is a part of Python software.

PVM Does the following things :
1. The moment when we run the python program, Python program will be translated into Byte Code
2. PVM It reads the bytecode and translated into machine language.

The PVM is always present as part of the Python system and is the component that truly runs your scripts. Technically, it's just the last step of what is called the Python interpreter. ... Python does something clever to improve its performance. It compiles to bytecode (.pyc files) the first time it executes a file.

Object Reference

A Python program accesses data values through references. A reference is a name that refers to the specific location in memory of a value (object).

Python doesn't have variables as such but instead has object-reference. When it comes to immutable objects like strs (String data type), there is no discernable (noticeable) difference between a variable and an object reference. As for mutable objects, there is a difference, but it rarely matters in practice.
We will use the terms variable and object reference interchangeably.

An object reference is nothing more than a concrete representation of the object’s identity (the memory address where the object is stored).

References take the form of variables, attributes, and items. In Python, a variable or other reference has no built-in data type.





Comment Lines in Python

Comment Lines in Python:

Two types of comment lines are available in Python.
1.  Single line comment line
#this is single-line comment
2. Multiline comment line
#
#
#
(or)
“”” this is a multi-line comment line
It is used for more one sentence”””

Previous Topic:


You may like the following posts:

Tuesday, 25 June 2019

Example program on None data type

Example program on None

def ex():

   a=10

print(ex())

""" out put """
 None



Python Syntax

Python Syntax:

(1.)Python syntax can be executed by writing directly in the command line.  Ex

>>>print(“Hello “)

Hello

 Or by creating a python file (Note pad)on the server, using the .py file extension, and running it in the Command Line:

open a note pad: type the following syntax:
print("Hello")

save as ex.py
open commandline, go to the directory(folder) where you saved ex.py file, type python ex.py


C:\Users\Rajendra>python ex.py

(2.) Python Indentation 

Where in other programming languages the indentation in code is for readability only, in Python the indentation is very important.

Python uses indentation to indicate a block of code.

if 10 2:
  print("Ten is greater than two!")
The above is giving indentation otherwise leads to error

For example:
if 10 > 2:
print("Ten is greater than two!") # this is error bcoz there is no indentation


What is Indentation?

Python uses a different methodology. Python programs get structured through indentation, i.e. code blocks are defined by their indentation.  

All statements with the same distance to the right belong to the same block of code, i.e. the statements within a block line up vertically. The block ends at a line less indented or the end of the file. If a block has to be more deeply nested, it is simply indented further to the right. 

Type Casting


Type casting:

Converting from one data type to another data type.

There are two types:

1.       implicit type casting
2.       Explicit type casting

Explicit type casting:

Explicit type casting is done by the programmer.

Example:


>>> int(123.67)
123
>>> int(10+5j) #Error
>>> int(True) #Converting from Bool to integer
1
>>> float(10) #converting from int to float
10.0
>>> float(True)
1.0
>>> float(3+4j) # can't convert complex data type to float
output: Error
TypeError: can't convert complex to float
>>> 
int(a) # Error bcoz complex data types type casted to int
c=”123” # here c is str data type
int(c) # here str to int converted

Note:
1.        We can convert from any data type to int or float except complex type.
2.        Whenever we are trying to convert str data type to int/float, it is mandatory str should be either int/float literal.
Ex:
>>> a="123"
>>> int(a)
123
>>> b="10.5"
>>> float(b)
10.5
>>> 
Complex()
>>> complex(10)
(10+0j)
>>> complex(10.4)
(10.4+0j)
>>> complex("hel")
Traceback (most recent call last):
  File "<pyshell#2>", line 1, in <module>
    complex("hel")
ValueError: complex() arg is a malformed string
>>> complex(True)
(1+0j)

a=123.456 # a is float variable

int(a) #now data is converted   #from float to integer.
b=True
int(b) or int(True)
#1
c=False
int(c) -> 0 displays
a=2+3j
int(a) # Error bcoz complex data types type casted to int
c=”123” # here c is str data type
int(c) # here str to int converted

complex(x,y):
We can use this method to convert x and y into complex form such that x will be real part and y will be imaginary part.
Ex:
complex(10,-2) -->10-2j
complex(True,False)-->1+0j

Bool()
Converting from other data types into bool type.

Ex:
bool(0)àFalse
bool(1)->True
bool(“”)->False
>>> bool("True")
True
>>> bool("False")
True
>>> bool(False)
False
>>> bool(10-3j) # Non Zero
True
>>> bool(0-0j) # Zero
False
>>> print('python''programming')
pythonprogramming
>>> 

Next topic: Immutable
Previous topic:str data type

Sequences

Built-in Data types:
1.  Int
2.  Float
3.  complex
4.  bool
5.  None
6.  sequences
7.  sets
8.  Mappings (dictionary)

So far we have discussed int, float, complex, bool, None.
Now we are going to see sequences:

Sequences:

Sequences means a group of elements or a group of items or collection of objects.

 Sequences are:
·  str
·  bytes
·  bytearray
·  list
·  tuple
·  range



Next topic      : str data type
Previous topic: Built-in Data types part 1
Click here to see related videos


Non Boolean logical operators


For Non-boolean types :


x=10
y=20
print(x and y)#x is non zero (True), which returns 2nd arg: y(20)
print(x or y)#x is non zero(True), which returns 1st         #    arg: x(10)
print(not x)

"""output
20
10
False
"""

x=1 #non zero: True
y=2#True
z=3#True
print(x and y)# print(True and 2): 2
print(x<y and y<z) #print(1<2 (True) and 2<3(True):True
if(x<y and y<z):  #1<2(True) and 2<3(True):True
    print("Hyd")
else:
    print("Vij")

"""output
2
True
Hyd


In the above statement, compound condition x<y and y<z, this is a combination of two conditions, when ‘and’ is used, the total condition will become ‘True’, if both the conditions are ‘True’ result is also ‘True’, since both the conditions are True, we will get “Hyd” as output.

Note2

x=1,y=2,z=3
Here x>y i.e 1>2 (False) but y<z i.e 2<3(True) when using ‘or’ operator if anyone condition is True, it will take the total compound conditions as True.

0 means False, Non-zero means True

Lets take x=1 and y=2


Operator
Example
Meaning
Output
and
X and y
If x is ‘false’, it returns x, otherwise, it returns y
1 and 2= 2
Or
X or y
If x is false, it returns y, otherwise, it returns x
1 or 2= 1
Not
not x
If x is false, it returns True, otherwise False
Not True=False

Expected output: by using logical operators and,or not

200
100
False

x=100
y=200
print(x and y)
print(x or y)
print(not x)


Example4:

10 and 20 result 20
0 and 20 result 0

If first argument is zero then result is zero otherwise result is non-zero

Note: empty string is treated as False.

#empty string is treated as 'False'
print("ravi" and "rajendra") #rajendra
print("" and "Sitha") #false so returns 1st argu:  #empty string
print("kiran" and "")#True and false i.e empty
print("" or "rajesh) #1st is false so returns 2nd  i.e #rajesh
print("Hyd" or "") #1st True so returns 1st “Hyd
print(not "") # not False i.e True
print(not "Vij") #not True i.e False

output:
rajendra


rajesh
Hyd
True
False

Logical Boolean operators:
Let's take a=True, b=False

Opearators
Example
Meaning
Output
And
a and b
If both a and b are True, then it returns True
False
Or
a or b
If either a or b is True, then it returns True, else false
True
Not
not x
If x is True, it returns False
False

Example program:

a=True
b=False
print(a and a)#True
print(a and b)#False
print(b and b)#False
print(a or a)#True
print(a or b)#True
print(b or b)#False
print(not a)#False
print(not b)#True


"""output
True
False
False
True
True
False
False
True
"""

Related Youtube Video: https://youtu.be/6z3kUjBEq6Q
Next Topic: Assessment 6
Assignment operators
Previous Topic:Logical Operators

Files with Exception handling

#Ask the user to take two input integer values var a,b try:     a=int(input("enter any integer value:"))     b=int(input(&qu...