Category Archives: Python

[Solved]: IOError in Python

Python IOError is subclass of EnvironmentError. Python IOError is occurred when an input/output operation like open() file, or a method or a simple print statement is failed due to IO reason like “Disk full” or “File not found”

See Also:

Example of Python IOError

In the below code, the xyz.txt file is not exist because of that the program will throw IOError exception. This Python IOError handle in the program through try-except block.

import sys
def readFile():
    try:
        f = open ( "xyz.txt", 'r' )
    except IOError as e:
        print (e)
readFile()

Output

[Errno 2] No such file or directory: 'xyz.txt'

This IOError exception message will print only when exception occurred.

Conclusion

Python IOError is a result of incorrect file name or file path. IOError occurred in multiple cases and these conditions can be handled using try except code block. Implementation way to handle IOError by try-except can check by above example.

Related Posts

Your Feedback Motivate Us

If our FacingIssuesOnIT Experts solutions guide you to resolve your issues and improve your knowledge. Please share your comments, like and subscribe to get notifications for our posts.

Happy Learning !!!

[Solved]: AssertionError in Python

What is Assertion in Python?

Assertion is use in programming language to declare condition which should be validate as true by using assert statement prior to running the module or line of code. If assert condition is true then program control moves to next line in case it’s false the program stops running and throw Python AssertionError exception.

Python AssertionError
Python AssertionError

Python Syntax of Assertion

assert condition, error_message(optional)

See Also:

Where to use Assertion?

In Python, Assertion can be use in following cases:

  • Checking valid input/type.
  • Checking values of parameters.
  • Detecting abuse of an interface by another programmer.
  • Checking output of a function.

Python AssertionError Example

x = 10
z = 0
# denominator can't be 0
assert z != 0, "Invalid Operation" 
print(x / z)

Output

Traceback (most recent call last):
  File "/home/xyz.py", line 4, in 
    assert z!=0, "Invalid Operation"
AssertionError: Invalid Operation

In this above Python program, The default exception handler will print the error message written by the programmer, or else will just handle the error without any message.

Solution AssertionError exception

AssertionError is subclass of Exception class, when this exception AssertionError occurs in program there are two ways to handle, either default exception handler or user handle it.

try:
    x = 10
    z = 0
    assert z != 0, "Invalid Operation"
    print(x / z)
  
#The configured error message will print in log
except AssertionError as err: 
    print(err)

Output

Invalid Operation

Conclusion

In this topic you learn about the Assertion in programming language and how to use it. In case any Python AssertionError occurs then you can handle it through Try-except exception handling.

Related Posts

Your Feedback Motivate Us

If our FacingIssuesOnIT Experts solutions guide you to resolve your issues and improve your knowledge. Please share your comments, like and subscribe to get notifications for our posts.

Happy Learning !!!

[Solved]: Python SyntaxError: (unicode error) ‘unicodeescape’ codec can’t decode bytes in position 2-3: truncated \UXXXXXXXX escape

Python SyntaxError occurred when you are trying to access a path with normal String. As you know ‘/’ is escape character in Python that’s having different meaning by adding with different characters for example ‘\n’ is use for one line , ‘\t’ use for tab.

This error is considered as Python SyntaxError because unicode forward slash (\) is not allow in path.

In further section of topic you will learn how to handle this problem in Python while writing path of file to access it.

See Also:

Example of Python SyntaxError of Unicode Error

Lets take below example to read CSV file in Windows operating system.

import csv
with open('C:\Users\saurabh.gupta\Desktop\Python Example\input.csv','r') as csvfile:
    reader=csv.reader(csvfile)
    for record in reader:
        print(record) 

If you notice the above code is having path for windows file system to access input.csv. In windows path mentioned by using forward slash (\) while in Python programming forward slash(\) is use for handling unicode characters. That’s why when you execute the above program will throw below exception.

Output

File "C:/Users/saurabh.gupta14/Desktop/Python Example/ReadingCSV.py", line 2
    with open('C:\Users\saurabh.gupta\Desktop\Python Example\input.csv','r') as csvfile:

Solution

The above error is occurred because of handling forward slash(\) as normal string. To handle such problem in Python , there are couple of solutions:

1: Just put r in path before your normal string it converts normal string to raw string:

with open(r'C:\Users\saurabh.gupta\Desktop\Python Example\input.csv','r') 


2: Use back slash (/) instated of forward slash(\)

with open('C:/Users/saurabh.gupta/Desktop/Python Example/input.csv','r') 

3: Use double forward slash (\\) instead of forward slash(\) because in Python the unicode double forward value convert in string as forward slash(\)’

with open('C:\\Users\\saurabh.gupta\\Desktop\\Python Example\\input.csv','r') 

If this solution help you , Please like and write in comment section or any other way you know to handle this issue write in comment so that help others.

Related Posts

Your Feedback Motivate Us

If our FacingIssuesOnIT Experts solutions guide you to resolve your issues and improve your knowledge. Please share your comments, like and subscribe to get notifications for our posts.

Happy Learning !!!

[Solved]: StopIteration in Python

Python StopIteration Error is an exception which occurred by built-in next() and __next__() method in iterator to signal that iteration is done for all items and no more to left to iterate.

Example of Python StopIteration Error

In this example string value “FacingIssuesOnIT” is Iterating to print character. In this case while loop will run indefinitely and call next() method on iterable value to print value.

iterable_value = 'FacingIssuesOnIT'
iterable_obj = iter(iterable_value)
 
while True:
    try: 
        # Iterate by calling next
        item = next(iterable_obj)
        print(item)
    except StopIteration as err:
        print('Stop Iteration occured')
        break

Output

F
a
c
i
n
g
I
s
s
u
e
s
O
n
I
T
Stop Iteration occurred

In this program after completing the iteration next() element print of iterable_value when it goes to next element print it will throw StopIteration exception because there is no more element in iterable_value.

Solution

Whenever you apply the next() method of iterable object always check the length of iterable object then run the loop to get element by next() method otherwise through Python StopIteration Error.

Related Posts

Your Feedback Motivate Us

If our FacingIssuesOnIT Experts solutions guide you to resolve your issues and improve your knowledge. Please share your comments, like and subscribe to get notifications for our posts.

Happy Learning !!!

[Solved]: AttributeError in Python

Python AttributeError is sub class of Exception. Python AttributeError occurred when an attribute reference or assignment fails because pointing object does not support attribute references or attribute assignment.

See Also:

Python AttributeError Example

In this Python program, Test class is having attribute p and initialize with 0 inside the constructor __init__().

class Test:
    def __init__(self):
        self.p = 0
f = Test()
print(f.p)
print(f.q)

Output

    print(f.q)

AttributeError: 'Test' object has no attribute 'q'

This program is throwing Python AttributeError in line 6 because attribute q is not declared inside the class Test but trying to print through program that’s why throw Python AttributeError.

Solution

To solve this problem you can handle exception in program by using try and except block.

try:
    class Test:
        def __init__(self):
            self.p = 0
    f = Test()
    print(f.p)
    print(f.q)
except Exception as e:
    print (e)
    print ('This is an example of StandardError exception')

Output

'Test' object has no attribute 'q'
This is an example of AttributeError exception

Conclusion

In this topic you learn about the case when the AttributeError occurred in Python program and way to handle this error through exception handling.

Related Posts

Your Feedback Motivate Us

If our FacingIssuesOnIT Experts solutions guide you to resolve your issues and improve your knowledge. Please share your comments, like and subscribe to get notifications for our posts.

Happy Learning !!!

[Solved]: Python FloatingPointError

In Python, FloatingPointError is subclass of ArithmeticError. FloatingPointError occured with floating point operations when floating point exception control (fpectl) is turned on.
To Enable fpectl in Python requires an interpreter compiled with the –with-fpectl flag.

Note : In Python, fpectl module is not built by default, you have explicitly import it to control over the floating point units from several hardware manufacturer. This allow the use to turn on the generation of SIGFPE whenever any IEEE-754 exceptions Division by Zero, Overflow, or Invalid Operation occurs.

Example FloatingPointError

The below example is created to occurs FloatingPointError in Python program where just trying exponential of number with certain values before and after enabling the fpectl.

import sys
import math
import fpectl
try:
    print ('FPECTL Control Not Enable:', math.exp(750))
    fpectl.turnon_sigfpe()
    print ('FPECTL Control Enabled:', math.exp(750))
except Exception as err:
    print (err)
    print (sys.exc_type)

Output

FPECTL Control Not Enable: 1.01423205474e+304
FPECTL Control Enabled: in math_1
<type 'exceptions.FloatingPointError'>

Solution

When dealing with any floating point number and performing operation where precision values can be more always handle Exception.

To learn more on exception handling follow the link Python: Exception Handling.

If this blog for solving FloatingPointError help you to resolve problem make comment or if you know other way to handle this problem write in comment so that it will help others.

[Solved]: Python OverflowError : (34, ‘Result too large’)

In Python, OverflowError is subclass of ArithmeticError. This error occurred for floating points numbers when size exceed the limit of variable type.

In case of Integer when size grow variable convert to long value. If variable size exceed the limit of Long also then Python throw MemoryError.

Example of OverFlowError

In this Python program we are just continually multiplying the value for floating numbers with 2 as long as for loop condition match (50 times) because it’s floating number and having limit of size once this size limit will exceed will throw exception as OverflowError.

i=1
try:
    f = (2.0**i)
    for i in range(50):
        print (i, f)
        f = f ** 2
except OverflowError as err:
    print ('Overflowed on power ', f, err)

Output

0 2.0
1 4.0
2 16.0
3 256.0
4 65536.0
5 4294967296.0
6 1.8446744073709552e+19
7 3.402823669209385e+38
8 1.157920892373162e+77
9 1.3407807929942597e+154
Overflowed on power  1.3407807929942597e+154 (34, 'Result too large')

If you noticed this Python program this is throwing error as “OverflowError: (34, ‘Result too large’)” because floating variable size is continuesly increasing once it will reach to 34 for precision will throw OverflowError.

Solution

In Python, when you are performing operation of floating number and these operations are inside the recursive method or loops then always handle the OverflowError by try catch block so that your program will not terminate.

[Solved]: Python NameError: name ‘XYZ’ is not defined

In Python, NameError occurred for identifier when it’s being used but not defined in local or global scope so Python will able to find and throw exception. NameError can be occurred by following reasons:

1: Misspelled built-in function
2: Using unidentified variables
3: Define variable after used
4: Incorrect Usage of Scope

Note : In any programming language Identifier is name of variable, function, class or object.

We will discuss in detail about all these above cases with example.

Example : Misspelled built-in function

In this example by mistake not type correct name for print function. I have written as ‘prin’ instated of ‘print’ that’s why Python with throw NameError.

sugar_weight = input("Enter how much sugar you want: ")
prin(sugar_weight)

Output

   prin(sugar_weight)

NameError: name 'prin' is not defined

Example : Using unidentified variables

In this example calculating the sub of variable ‘A’ and ‘B’ but variable B is not defined that’s why Python with throw NameError.

A=5
sum=A + B
print("Sum:"+sum)

Output

   sum=A + B

NameError: name 'B' is not defined

Example : Define variable after used

In this example the variable sum is getting printed before going declare or assigned that’s why Python with throw NameError.

A=5
B=10
print("Sum:"+add)
add=A + B

Output

 print("Sum:"+add)

NameError: name 'add' is not defined

Example : Incorrect Usage of Scope

In this example the avg variable is having local scope with in the function calculateAverage but trying to access for print outside the function. In this case This avg variable will be undefined out the calculateAverage() method then Python will throw NameException.

def calculateAverage(numbers):
    avge = sum(numbers)/len(numbers)

numbers=[10,20,30,40,50] 
calculateAverage(numbers)
print(avge)

Output

  print(avge)

NameError: name 'avge' is not defined

Solution for NameError

In Python NameError related to variable or function name must be fix by modifying the name of variable or correct the code. In case NameError can occurred on runtime then you can explicitly use try and except block to handle NameError.

def calculateAverage(numbers):
    avge = sum(numbers)/len(numbers)
try:
	numbers=[10,20,30,40,50] 
	calculateAverage(numbers)
	print(avge)
except NameError:
    print ("NameError occured in code because some variable isn't defined.")

Output

NameError occured in code because some variable isn't defined.

Conclusion

In this topic you learn about the different cases where NameError can be occurred. It’s explained with example for NameError and finally provided solution to handle NameError by exception handling.

To learn more on exception handling follow the link Python: Exception Handling.

If this blog for solving NameError help you to resolve problem make comment or if you know other way to handle this problem write in comment so that it will help others.

[Solved] : Python TypeError: ‘builtin_function_or_method’ object is not iterable

In Python, When in built-in function used it must be specify with parenthesis (()) after the name of the function. If you try to run or iterate the program over a built-in method or function without parenthesis (()) the Python will throw exception as “TypeError: builtin_function_or_method is not iterable”.

Exampe TypeError: builtin_function_or_method is not iterable

Let’s consider the scenario of successful execution of a built in function in Python.

fruits = ["Papaya", "Orange", "Grapes", "Watermelon", "Apple"]
print(", ".join(fruits))

In Python, The join() is a built-in function which turns a list into a string and adds a separator between each value in a string. The output of code as below.

Output

Papaya, Orange, Grapes, Watermelon, Apple

In case while writing code, you forget the brackets (()) in built-in function then Python will throw an error. In this below scenerio will throw exception as “TypeError: builtin_function_or_method is not iterable

user = {
    "name": "Saurabh Gupta",
    "age": 35,
    "city": "Noida"
}
#iterate user dictionary
for key, value in user.items:
    print("Key:", key)
    print("Value:", str(value))

Output

File "C:/Users/saurabh.gupta/Desktop/Python Example/test.py", line 7, in <module>
    for key, value in user.items:

TypeError: 'builtin_function_or_method' object is not iterable

The above example is throwing as “TypeError: ‘builtin_function_or_method‘ object is not iterable” because while using items function of dictionary programmer missed to write parenthesis (()) because for loop is iteration operation and it’s required Iterable object but items method is used without parenthesis that’s why Python is considering as object and throwing exception as “TypeError: ‘builtin_function_or_method’ object is not iterable“.

Solution

To resolve such problem related to built-in function or any function always write method with parenthesis (()).

You make correct the above program by writing items method with parenthesis as below in line no 7

user = {
    "name": "Saurabh Gupta",
    "age": 35,
    "city": "Noida"
}
#iterate user dictionary
for key, value in user.items():
    print("Key:", key)
    print("Value:", str(value))

Output

Key: name
Value: Saurabh Gupta
Key: age
Value: 35
Key: city
Value: Noida

Conclusion

This type of exception “TypeError: builtin_function_or_method is not iterable” is common when user forget to use parenthesis (()) while using built-in function.

To learn more on exception handling follow the link Python: Exception Handling.

If this blog for solving TypeError help you to resolve problem make comment or if you know other way to handle this problem write in comment so that it will help others.

[Solved]: Python ValueError: invalid literal for int() with base 10

Python supports explicit type conversion by converting values to different data types. In Python you can convert integers to strings, strings to integers, floats to integers but one conversion Python does not support a float as a string to an integer. In if you try to convert from float as an string to integer then it throw exception as “ValueError: invalid literal for int() with base 10“.

Example: ValueError: invalid literal for int() with base 10

Let’s take a below example where asking weight as input from user, as you know weight can be float value. In this example if user input weight more than 10 KG then user will get discount of 100 Rs. otherwise not discount.

sugar_weight = input("Enter how much sugar you want: ")

sugar_weight_as_int = int(sugar_weight)

if sugar_weight_as_int > 10:
    print("You have discount of 100/- Rs.")
else:
    print("You do not have discount on sugar.")

Output

Enter how much sugar you want: 6.5
Traceback (most recent call last):
  File "main.py", line 3, in <module>
    sugar_weight_as_int = int(sugar_weight)
ValueError: invalid literal for int() with base 10: '6.5'

In this example throw exception as “ValueError: invalid literal for int() with base 10: ‘6.5’” because here user insert the sugar weight as 6.5 which is float string value now to comparing with integer value type casting as int but Python doesn’t support type casting from float string to integer that’s why Python will throw exception as “ValueError: invalid literal for int() with base 10: ‘6.5’“.

If you noticed the above error messages have two parts:

1: ValueError: This error occured when there is an issue with the value stored in a particular object.
2: Error Message “invalid literal for int() with base 10: ‘6.5’” : This means the value we have passed through an int() method cannot be converted because the int() method does not allow you to pass a float represented as a string.

Solution

To resolve this issue, you should convert this passing float string value to float then this exception will get resolve because Python allows float string to float conversion.

sugar_weight = input("Enter how much sugar you want: ")

sugar_weight_as_int = int(float(sugar_weight))

if sugar_weight_as_int > 10:
    print("You have discount of 100/- Rs.")
else:
    print("You do not have discount on sugar.")

Output

Enter how much sugar you want: 6.5
You do not have discount on sugar.

Conclusion

In Python “ValueError: invalid literal for int() with base 10” error is occurred when you try to convert a string value that is not formatted as an integer. To overcome this issue you can use the float() method to convert a floating-point number in a string to an integer. Then, you can use int() to convert your number to an integer.

If this solution does not work, make sure the input value of a string does not contain any letters because Strings with letters cannot be converted to an integer unless those letters have a special meaning.

To learn more on exception handling follow the link Python: Exception Handling.

If this blog for solving ValueError help you to resolve problem make comment or if you know other way to handle this problem write in comment so that it will help others.

[Solved]: Python IndexError: tuple index out of range

In Python, lists, tuples are indexed. It means each value in a tuple is associated with index position (0 to n-1) to access that value. Where N represent the total number of values in list or tuple. When user try access an item in a tuple that is out of range the Python returns an error that says “IndexError: tuple index out of range”.

Example: IndexError: tuple index out of range

Lets consider a below example for tuple of fruits. Where index of value start from 0 and up to (number of element -1).

fruits = ("Apple", "Banana", "Grapes", "Papaya", "Litchi")

This tuple fruits is having five values and each element is associated with index number as below:

AppleBananaGrapesPapayaLitchi
01234

To access the value “Grapes” from fruits tuple, we would use this code:

print(fruits[2])

Our code returns: Grapes. here we accessing the value at the index position 2 and print it to the console. Same way we can try with other values in tuple.

Now lets consider an example to create this IndexError, Try to access value by using index value out of range (3 to 6) where index position 5 is out of range and this example will throw exception as “IndexError: tuple index out of range“.

fruits = ("Apple", "Banana", "Grapes", "Papaya", "Litchi")
for i in range(2, 6):
    print(fruits[i])

Output

Grapes
papaya
Lichi

Traceback (most recent call last):
  File "main.py", line 4, in <module>
    print(fruits[i])
IndexError: tuple index out of range

Our code prints out the values Grapes, Papaya and Litchi. These are the last three values in our tuple. Then throw exception as “IndexError: tuple index out of range” because index position 5 is out of the range for elements in the tuple.

The Solution

Our range() statement creates a list of numbers between the range of 2 and 6. This number list is inclusive of 2 and exclusive of 6. Our fruits tuble is only indexed up to 4. This means that our loop range will try to access a fruit at the index position 5 in our tuple because 5 is in our range.

Now lets try to run this below updated program for loop range 2 to 5 then observe the result. To learn more on for loop follow link Python: for loop

fruits = ("Apple", "Banana", "Grapes", "Papaya", "Litchi")
for i in range(2, 5):
    print(fruits[i])

Output

Grapes
papaya
Litchi

Our code successfully prints out the last three items in our list because now accessing items at the index positions 2, 3, and 4 which is in range of fruit tuple indexes.

Conclusion

The IndexError: tuple index out of range error occurs when you try to access an item in a tuple that does not exist. To solve this problem, make sure that whenever you access an item from a tuple that the item for which you are looking exists.

To learn more on exception handling follow the link Python: Exception Handling.

If this blog for solving IndexError help you to resolve problem make comment or if you know other way to handle this problem write in comment so that it will help others.

[Solved]: Python TypeError: ‘int’ object is not subscriptable

In Python some objects are subscriptable. It means that they contain, or can contain, other objects. Integers are used to store whole numbers so that are not a subscriptable object. If programmer treat an integer like a subscriptable object, an error will be raised like “TypeError : ‘int’ object is not subscriptable“.

If you noticed this is TypeError and it occurs when you try to perform operation that’s doesn’t support on object for example when you concatenate string and int then it will throw TypeError . You can more detail on [Solved] TypeError: unsupported operand type(s) for +: ‘int’ and ‘str’.

Example : TypeError: ‘int’ object is not subscriptable

In this example, user is inserting date of birth in the format of DDMMYYYY then parse this date in Date (DD), Month(MM) and Year(YYYY).

dob = int(input("When is your date of birth? (ddmmyyyy) "))

day = dob[0:2]
month = dob[2:4]
year = dob[4:8]

print("Day:", day)
print("Month:", month)
print("Year:", year)

Output

When is your date of birth? (ddmmyyyy) 19051987
Traceback (most recent call last):

File “”, line 1, in
runfile(‘C:/Users/saurabh.gupta/Desktop/Python Example/Exception Test.py’, wdir=’C:/Users/saurabh.gupta/Desktop/Python Example’)

File “C:\ProgramData\Anaconda3\lib\site-packages\spyder\utils\site\sitecustomize.py”, line 705, in runfile
execfile(filename, namespace)

File “C:\ProgramData\Anaconda3\lib\site-packages\spyder\utils\site\sitecustomize.py”, line 102, in execfile
exec(compile(f.read(), filename, ‘exec’), namespace)

File “C:/Users/saurabh.gupta/Desktop/Python Example/Exception Test.py”, line 30, in
day = dob[0:2]

TypeError: ‘int’ object is not subscriptable

In this above example, user input date of birth (19051987) and convert this date to int. Which is now whole number and not subscriptable. now in code try to parse this date of birth in form of Day (DD), Month (MM) and Year (YYYY). Because it’s whole integer number when you try to parse this integer value will through exception as “TypeError: ‘int’ object is not subscriptable

Solution

In this above program issue is because programmer is explicitly type casting the string date of birth to integer which is whole number and not subscriptable to resolve this problem programmer need to remove this explicit integer type casting as below.

dob = input("When is your date of birth? (ddmmyyyy) ")

day = dob[0:2]
month = dob[2:4]
year = dob[4:8]

print("Day:", day)
print("Month:", month)
print("Year:", year)

Output

When is your date of birth? (ddmmyyyy) 19051987
Day: 19
Month: 05
Year: 1987

To learn more on exception handling follow the link Python: Exception Handling.

If this blog for solving KeyError help you to resolve problem make comment or if you know other way to handle this problem write in comment so that it will help others.

[Solved]: Python KeyError: XYZ in Python

In Python, KeyError occurred when try access a value in dictionary by key name but key don’t exist. If key found in dictionary will return a value if doesn’t exist then through KeyError : key_name .

How to handle KeyError in Python?

You can handle KeyError while accessing the key from dictionary by following ways:

  • Check for key in advance for accessing the key
  • Use the ‘in’ keyword to check for key
  • Use try and except block.

Example of KeyError in Python

Lets take simple example where user want to access key from dictionary to retrieve value. In this example if user input key name, age or city either of them then it will return value. if user input other value as key that doesn’t exist in dictionary then it will throw exception as KeyError: passing_key.

user = {
    "name": "Saurabh Gupta",
    "age": 35,
    "city": "Noida"
}

key_name=input("What information you want to get? (name, age, city)")
print(key_name+" :"+user[key_name])

Now as suggested above solution to KeyError, lets fix the above to problem to exception handle and show message in case user input other keys except in dictionary.

Solution 1 : Iterate all key and value

Lets take first solution to get keys from dictionary then retrieve values from dictionary.

user = {
    "name": "Saurabh Gupta",
    "age": 35,
    "city": "Noida"
}
#iterate user dictionary
for key, value in user.items():
    print("Key:", key)
    print("Value:", str(value))

In this solution user will able to print all values w.r.t each key.

Solution 2 : Advance check by in

Lets take second solution to fix this problem to check key in dictionary first by using ‘in’ in if statement. if key not available in dictionary then print else statement.

user = {
    "name": "Saurabh Gupta",
    "age": 35,
    "city": "Noida"
}

key_name=input("What information you want to get? (name, age, city)")
if key_name in user:
    print(key_name+" :"+user[key_name])
else:
    print(key_name +" key is not available in user")

in this solution if user input any key like name, age or city then print value otherwise print as key is not available.

Solution 3 : try and except

Lets take third solution to solve KeyError by using exception handling through try and except.

user = {
    "name": "Saurabh Gupta",
    "age": 35,
    "city": "Noida"
}

key_name=input("What information you want to get? (name, age, city)")
try:
    print(key_name+" :"+user[key_name])
except KeyError:
    print(key_name +" key is not available in user")

In this solution if key is correct then print value w.r.t key in dictionary. if key doesn’t exist and KeyError exception occurs the print statement as “Key is not available in user”.

To learn more on exception handling follow the link Python: Exception Handling.

If this blog for solving KeyError help you to resolve problem make comment or if you know other way to handle this problem write in comment so that it will help others.

[Solved]: Python SyntaxError

What is Syntax in programming Language?

In any programming language, Syntax are set of rules which dictate how program need to written. Every language have different syntax from other language like C, C++, Java, C# having curely bracket ({}) to represent block of statements while in Python blocks like if-else, loops, functions etc. represent by indentations. We can also think of example of our spoken language having grammar, punctuation etc.

You can identify these exceptions on runtime when you code give SyntaxError the you can fix it. In Python, Sometime programmer omit some set statement, not following indentation or programmer move from another language put curly bracket({}),semi colon (:) etc. then it show SyntaxError because python doesn’t support that.

In this blog you will learn about the some of the common Python SyntaxErrors, provide examples, and show you how to fix them.

Example 1:

In this below example where calculating average of numbers and returning final result to print but this simple example will through exception as in output

numbers = [8, 7, 9, 8, 7]

def calculate_average_age():
    average = sum(numbers) / len(numbers)
    print(average)
return average

total_average = calculate_average_age(numbers)
print(total_average)

Output

File “C:/Users/saurabh.gupta/Desktop/Python Example/Exception Test.py”, line 12
return average
^
SyntaxError: ‘return’ outside function

Solution

The above issue is because of indentation of return statement that’s why it’s showing in error as ‘return is outside the function’. To fix this problem return should be same intended as other statement of function as below.

numbers = [8, 7, 9, 8, 7]

def calculate_average_age():
    average = sum(numbers) / len(numbers)
    print(average)
    return average
total_average = calculate_average_age(numbers)
print(total_average)

Example 2

Let’s take another example of dictionary which will print the elements as key and value but this program will through exception as “SyntaxError: Invalid syntax“.

user = {
    "name": "Saurabh Gupta",
    "age": 35
    "city": "Noida"
}
#iterate user dictionary
for key, value in user.items():
    print("Key:", key)
    print("Value:", str(value))

Output

File “C:/Users/saurabh.gupta/Desktop/Python Example/Exception Test.py”, line 4
“city”: “Noida”
^
SyntaxError: invalid syntax

Solution

In this above example, if you noticed this exception occurred in the line 4 inside the dictionary. It’s because of missing commas in each element for key and value that’s why it’s showing exception as “SyntaxError: invalid syntax“.

You can modify the above code after adding comma in dictionary as below:

user = {
    "name": "Saurabh Gupta",
    "age": 35,
    "city": "Noida"
}
#iterate user dictionary
for key, value in user.items():
    print("Key:", key)
    print("Value:", str(value))

Output

The above line of updated code will return output as below:

Key: name
Value: Saurabh Gupta
Key: age
Value: 35
Key: city
Value: Noida

Summary

In this topic you learn about the Syntax inside the programming language and in case any SyntaxError happen in your code you can identify the problem by checking he stack trace of logs by line number then identify the problem accordingly fix it.

Learn Python exception handling in more detain in topic Python: Exception Handling

[Solved] Python ValueError: math domain error

In Python, some of the mathematics operation doesn’t support negative or zero values. In this case when you perform operation with negative value then on runtime Python throws exception as “ValueError: Mathematics Domain Error” .

Here are some operations like sqrt() , log() etc. method which doesn’t work with negative values.

Example:

In this below example, we will try to create scenario by passing both positive and negative numbers and see the results.

import math

number = input("Please insert a number: ")

square=math.sqrt(int(number))

print("Square of number "+str(number) +" is :"+str(square))

Output

Passing Positive Number : 5

Please insert a number: 5
Square of number 5 is :2.23606797749979

Passing Negative Number: -5

File “C:/Users/saurabh.gupta/Desktop/Python Example/Exception Test.py”, line 5, in
square=math.sqrt(int(number))

ValueError: math domain error

After passing the value as -5 it’s throwing the runtime exception as “ValueError:math domain error“.

Solution

The solution to handle such situation is apply condition which check for negative values in case any negative values pass by user the show message to user as this operation is not allow for negative values.

import math

number = input("Please insert a number: ")
if(int(number)>0):
    square=math.sqrt(int(number))
    print("Square of number "+str(number) +" is :"+str(square))
else:
    print("Negative values are not allow for SQRT() operation")

Output

Passing Positive Number : 5

Please insert a number: 5
Square of number 5 is :2.23606797749979

Passing Negative Number : -5

Please insert a number: -5
Negative values are not allow for SQRT() operation

If you noticed from above program in solution, I just put one condition to check the value of input number to resolve the problem “ValueError: math domain error

[Solved] Python ValueError: too many values to unpack (Expected X)

In Python, When bags are not unpack well then it throws exception as “ValueError: Too many values to unpack (Expected X) . This exception generally occurs in two cases:

  • When you try to iterate over a dictionary and unpack its keys and values separately.
  • When you forget to unpack every item from a list to a variable.

If you noticed this is ValueError and it’s occurred when you try to access value that doesn’t exists. Values can be any type like object, string, list or dictionary.

Example 1

In this below dictionary iteration example, print values of key and value from user dictionary but it will through exception as “ValueError: Too many values to unpack (expected 2)“. Its’ because loop is try to access two values key and value from dictionary while there is only value because dictionary consider each as value.

user = {
	"name": "Saurabh Gupta",
	"age": 35,
	"city": "Noida"
}
#iterate user dictionary
for key, value in user:
	print("Key:", key)
	print("Value:", str(value))

Output

File “C:/Users/saurabh.gupta/Desktop/Python Example/Exception Test.py”, line 13, in
for key, value in user:

ValueError: too many values to unpack (expected 2)

Solution

To resolve above problem and access key and value from dictionary each item , you can use dictionary items() method which analyze keys and values from dictionary and return these values in iteration. You can modify the code as below:

user = {
	"name": "Saurabh Gupta",
	"age": 35,
	"city": "Noida"
}
#iterate user dictionary
for key, value in user.items():
	print("Key:", key)
	print("Value:", str(value))

Output

After adding items() method in code you can observe below output which is returning key and value of dictionary.

Key: name
Value: Saurabh Gupta
Key: age
Value: 35
Key: city
Value: Noida

Note: Till Python 2.0 use method iteritems() in Python 3+ it’s replace with method items().

Example 2

In Python, allows sequence of values to assign on number of variables. In case number of values are more then variables, it throws exception as “ValueError: too many values to unpack (expected X)

grapes, bananas, apples, papaya = [250, 80, 200, 300, 500]

Output

It will throws exception as below because count of variables are less then the values on list.

File “C:/Users/saurabh.gupta/Desktop/Python Example/Exception Test.py”, line 11, in
grapes, bananas, apples, papaya = [250, 80, 200, 300, 500]

ValueError: too many values to unpack (expected 4)

In case number of values are less then variables, it throws exception as “ValueError: not enough values to unpack (expected X)”

grapes, bananas, apples, papaya = [250, 80, 200]

Output :

File “C:/Users/saurabh.gupta/Desktop/Python Example/Exception Test.py”, line 18, in
grapes, bananas, apples, papaya = [250, 80, 200]

ValueError: not enough values to unpack (expected 4, got 3)

This is because of number of values are less (3) while number of values

To resolve such type of issues, always make sure the number of variables should be equal to number of values in list.

[Solved]: Python TypeError: cannot unpack non-iterable NoneType object

In Python, TypeError is subclass of Exception. Python sequence can be unpacked. This means you can assign content of sequence to multiple variables. If you try to assign a None value to a variable by using this syntax then it throws error as “TypeError: Can not unpack Non-iterable None Type object”.

Note: Syntax error should not be handle through exception handling it should be fixed in your code.

You can check complete list of built-in exception hierarchy by following link. Python: Built-in Exceptions Hierarchy

How to unpack sequence elements to variables?

In this below unpacking sequence the elements of list will assign to variables in sequence. For example:

fruit_prices = [250, 80, 200]
grapes, bananas, apples = fruit_price

In the above code the values in fruit_prices will assign in variables as below :

grapes=250, bananas=80, apples=200

Lets take another example of unpacking sequence from function where return values from functions can be assigned in sequence of variables. For Example:

prices = [4.30, 5.90, 6.70, 3.90, 5.60, 8.30, 6.50]
def calculate_statistics(prices):
    average_price = sum(prices) / len(prices)
    largest_price = max(prices)
    return average_price, largest_price
average, largest = calculate_statistics(prices)
print("Average :"+str(average))
print("Largest :"+str(largest))

In this above example, If you will see it’s returning two values (line 5) from calculate_statistics function and returned values will assign to variables average and largest in sequence (line 6).

Average : 5.88

Largest : 8.30

Scenario for Exception

Now lets create scenario for creating exception, I have modified the above code with comments the line # 5. It will display the code as below

prices = [4.30, 5.90, 6.70, 3.90, 5.60, 8.30, 6.50]
def calculate_statistics(prices):
    average_price = sum(prices) / len(prices)
    largest_price = max(prices)
    #return average_price, largest_price
average, largest = calculate_statistics(prices)
print("Average :"+str(average))
print("Largest :"+str(largest))

When you execute the above code will through exception as below

average, largest = calculate_statistics(prices)

TypeError: ‘NoneType’ object is not iterable

In this example, Hope you understand the scenario as the number of values in sequence will assigned to value on same number of value.

Learn Python exception handling in more detain in topic Python: Exception Handling

[Solved] : Python TabError: inconsistent use of tabs and spaces in indentation

In Python, TabError is sub class of IndentationError. Python allows code style by using indentation by space or tabs. If you are using both while writing code for indentation then Python encounter “TabError : inconsistent use of tabs and spaces in indentation”.

In Python, Indentation is important because the language doesn’t depend on syntax like curly brackets to denote where a block of code starts and finishes . Indents tell Python what lines of code are part of what code blocks.

Note: Syntax error should not be handle through exception handling it should be fixed in your code.

You can see complete Python exception hierarchy through this link : Python: Built-in Exceptions Hierarchy.

Example

Consider a below scenario where indentation is use by implementing space and tab both on line 3 (used space for indentation) while in line 4 (used tabs for indentation). When you will run the below program it will throw exception as mentioned in output.

numbers = [3.50, 4.90, 6.60, 3.40]
def calculate_total(purchases):
	total = sum(numbers)
        return total
total_numbers = calculate_total(numbers)
print(total_numbers)

Output

File “C:/Users/saurabh.gupta/Desktop/Python Example/Exception Test.py”, line 10
return total
^
TabError: inconsistent use of tabs and spaces in indentation

Solution

To resolve this issue, you have done some minor change in your code for indentation by either space or tabs and run the program will work fine.

numbers = [3.50, 4.90, 6.60, 3.40]
def calculate_total(purchases):
    total = sum(numbers)
    return total
total_numbers = calculate_total(numbers)
print(total_numbers)

Output

18.4

Learn Python exception handling in more detain in topic Python: Exception Handling

Let me know your thought on it.

Happy Learning !!!

[Solved] : Python IndentationError: unexpected indent in Python

Base class of IndentationError is SyntaxError. This exception occurred in Python because of incorrect Indentation because Python don’t use curly brackets for segregate blocks for loop, if-else, functions etc. it’s identify the blocks based on indentation only. Sometime if with in same block there is difference in indentations then it can throw TabError.

Note: Syntax error should not be handle through exception handling it should be fixed in your code.

You can check complete list of built-in exception hierarchy by following link. Python: Built-in Exceptions Hierarchy

Example

Here is simple example of reading the csv file by Python csv module. It’s throwing indentation error because of not proper indentation in second statement.

import csv
   with open(r'C:\Users\saurabh.gupta14\Desktop\Python Example\input.csv','r') as csvfile:
    reader=csv.reader(csvfile)
    for record in reader:
        print(record)

Output

File “C:/Users/saurabh.gupta14/Desktop/Python Example/ReadingCSV.py”, line 2
with open(‘C:\Users\saurabh.gupta14\Desktop\Python Example’,’r’) as csvfile:
^
IndentationError: unexpected indent

Solution

In the above example the second line is start from after taking tab which is not required. It should start without taking any space or tab. To fixed this issue i have remove the space and run it again.

import csv
with open(r'C:\Users\saurabh.gupta14\Desktop\Python Example\input.csv','r') as csvfile:
    reader=csv.reader(csvfile)
    for record in reader:
        print(record) 

The above modified code with not throw the IndentationError.

Learn Python exception handling in more detain in topic Python: Exception Handling

Let me know your thought on it.

Happy Learning !!!

[Solved] Python ZeroDivisionError: division by zero in Python

The super class of ZeroDivisionError is ArithmeticError. This exception raised when the second argument of a division or modulo operation is zero. The associated value is a string indicating the type of the operands and the operation.

In simple term in any arithmetic operation when value divided by zero then in Python throw ZeroDivisionError.

You can see complete Python exception hierarchy through this link : Python: Built-in Exceptions Hierarchy.

Example :

In the Python program will throw ZeroDivisionError in case of num_list is not having any element then it’s length become 0 and while executing this program will through ZeroDivisionError.

num_list=[]
total=0
avg=total/len(num_list)
print("Average:"+avg)

Output

ZeroDivisionError : Division by Zero

Solution

While implementing any program logic and there is division operation make sure always handle ArithmeticError or ZeroDivisionError so that program will not terminate. To solve above problem follow this example:

num_list=[]
total=0
try:
    avg=total/len(num_list)
    print("Average:"+avg)
except ZeroDivisionError:
    print ("Zero Division Error occurred")

Output

Zero Division Error occurred.

In this above modified code applied exception handling for particular code section so that program will not terminate.

Learn Python exception handling in more detain in topic Python: Exception Handling

Let me know your thought on it.

Happy Learning !!!

Python: Exception Handling

What is an Exception?

In Python, Sometimes the programs may misbehave or terminate/crash unexpectedly due to some unexpected events during the execution of a program. These unexpected events are called as exceptions and the process of handling them to avoid misbehavior or crashing the program is called as exception handling.

Let’s execute the below code in python and have a look at the output.

	def calculate_expenditure(list_of_expenditure):
	    total=0
	    for expenditure in list_of_expenditure:
	        total+=expenditure
	    print(total)
	list_of_values=[100,200,300,"600",500]
	calculate_expenditure(list_of_values)

Above code will give an error, one way to take care of such error situation is to use selection constructs. The error was due to addition of a string (“600”) to an integer. If we add a condition to check whether the expenditure is of type int, that would solve this error.

But that can cause further issues. Let’s see that by executing the below code in python playground.

	def calculate_expenditure(list_of_expenditure):
	    total=0
	    for expenditure in list_of_expenditure:
	        if(type(expenditure) is int):
	            total+=expenditure
	        else:
	            print("Wrong data type")
	            break
	    print(total)
	
	list_of_values=[100,200,300,"600",500]
	calculate_expenditure(list_of_values)

Although we have handled this error using if statement, the function itself returns wrong output when there is error in the input. 
The ideal situation would be if the function can tell us that something went wrong.

try and except

In python we can create a try and except block of code to handle exceptions.
If any exception occurs in the try block of code, it will jump to except block of code. Once the except block is executed, the code continues to execute other statements outside except block.

	def calculate_expenditure(list_of_expenditure):
	    total=0
	    try:
	        for expenditure in list_of_expenditure:
	            total+=expenditure
	        print(total)
	    except:
	        print("Some error occured")
	    print("Returning back from function.")
	
	list_of_values=[100,200,300,"600",500]
	calculate_expenditure(list_of_values)

With this we will not get incorrect output like before.

Built-in Exceptions

Python has many kinds of exceptions predefined as part of the language. BaseException is the base class of all type of exception. Below are some most common types built-in exception.

You can check complete list of built-in exception hierarchy by following link. Python: Built-in Exceptions Hierarchy

Built-in exceptionWhen it will raiseExample
ZeroDivisionErrorWhen a value is divided by zero.num_list=[]
total=0
avg=total/len(num_list)
TypeErrorWhen we try to do an operation with incompatible type.total=10
total+=”20″
NameErrorWhen try to access a variable which is not defined.avg=total/10 #where total is not defined
IndexErrorWhen try to access a index value which is out of range.num_list=[1,2,3,4]
value=num_list[4]
ValueErrorWhen we use a valid data type for an argument of a built-in function but passes an invalid value for itstring is a valid data type for int() but the value “A” is invalid, as “A” can’t be converted into int.
value=”A”
num=int(value)

Python also allows us to handle different exceptions that can occur separately. That means you can have a different action or message for every unique exception that occurs.

Exception Handling Example

Here is the same expenditure calculation code with additional average expenditure calculation.

	def calculate_expenditure(list_of_expenditure):
	    total=0
	    try:
	        for expenditure in list_of_expenditure:
	            total+=expenditure
	        print("Total:",total)
	        avg=total/num_values
	        print("Average:",avg)	    
        except ZeroDivisionError:
	        print("Divide by Zero error")
	    except TypeError:
	        print("Wrong data type")
	    except:
	        print("Some error occured")
	list_of_values=[100,200,300,"400",500]
	num_values=0
	calculate_expenditure(list_of_values)

Note:

  1. Default except block is the one without any type mentioned.
  2. If an error occurs and the matching except block is found, then that is executed.
  3. If an error occurs and the matching except block is not found, it executes the default except block.
  4. If an error occurs and the matching except block is not found and if the default except block is also not found, the code crashes.
  5. The default except block, if present should be the last except block, otherwise it will result in a runtime error.

Exception handling inside a function

If an exception occurs inside a function and if the exception is not caught inside it, then the exception is transferred to the function call. We have another opportunity to catch it, if we write function call inside another try and except block.

Try the below code in python playground and observe the output.

	def calculate_sum(list_of_expenditure):
	    total=0
	    try:
	        for expenditure in list_of_expenditure:
	            total+=expenditure
	        print("Total:",total)
	        avg=total/no_values
	        print("Average:",avg)
	    except ZeroDivisionError:
	        print("Divide by Zero error")
	    except TypeError:
	        print("Wrong data type")
	
	try:
	    list_of_values=[100,200,300,400,500]
	    num_values=len(list_of_values)
	    calculate_sum(list_of_values)
	except NameError:
	    print("Name error occured")
	except:
	    print("Some error occured")

finally

Sometimes in programming we need to execute some code irrespective of whether the primary program logic itself succeeds or fails to do its job. In Python we can achieve this using a finally block. A finally block of statement is an optional part of the try-except statements. A code written inside the finally block will ALWAYS be executed.

finally block is majorly used to close the database connections in the programs which involves database connectivity.

Try the below code in python playground and observe the output.

	balance=1000
	amount="300Rs"
	
	def take_card():
	    print("Take the card out of ATM")
	try:
	    if balance>=int(amount):
	        print("Withdraw")
	    else:
	        print("Invalid amount")
	except TypeError:
	    print("Type Error Occurred")
	except ValueError:
	    print("Value Error Occurred")
	except:
	    print("Some error Occurred")
	finally:
	    take_card()

In this topic you learn about the exception, built-in exceptions and handling of exceptions in different cases.

Python: Built-in Exceptions Hierarchy

In Python version 3.9.2 is having the below class hierarchy for built-in exceptions. You will get to know more about each exception and solutions on click of it.

In Python, to learn about the exception handling follow the topic Exception Handling in Python.

Python: Variable Scope

This code has been written in Python to represent the baggage weight check process based on the weight limit specified by an airline.

You can go through the below code and guess the output.

	wt_limit=30
	
	def baggage_check(baggage_wt):
	    extra_baggage_charge=0
	    if not(baggage_wt>=0 and baggage_wt<=wt_limit):
	        extra_baggage=baggage_wt-wt_limit
	        extra_baggage_charge=extra_baggage*100
	    return extra_baggage_charge
	
	def update_baggage_limit(new_wt_limit):
	    wt_limit=new_wt_limit
	    print("This airline now allows baggage limit till",wt_limit,"kgs")
	
	print("This airline allows baggage limit till",wt_limit,"kgs")
	print("Pay the extra baggage charge of",baggage_check(35),"rupees")
	update_baggage_limit(45)
	print("Pay the extra baggage charge of",baggage_check(35),"rupees")	 

Let us go through the code now in more detail to see the scope of variables.

Python scope of variables

extra_baggage and extra_baggage_charge are created inside the function baggage_check(). Hence they are local to that function or in other words, they are local variables. They are created when owning function starts execution and remains in memory till owning function finishes execution. They can be accessed only inside that function.

wt_limit is created outside the functions. Hence it is a global variable. Global variables are created when the program execution starts and remains in memory till the program terminates. They can be read anywhere in the program – within a function or outside. But they are protected from modification inside a function. As it is available throughout the program, use of global variable should be restricted to avoid accidental misuse by developers and to minimize memory usage.

In cases where a global variable needs to be modified inside a function, like in function update_baggage_limit(), Python allows you to do that using the global keyword.

Python Variable Scope

Python: Typs of Argument

Programming languages allow controlling the ordering and default values of arguments. In python we will observe the following in different cases:

Case 1: Positional

This is default way of specifying arguments. In this, the order, count and type of actual arguments should exactly match that of the formal arguments. Else it will result error.

Python: Positional Argument

Case 2: Keyword

This allow flexibility in the order of passing the actual arguments by mentioning the argument name.

Python : Keyword in argument

Case 3: Default

This allows the specify default value for an argument in the function signature. It is used only when no value is passed for the arguments else it works normally. In Python, default arguments should be last in the order.

Python: Default Argument

Case 4: Variable argument count

This allows a function to have variable number of arguments. In Python, any argument name starting with ‘*’ is considered to be a vary length argument. It should be last in order, It works by copying all values beyond that position in a tuple.

Python: Variable argument count

Python: Argument Passing

In programming, there are two ways in which arguments can be passed to functions: 

  • Pass by value
  • Pass by reference

Some languages use pass by value by default while others use pass by reference. Some languages support both and allow you to choose.

In Python, we don’t have to think about pass by value and pass by reference as it does that automatically for you. To emulate this using Python, we use the concept of mutability. If the argument passed is immutable then it follows pass by value, else if the argument passed is mutable then it follows pass by reference.

Note: Till now we have seen int, float, string data types which immutable and mutable data types we will discuss in later part of the topics.

Pass by reference method

Pass by reference case apply on mutable type values, In this case value pass as reference to a method in case any change done with in function will reflect out side the function also. From below example you will see formal and actual argument point to same data location because of reference value.

Python Pass by reference

Pass by value method

Pass by value case apply on immutable variables/arguments in case value change with in the function then changes done on function will not reflect out side of the method. From the below example you will see the storage of formal and actual argument are separate.

Python pass by value method

Functions in Python

Functions are set of instructions to perform a specific task. A function is a block of code which only runs when it is called. You can pass data, known as parameters/argument, into a function. It also called as method.

Syntax

Below is the syntax of functions in python. In the below example you will get more clarity about the function syntax.

Define Function

def function_name([arg1,…,argn]): 
    #statements 
    [return value] 

Call Function
variable_name = function_name([val1,…,valn])

Note: Anything enclosed in [ ] (square bracket) is optional

Function can we call from any program, class or from another functions also.

Example

This is simple example of function, where calculate_sum function is performing the task of sum of two numbers/ passing arguments data1 and data2 and returning final result in value result_sum.

Python Functions Example

Output

30

Returning from a function

Let’s see how we can use values returned from a function.

Python return from a function

In the above screen display the different cases of return value from a function. It’s depend on your task in case your task required to return value then return one result value from function then assign this value to some variable where you call this function.

In case, you need return multiple value you can use reference type variable like array or you can also change value in passing argument if these are reference type and can be access out side the function. You will get more detail of reference variable in next topic Argument passing in Python.

Python: Control Structure

In Python, The commonly used control structures are:

Selection Statements

During the execution of the program, we may not wish to execute all sets of statements sequentially. Sometimes we may wish to select between the set of statements based on some conditions. Based on the test condition evaluation, the flow is determined inside the program. Here is the list of selection statements in Python:

  • If statement: It is a conditional statement used for decision making in python. Example
  • else if statement: It is a conditional statement if block condition is false then execute the else block. Example
  • else if ladder statement: These are multiple else if statement in sequence if one condition not match then go next else for condition check .Example
  • Nested if statement: You can write if block with in another if block that is called nested if. Example

The example of if, else, elif and nested if will discuss in further blogs in more detail.

Looping Statements

Looping statements are used to execute the same block of code multiple times in python based on the test condition. Here is the list of looping statements in python.

  • while loop: The while loop is used to execute a piece of code as long as the test condition is true. While loop is preferred whenever the number of iterations is not known. Example
  • for loop: In python, for loop allows the loop to run over a specific sequence of values. In other words, for every value in the sequence, the loop runs once. Thus we can avoid infinite loops by using a for loop. Example
  • Nested loops: Loop with in another loop is called as nested loop. Example

The example of while loop, for loop and nested loop will discuss in further blogs in more detail.

Loop Control Statements

The flow inside looping statements are controlled using the looping control statements like pass, break and continue.

  • break: When we want to stop a loop or break away from it we can use the break statement. Example
  • continue: When we want to skip the remaining portion of loop statements and continue with the next iteration, we can use the continue statement. Example
  • pass : pass is a null statement that is used to do create empty blocks. When the pass is executed, it results in no operation and the control will move to the next statement applicable. Example

The example of the break, continue, and pass will discuss in further blogs in more detail.

Python: pass Loop Control Statement

The flow inside looping statements are controlled using the looping control statements like pass, break and continue.

In python, pass is a null statement which is used to do create empty blocks. When pass is executed, it results in no operation and the control will move to the next statement applicable.

Example

Below example program shows how pass can be used to create a empty if block.

num=10
count=0
while(count <= num):
   if(count%2 == 0):
	  pass
   else:
	  print(count)
   count+=1

Output

1
3
5
7
9

In the above example try to explain the case of pass statement and treat as empty block. Otherwise same case be handle through continue with same result.

Python: continue Loop Control Statement

The flow inside looping statements are controlled using the looping control statements like pass, break and continue.

When we want to skip the remaining portion of loop statements and continue with the next iteration, we can use continue statement.

Example

Go through the below code, Assume A – Adult passenger, C- Child, FC – Flight Captain, FA – Flight Attendant, SP – Suspicious passenger.

for pasngr in "A","A", "FC", "C", "FA", "SP", "A", "A":
	if(pasngr=="FC" or pasngr=="FA"):
	   print("No check required")
	     continue
	
	if(pasngr=="SP"):
	    print("Declare emergency in the airport")
	    break	
	if(pasngr=="A" or pasngr=="C"):
	    print("Proceed with normal security check")
print("Check the person")
print("Check for cabin baggage")


Output

Proceed with normal security check
Check the person
Check for cabin baggage
Proceed with normal security check
Check the person
Check for cabin baggage
No check required
Proceed with normal security check
Check the person
Check for cabin baggage
No check required
Declare emergency in the airport

In this above example, if you will see when value of passenger is FC or FA then it will execute the statement inside the if block because it’s having continue keyword the the next statement after continue will skip and pointer will reach to next value of for loop.

Same as when passenger will value will be SP then this block having break keyword, it will terminate the loop and stop execution inside the loop and pointer will directly jump to next statement after loop.

Python: for loop

In python, for loop allows the loop to run over a specific sequence of values. In other words, for every value in the sequence, the loop runs once. Thus we can avoid infinite loops by using a for loop.

Syntax

Python for loop

Example

Similar to example of while loop lets handle same scenario with for loop:

	for number in 1,2,3,4,5:
	    print("The current number is ",number) 

Output

The current number is  1
The current number is  2
The current number is  3
The current number is  4
The current number is  5

In the above for loop , the statement inside the loop will execute for each value of number.

Another variation of for loop

In Python, there is an easy way to achieve this by using range(x,y,step). It creates a sequence from x to y-1 with a difference of step between each value. 

Example

	start=1
	end=10
	step=2	
	for number in range (start, end, step):
	    print("The current number is ", number) 

Output

The current number is  1
The current number is  3
The current number is  5
The current number is  7
The current number is  9

In the above example of for loop, the start value will vary from 1 to end-1 i.e 9 and each step increase start value as step 2.

Python: while loop

The while loop is used to execute a piece of code as long as the test condition is true. While loop is preferred whenever the number of iterations is not known.

Syntax

Python while loop

Example

	num=5
	count=1
	while count <= num:
	    print("The current number is:",count)
	    count+=1

Output

The current number is: 1
The current number is: 2
The current number is: 3
The current number is: 4
The current number is: 5

In the above example, while loop will check the condition continuously the value count and compare with num value as long as condition is true. In case of true all the statement inside the while loop will execute.

Python: Nested if Statement

An if statement within another if statement is known as nested if statement. Similarly, any decision logic can be written within an else statement also.

Have a look at the below example of nested if:

Example

num1=10
num2=20
num3=30
	
if(num1>num2):
	if(num1>num3):
      print("num1 is greater")
	else:
	  print("num3 is greater")
elif(num2>num3):
	print("num2 is greater")
else:
	print("num3 is greater")

Output

num3 is greater

in this above example, one if statement is inside of another if block. It’s good example of nested if statement.

Python:else-if Ladder

It is a conditional statement used for selection between multiple set of statements based on multiple test conditions. The various test conditions are provided inside each if statement. Whenever the test condition is evaluated as True, the statements inside the corresponding if block are executed and the control comes out of the else-if ladder. If none of the test conditions are evaluated as True, the statements inside the else block are executed. As we have multiple set of statements to select based on the test conditions, it is also called as multi way selection statement.

In else-if ladder the conditions are evaluated from the top of the ladder downwards. As soon as a true condition is found, the statement associated with it is executed skipping the rest of the ladder.

Below is the syntax of else-if ladder statement:

Python else-if statement

Example

	a=0
	if(a>0):
	    print("positive integer")
	elif(a<0):
	    print("negative integer")
	else:
	    print("it’s zero") 

Output

It’s zero

In this above example, first evaluate the condition in if but a=0 so condition in if statement will result as false. Then it will go to next else if statement to evaluate the condition but the condition evaluation value will be false then it will go to else statement and execute all statement inside of it.

Python: If-Else Statement

It is a conditional statement used for selection between two set of statements based on the evaluation of test condition. The statements inside the if block are executed only if the evaluated condition is true. Otherwise statements inside the else block are executed. As we have two set of statements to select based on the test condition, it is also called as Two-way selection statement.

Below is the syntax of if-else statement:

Python if-else statement

Example

	a=-10
	if(a>0):
		print("positive integer")
	else:
		print("Not a positive integer")

Output

Not a positive integer

In the if statement will evaluate condition and result as false then it will jump to else block then it will execute statement of else block.

Python : If Statement

It is a conditional statement used for decision making in python. In if statement, the test condition is evaluated and the statements inside the if block are executed only if the evaluated condition is true. In if statement, we have only one set of statements to select based on the test condition. So, it is also called as One-way selection statement.

Below is the syntax of simple if statement:

Python if Statement

Example:

a=10
if(a>0):
   print("Positive Integer")

Output

Positive Integer

Python: Excel Read and Write

Python uses openpyxl module to read, write and modify Excel files. This module acts as an interface between our python script and the excel file.

What is Excel File, Workbook, Row, and column?

An Excel file called as Workbook is a collection of sheets called as Worksheets. Each sheet is further divided into rows and columns.

The intersection of a row and a column is called a Cell. Cells hold the data of an Excel sheet.

How Python read & write to excel file?

In order to work with an Excel sheet, we first need to load that excel workbook into our program and then fetch the required worksheet from the workbook object. Once the workbook will load successfully you can point to any sheet in the workbook and then read and write to cell based on selected rows and columns.

In the further section, you will get to know about openpyxl module methods and attributes for each type of case to fetch data or update data to an excel file.

Load Workbook

load_workbook method can be used to load a workbook.

import openpyxl as xl
work_book=xl.load_workbook(r'Employee.xlsx')

Workbook Sheet Names

Once the workbook load successfully, Then you can get the list of sheet names or index the sheets to fetch the worksheet.

  • Sheet Names : sheetnames attribute of workbook object is used to display all the sheet names available in the workbook.
print('Sheet names:',work_book.sheetnames)
  • Specific Sheet: By indexing the sheet name can use to fetch data from specific sheet
work_sheet=work_book['Emp']

Accessing the cells

A cell in a worksheet can be accessed in two ways. 

  • The cell method of worksheet object can be used, we need to pass the row and column numbers as arguments to this method. 
    Note: The row and column numbers will begin from 1.
cell1=work_sheet.cell(1,1)
  • The worksheet object can be indexed with the cell reference to retrieve the corresponding cell object. such as ‘A2’ can be used to select the cell from 2nd row 1st column.
cell2=work_sheet['A2']

Note: The above two methods will return cell objects. The value stored in the cell can be retrieved using the value attribute of the cell object.

cell1.value
cell2.value

Maximum Rows and Columns

To check the maximum number of rows and columns with data in a given sheet. we can use max_row and max_column attributes of the worksheet object.

work_sheet.max_row
work_sheet.max_column

Sheet Slicing

In order to extract a portion of sheet, we need to use slicing. ws[‘A1′:’C4’] is used to extract cells that belong to rows 1 to 4 and columns ‘A’ to ‘C’.

cells=ws['A1':'C4']
for row in cells:
    for cell in row:
        print(cell.value,end=' ')
    print()

This will return a tuple of tuples each representing a row. Every row tuple will consist of cells that represent the columns.

Special Indexing

To retrieve individual rows and individual columns of the worksheet, we are going to use the respective indices of the rows and columns.

Example: ws[1] will retrieve all the cells that belong to 1st row. ws[‘A’] will retrieve all the cells that belong to 1st column.

cells=ws[1]
print('Items of row 1 are:',end=' ')
for cell in cells:
    print(cell.value, end=' ')
cells=ws['B']
print('\nItems of column B are:')
for cell in cells:
    print(cell.value)

This will return a tuple of cells.

Accessing Particular Records

Let us see how to retrieve the record of employee with id 3

import openpyxl as xl
wb=xl.load_workbook(r'Employee.xlsx')
ws=wb['Emp']
cells=tuple()
for row_num in range(2,ws.max_row+1):
    if ws.cell(row_num,1).value==3: 
        cells=ws[row_num]
        break
if cells:
    for cell in cells:
        print(cell.value,end=' ')
else:
    print('Employee record not found')

Note: Iterating is starting from the second row, since the excel sheet has headers in its first row.

Accessing Particular Column

Columns can be accessed in two ways.

  1. If we know the position of the columns, then we can access it using the column reference. 2nd column in a worksheet can be accessed as WS[‘B’]
  2. If we don’t know the column, then we need to validate using the headers and retrieve all the cells.

The below example displays names of all the employees

import openpyxl as xl
wb=xl.load_workbook(r'Employee.xlsx')
ws=wb['Emp']
cells=tuple()
for col_num in range(1,ws.max_column+1):
    if ws.cell(1,col_num).value.lower().strip()=='name': 
        for row_num in range(2,ws.max_row+1):
            cells+=ws.cell(row_num,col_num),
        break
if cells:
    for cell in cells:
        print(cell.value)
else:
    print('No Employees present')

Deleting a specific record

We can delete a record using delete_rows method of worksheet object. It accepts two parameters, 

  1. index – The index at which, we need to delete the row
  2. num – number of rows to be deleted

The below code is used to delete the record of employee with id 3.

import openpyxl as xl
filepath=r'Employee.xlsx'
wb=xl.load_workbook(filepath)
ws=wb['Emp']
for row_num in range(1,ws.max_row+1):
    if ws.cell(row_num,1).value==3: 
        ws.delete_rows(row_num,1)
        wb.save(filepath)
        print('Employee deleted')
        break
else:
    print('Employee not found')

Note: Any changes made will be persisted if and only if the save method of workbook object is invoked. Else, the changes will be lost

Deleting a specific column

We can delete a column using delete_cols method of worksheet object. It accepts two parameters, 

  1. index – The index at which, we need to delete the row
  2. num – number of rows to be deleted

The below code is used to delete salary column.

import openpyxl as xl
filepath=r'Employee.xlsx'
wb=xl.load_workbook(filepath)
ws=wb['Emp']
for col_num in range(1,ws.max_column+1):
    if ws.cell(1,col_num).value.lower().strip()=='salary': 
        ws.delete_cols(col_num,1)
        wb.save(filepath)
        print('Column deleted')
        break
else:
    print('Column not found')

Adding a new record

 To add a new record we need to use append method of worksheet object. append method accepts a list of items which represent a row.

The below code is used to add new employees to the existing sheet.

import openpyxl as xl
filepath=r'Employee.xlsx'
wb=xl.load_workbook(filepath)
ws=wb['Emp']
ws.append([4,'Bharti',10000])
wb.save(filepath)

Creating a new workbook

In order to create a workbook we need to create an object of Workbook class. The following example will help you to create a workbook,create a sheet, remove a sheet. Insert data into it and save it.

import openpyxl as xl
wb=xl.Workbook()
print(wb.sheetnames)
wb.create_sheet(title='Emp', index=0)
print(wb.sheetnames)
wb.remove(wb['Sheet'])
print(wb.sheetnames)
ws=wb['Emp']
 
ws['A1']="Name"
ws['B1']='Salary'
ws.append(['Saurabh',23400.0])
ws.append(['Gaurav',21529.12])
wb.save(r'Employee1.xlsx')

append method is used to insert a new row into the worksheet.
save method is used to save the current workbook.
create_sheet is used to create a new sheet.
remove_sheet is used to remove an existing sheet.

Summary

In this blog we have covered following sections to read and write to excel through Python by using openpyxl module:

  • Load data from workbook
  • Loading complete column and row data
  • Sheet slicing
  • Deleting/Displaying a particular row and column data
  • Create a new work book
  • Add and remove a work sheet from workbook
  • Insert data to worksheet

Python: CSV Read and Write

CSV (Comma Separated Values)?

A comma-separated values (CSV) file is a delimited text file that uses a comma to separate values. A CSV file stores tabular data (numbers and text) in plain text. Each line of the file is a data record. Each record consists of one or more fields, separated by commas. The use of the comma as a field separator is the source of the name for this file format.

How to handle CSV file records in Python?

In Python, there is a library/module named csv which is used to handle CSV files. It consists of methods for read and write operations.

In order to open a CSV file we use open() method. This method accepts two mandatory arguments which are the file name and the mode.

They are three different modes:

  1. Read mode – ‘r‘ is used to open a file in read mode.
  2. Write mode – ‘w‘ is used to open a file in write mode.
  3. Append mode – ‘a‘ is used to open a file in append mode.

Note: Whenever you try to open a file which is not existing on the file system, a new file will be created by the open method. The difference between write mode and append mode is ‘In write mode, the existing contents of the files will be deleted whereas in append mode the existing contents will be retained‘.

The csv module consists of methods that are useful to perform read and write operations.

Read Methods

  • reader() – reader  method accepts file object as an argument and returns a reader object. We can read each record as a list where each element in the list represents a column value.
  • dictReader() – DictReader() accepts file object as an argument and returns a DictReader object. Each record of csv file will be fetched as dictionary where keys represent the column names and values are their corresponding values.

Write Methods

  • writer() – writer method accepts file object as an argument and returns a csv writer object. We need to use writerow method in order to insert records. Lists are used to insert the data into file.
  • dictWriter() – DictWriter accepts filename and field names as arguments. Data which needs to be inserted should be in dictionary format and the keys of dictionary should match with the field names.

Sample CSV File Data

In further example of csv, we are going to use the following data. You can use same by place in text file and change extension of file with .csv

id,name,salary,start_date,dept
1,Saurabh,563.3,2018-01-15,IT
2,Gaurav,326.2,2016-09-23,Operations
3,Ramesh,360,2018-11-15,IT
4,Rajesh,729,2019-05-11,HR
5,Ranjith,986.25,2021-03-27,Finance
6,Rajendra,796,2018-05-21,IT
7,Ajay,423.8,2016-07-30,Operations
8,Bharti,934.5,2015-06-17,Finance

Sample CSV File

Here in the above data first-row, comma-separated values represent column name while the rest of the rows are data for each column.

Reading a CSV File

As explained in the above method definition. You can use these lines of statement to read CSV File.

import csv
   with open(r'C:\Users\saurabh.gupta14\Desktop\Python Example\input.csv','r') as csvfile:
    reader=csv.reader(csvfile)
    for record in reader:
        print(record)

Output

[‘id’, ‘name’, ‘salary’, ‘start_date’, ‘dept’]
[‘1’, ‘Saurabh’, ‘563.3’, ‘2018-01-15’, ‘IT’]
[‘2’, ‘Gaurav’, ‘326.2’, ‘2016-09-23’, ‘Operations’]
[‘3’, ‘Ramesh’, ‘360’, ‘2018-11-15’, ‘IT’]
[‘4’, ‘Rajesh’, ‘729’, ‘2019-05-11’, ‘HR’]
[‘5’, ‘Ranjith’, ‘986.25’, ‘2021-03-27’, ‘Finance’]
[‘6’, ‘Rajendra’, ‘796’, ‘2018-05-21’, ‘IT’]
[‘7’, ‘Ajay’, ‘423.8’, ‘2016-07-30’, ‘Operations’]
[‘8’, ‘Bharti’, ‘934.5’, ‘2015-06-17’, ‘Finance’]

If you noticed in the above example all the rows of CSV file read including column header and got printed.

Read CSV File by using DictReader

import csv
with open(r'C:\Users\saurabh.gupta14\Desktop\Python Example\input.csv','r') as csvfile:
    reader=csv.DictReader(csvfile)
    for record in reader:
        print(record) 

Output

OrderedDict([(‘id’, ‘1’), (‘name’, ‘Saurabh’), (‘salary’, ‘563.3’), (‘start_date’, ‘2018-01-15’), (‘dept’, ‘IT’)])
OrderedDict([(‘id’, ‘2’), (‘name’, ‘Gaurav’), (‘salary’, ‘326.2’), (‘start_date’, ‘2016-09-23’), (‘dept’, ‘Operations’)])
OrderedDict([(‘id’, ‘3’), (‘name’, ‘Ramesh’), (‘salary’, ‘360’), (‘start_date’, ‘2018-11-15’), (‘dept’, ‘IT’)])
OrderedDict([(‘id’, ‘4’), (‘name’, ‘Rajesh’), (‘salary’, ‘729’), (‘start_date’, ‘2019-05-11’), (‘dept’, ‘HR’)])
OrderedDict([(‘id’, ‘5’), (‘name’, ‘Ranjith’), (‘salary’, ‘986.25’), (‘start_date’, ‘2021-03-27’), (‘dept’, ‘Finance’)])
OrderedDict([(‘id’, ‘6’), (‘name’, ‘Rajendra’), (‘salary’, ‘796’), (‘start_date’, ‘2018-05-21’), (‘dept’, ‘IT’)])
OrderedDict([(‘id’, ‘7’), (‘name’, ‘Ajay’), (‘salary’, ‘423.8’), (‘start_date’, ‘2016-07-30’), (‘dept’, ‘Operations’)])
OrderedDict([(‘id’, ‘8’), (‘name’, ‘Bharti’), (‘salary’, ‘934.5’), (‘start_date’, ‘2015-06-17’), (‘dept’, ‘Finance’)])

Writing to CSV File

Here is the line of code to write to a CSV File. To write in CSV file use mode as ‘a’ to append to an existing file if you want to rewrite the complete new CSV file use mode as ‘w’.

import csv
with open(r'C:\Users\saurabh.gupta14\Desktop\Python Example\input1.csv','w') as csvfile:
	    writer=csv.writer(csvfile)
	    writer.writerow(['id','name','salary','dept'])
	    writer.writerow([1,'Sunny',22001.00,'Operation'])
	    writer.writerow([2,'Jony',26501.00,'HR'])


Output

Write to csv with new line

If you have observed the above output, we get a blank line between every record. This is because writerow method inserts a newline after every insertion and also open method also inserts a newline character. It can be removed as follows by adding newline=” in open method:

import csv
with open(r'C:\Users\saurabh.gupta14\Desktop\Python Example\input1.csv','w',newline='') as csvfile:
	    writer=csv.writer(csvfile)
	    writer.writerow(['id','name','salary','dept'])
	    writer.writerow([1,'Sunny',22001.00,'Operation'])
	    writer.writerow([2,'Jony',26501.00,'HR'])


Output

CSV file without new line

Write to CSV file using DictWriter

import csv
with open(r'C:\Users\saurabh.gupta14\Desktop\Python Example\input2.csv','w',newline='') as csvfile:
	    fields=['id','name','salary','dept']
	    writer=csv.DictWriter(csvfile,fields)
	    writer.writeheader()
	    writer.writerow({'id':1,'name':'Raghav','salary':22001.00,'dept':'HR'})
	    writer.writerow({'id':2,'name':'Rajendra','salary':26501.00, 'dept':'Opearation'})

Note: The key of dictionary should exactly map with the name in the fields name.

Output

Summary

In this blog you have learn about the different cases of CSV handling through Python csv module.

  • Read operation through csv
  • Write operation through csv

Python: Comments

Comments are the lines that are skipped during the execution of a program. There are two types of comments available in python:

  • Single Line Comment
  • Multi Line Comment

Single Line Comment

In Python, a Single line comment starts with the ‘#’ symbol and extends till the end of the line. Comments can start from the beginning of the line and middle of the line, but they should not be a part of the string literal.

Example:

#program to demonstrate explicit type conversion 
num1=10 #variable of integer type
num2="20" #variable of string type
result=num1+int(num2) #using explicit conversion 	print(result)

All the above statements (start with a # sign) mentioned in the code are examples of the single-line comments.

Multi Line Comment

In Python, Multiline comment which starts with ”’ or “”” and ends with ”’ or “”” respectively. Which is mainly used for documentation purposes.

Example:

'''
used for: Demonstrating comments 
This is the first way of using multi-line comment
'''
	
"""
used for: Demonstrating comments 
the second way of using multi-line comment	
"""

All the above statement (start with ”’ and “”” )mentioned in code are an example of the multiline comment. Such types of comments generally use in class level or method level documentation.

[Solved] TypeError: unsupported operand type(s) for +: ‘int’ and ‘str’

In Python, when we perform any operation on variables of different datatypes, the data of one variable will be converted to a higher datatype among the two variables and the operation is completed. This conversion is done by interpreter automatically and it is known as implicit type conversion. But Python does not support implicit type conversion of two different data types, and it will throw an error.

Example:

num1=20
num2="30"
result=num1+num2
print(result)

Output:

Traceback (most recent call last):
  File “D:SaurabhPythonsrctest.py”, line 3, in <module>
    result=num1+num2
TypeError: unsupported operand type(s) for +: ‘int’ and ‘str’

Solution

If we must avoid this, then we have to explicitly convert the datatype of one variable into the required data type to complete the operation. This is known as explicit type conversion.

Example:

num1=20
num2="30"
result=num1+int(num2)
print(result) 

Output:

50

Note:

Programming languages define their own rules for implicit and explicit conversions. These rules will change from language to language.

Similarly, one has to be careful in explicit conversions as well. For example,

  • Converting a floating-point value to integer would result in loss of decimal point values.
  • A larger data type if converted to smaller data type will result in loss of data as the number will be truncated.

Python: Type Conversion (Implicit & Explicit)

In Python, when we perform any operation on variables of different datatypes, the data of one variable will be converted to a higher datatype among the two variables and the operation is completed. This conversion is done by interpreter automatically and it is known as implicit type conversion. But Python does not support implicit type conversion of two different data types, and it will throw an error.

Example:

num1=20
num2="30"
result=num1+num2
print(result)

Output:

Traceback (most recent call last):
  File “D:\Saurabh\Python\src\test.py”, line 3, in <module>
    result=num1+num2
TypeError: unsupported operand type(s) for +: ‘int’ and ‘str’

Solution

If we must avoid this, then we have to explicitly convert the datatype of one variable into the required data type to complete the operation. This is known as explicit type conversion.

Example:

num1=20
num2="30"
result=num1+int(num2)
print(result) 

Output:

50

Note:

Programming languages define their own rules for implicit and explicit conversions. These rules will change from language to language.

Similarly, one has to be careful in explicit conversions as well. For example,

  • Converting a floating-point value to integer would result in loss of decimal point values.
  • A larger data type if converted to smaller data type will result in loss of data as the number will be truncated.

Python: Operators

Operators in python are the symbols used to perform an operation. Some of the most common operators used in Python are

CategoryOperators
Arithmetic Operators+, -, *, /,%,//
Relational Operators==,!=,<,>,>=,<=
Assignment Operators=,+=,-=,*=,/=,%=
Logical Operatorsand, or , not

You will see example and more detail of all these Python Operators in further sections.

Arithmetic Operators

Here is more detail about the Python supported Arithmetic Operators:

OperatorExplanationExample
+Used for addition operation“+” is used as addition operator where 11+2 is evaluated as 13
Used for the subtraction operation“-” is used as subtraction operator where 11-2 is evaluated as 9, 2-11 is evaluated as -9
*Used for a multiplication operation“*” is used as multiplication operator where 11*2 is evaluated as 22
/Used for division operation“/” is used as division operator where 11/2 is evaluated as 5.5
//Used for integer division operation“//” is used for integer division where 11//2 is evaluated as 5
%Used for the modulo operation, consider the expression num 1%num2 which finds the remainder after dividing num1 by num2“%” is used as modulo operator where 11%2 is evaluated as 1, 9%11 is evaluated as 9

Relational Operators

Here is more detail about the Python supported Relational Operators:

OperatorExplanationExample
==Used for checking the equality of two values/variable10==10 is evaluated as True
100==10 is evaluated as False
!=Used for checking the in-equality of two values/variable10 != 10 is evaluated as False
10 != 100 is evaluated as True
>Used for checking the of num1 is greater than num2 in num1 > num210 > 10 is evaluated as False
100 > 10 is evaluated as True
<Used for checking the of num1 is lesser than num2 in num1 < num210 < 10 is evaluated as False
10 < 100 is evaluated as True
>=Used for checking the of num1 is greater than or equal to num2 in num1 >= num210 >= 10 is evaluated as True
10 >= 100 is evaluated as True
<=Used for checking the of num1 is lesser than or equal to num2 in num1 <= num210 <= 10 is evaluated as True
100 <= 10 is evaluated as False

Assignment Operators

Here is more detail about the Python supported Assignment Operators:

OperatorExplanationExample
=Used for assigning value to a variablenum=5
Here num is assigned with the value 5
+=Used as short hand assignment operator additionnum=num+1 can be represented using short hand assignment operator as num+=1
-=Used as short hand assignment operator subtractionnum=num-1 can be represented using shorthand assignment operator as num-=1
*=Used as short hand assignment operator multiplicationnum=num1 can be represented using shorthand assignment operator as num=1
/=Used as short hand assignment operator divisionnum=num/1 can be represented using shorthand assignment operator as num/=1
%=Used as short hand assignment operator modulo operationnum=num%1 can be represented using short hand assignment operator as num%=1

Logical Operator

Here is more detail about the Python supported Logical Operators:

OperatorsDescription
ANDThe result will be true if both the expressions are true. If any one or both the expressions are false, the result will be false.
ORThe result will be true, even if one of the expressions is true. If both the expressions are false, the result will be false.
NOTIf the expression is true, the result will be false and vice versa.

If A and B are two relational expressions, say A = (Num1>2000), B= (Num2>100), the result of combining A and B using logical operator is based on the result of A and B as shown below:

You can also try all these operators in problem mentioned in Python Exercises.

Python: Input & OUTPUT Statements

While writing a program or develop any application need to required input from users on runtime by console (Keyboard) and after execution or debug the program required to show output on the console.

In the further section, you will learn how to enter user input on the running program and show output to the console.

input() Statement

Python provides input() built-in function to read the input from the console by using the standard input device (i.e. keyboard). Input function returns the string data irrespective of any datatype it is going to read as user input.

Syntax: variable_name = input([“user interactive statement”])

where,

variable_name is the variable assigned with the string value which is read using input method.

User Interactive statement is the statement displayed to the user expecting the response from them.

Example:

1.	input_var=input("please enter a number : ")
2.	print(input_var) 

Sample Output:

please enter a number: 100
100

print() Statement

Python provides print() built in function to print the output on to standard output device on console.

Syntax: print(“var_name1, var_name2, …”, [end=”value1”, sep=”value2”])

where,

var_name1, var_name2 are the variable names or the literals you want to print or output

end is used to specify the separator between two print statements which is ‘\n’ by default

sep is used to specify the separator between the different variables printed using print statement

Example:

	a="Saurabh"
	b=25.127
	c=20
	print(a,b,c)
	print(a,b,c,sep=":")
	print(a,b,c,end=" ")
	print(a,b,c)
	print("b=%0.2f" %b)
	print("c=%8d" %c)
	print("c=%-8d" %c) 

Sample Output:

Saurabh 20.127 10
Saurabh:20.127:10 #seperator between variables changed to ‘:’
Saurabh 20.127 10 infy 20.127 10 #seperator between two print statement changed to ” “
b=20.13 #as the format is 0.2 value is rounded of two decimal digits
c=10 #right aligned within the reserved 8 spaces 
c=10       #left aligned within the reserved 8 spaces as there is a – symbol

Through this Python input () and print() inbuilt function, you learn how to enter user input to run the program and print output statements in different formats.

Python: Variables & Data Types

Variables

Variables are like containers for data (i.e. they hold the data) and the value of variable can vary throughout the program.

Note: Python variables are dynamically typed so no need to specifically write data type of variable like other languages C, C++, Java, etc. It takes data type based on assigned literals on the variable.

Declaration of Variable

Variable name is also called as identifier. It contains alphanumeric characters, underscore but no space or special characters allowed. The first letter should be alphabetical character or underscore.

Syntax: var_name = literal_value

where var_name is the name given to container which holds the value specified as literal_value

Example: distance=10

In the above example, distance is the container that holds the value 10 which can change during the execution of the program.

Some more example of variable name:

  • Variable store different types of values
class_strength = 96 #int
_subject = "Science" # String
Marks = 76.3 # Float
  • Invalid variable declaration
student name ="Arvind" #space in variable name
1st_mark = 99.6 #start with numeric value in variable name

Data Types

Python supports all these data  types: 

CategoryData TypeExample
Numericint124
Numeric long1247171381763817
Numeric with a decimal pointfloat124.46
Numeric with a decimal point double124124.32395324
AlphanumericcharA
Alphanumeric stringHello
BooleanbooleanTrue, False

Why Python is Dynamically Typed Language?

Python is called a Dynamically typed language because on time of declaring variable datatype was not mentioned and python considers these datatype based on assigned literal value.

Example:

distance=96 #line 1
print(distance, type(distance)) #line 2

Output :

96 <class ‘int’>

In line 1, variable distance is assigned a value 96 which is an integer, so the data type of variable num is an integer in line 1 and second-line 2 statement printing value of the variable and it’s type i.e int

Note: To check the datatype of the variable we can use type(var_name) which in turn returns the data type of the variable.

Data Types

Python support different type of Data Types this required specific size memory for storage.

  • Int
  • Float
  • Complex
  • String
  • Boolean

Types of Data

Python support all these types of data and data structure to store values. where data structure required to handle different types of storage for a collection of objects.

  • Numbers
  • String
  • List
  • Set
  • Tuple
  • Dictionary

We will discuss about all these type data and it’s storage structure in further section.

Python: Identifier & Keyword

Identifier

In Python name of any variable, function, class, module, and object is called an identifier. An identifier can start with a lowercase or uppercase character or an underscore (_) followed by any number of underscores, letters, and digits. All identifiers in python are case sensitive.

Example Variable: distance=10

In the above example distance is an identifier.

Example Function:  def calculateTotal(prices)

In this above example calculateTotal is identifier.

Example class:  class User

In this above example User is identifier.

Keyword or Reserve Word

Keywords are also called as reserved words in python. So keywords cannot be used as an identifier to name variables or object or functions. Few of the keywords are listed below.

Example: if, else, elif, for, while, break, continue, pass etc.

Following is the list of reserved keywords in Python 3. You can explore each keyword examples and detail on click of each.

andexceptlambdawith
asfinallynonlocalwhile
assertfalseNoneYield
breakfornot
classfromor
continueglobalpass
defifraise
delimportreturn
elifinTrue
elseistry

Python 3 has 33 keywords while Python 2 has 30. The print has been removed from Python 2 as keyword and included as built-in function

Features of Python

Python is having all these main important features that’s what it’s most preferred language for developers.

  • Python is open source: The Python implementation is under an open-source license that makes it freely usable and distributable, even for commercial use.
  • Python is interpreted: Python is a high-level language that is interpreted by a python interpreter.
  • Python is Interactive: Python provides users a command prompt where one can interact directly with an interpreter to write programs.
  • Python is a great choice for new learners: Python is easy to learn and follows a simple syntax, so it is a good choice for beginner programmers. Python also supports a wide range of application development.
  • Python is cross-platform compatible: Python can be executed on all major platforms like Windows, Linux/Unix, OS/2, Mac, and others.
  • Python is Object-Oriented: In Python, we encapsulate data within the objects as it supports the object-oriented style of programming.
  • Python is extensible: Python has a large range of libraries and built-in functions which helps in the easy and rapid development of applications.
  • Database connectivity: Python provides interfaces required to connect to all major databases like Oracle, MySQL, PostgreSQL, and others.

About Python

Python is a general-purpose, Open source, interactive, an interpreted language. It supports support both structured and object-oriented style programming.

Python was created by Guido Rossum in 1991.

In Python development is rapid because it’s easy to learn and follows the simple syntax, it provides a wide range of built-in libraries and functions that provide help to make development fast.

Why Python?

Python is most preferred language of programmers and Data Scientist because of below reasons:

  • Easy to lean programming language
  • You can create your own games and apps
  • Effortlessly installed
  • You learn problem-solving skills
  • It will improve your critical thinking skills
  • It provides a library for data scientists for managing data, statistics, and machine learning.

Python Uses in Daily Life

Most of the famous apps on your mobile devices are created using Python language. For Example:

  • The photos you upload on Instagram
  • Your favorite movie that you watch on Netflix
  • Your favorite hip hop songs that you listen to on Spotify
  • When your family book rides on Uber.

Python Overview

Python is a general-purpose interpreted, interactive, object-oriented, scripting, and high-level programming language. Python is highly readable and mostly uses English keywords and syntactical constructions other than languages.

Python Developed by Guido van Rossum during 1985- 1990. Python source code is also available in the GNU GPL (General Public License).

Why Python?

  • Python is Interpreted: Python did not require compilation. It’s processed by an interpreter at runtime. This is similar to PHP and PERL.
  • Python is Interactive: Python is interactive because you can write a python program on Python prompt and interact with an interpreter.
  • Python is Object-Oriented: Python supports Object-Oriented features for programming that encapsulates code within objects.
  • Python is a Startup Language for Beginner’s: Python supports a wide range of applications from Simple text to WWW browsers to games. Its keyword is the most common words of English to understand a program.

Python Features

Python is the most widely used language for application development. Here are the most important features that are the reason it’s most preferred:

  • Easy-to-learn: Python has a simple structure, keywords of the English language, and a clearly defined syntax. This allows the beginner level programmer to easily pick up.
  • Easy-to-read: Python code is more clear and indentation based formatting so you can easily read it.
  • Easy-to-maintain: Python’s source code is easy-to-maintain.
  • A broad standard library: Python’s library is cross-platform compatible and very portable.
  • Interactive Mode: Python is interactive because you can write a python program on Python prompt and interact with the interpreter. It allows testing and debugging of code on the snippet.
  • Extendable: Python is extendable to add low-level modules to the interpreter. By these modules enable programmers to add to or customize their tools to be more efficient.
  • Portable: Python is portable because it runs on a variety of hardware platforms and provides the same interface for all platforms.
  • Scalable: Python provides a better structure and support for programs for application than shell scripting.
  • Databases: Python provides interfaces to support all major databases use for commercial applications.
  • GUI Programming: Python supports GUI applications that can be developed and ported to so many system calls, libraries and windows systems, Macintosh, Windows MFC, etc.

Python Characteristics

These are the most important characteristics of Python Programming Language:

  • Python supports structured and functional programming methods and also supports some features of OOP.
  • Python can be used as a scripting language or can be compiled to byte-code for developing large applications.
  • Python supports dynamic type checking and also provides very high-level dynamic data types.
  • Python supports automatic garbage collection the same as Java.
  • Python can be easily integrated with C, C++, ActiveX, CORBA, COM, and Java.

Where to use Python?

Python is a very popular language to use in developing the application, used a scripting language and nowadays is the most popular language to use in Artificial intelligence and machine learning.

  • Web Development: Django, Bottle, Pyramid, Tornado, Flask, Web2py
  • GUI Development: tkInter, pyQt, PySide, Kivy, wxPython, PygObject
  • Software Development: Buildbot, Trac, Roundup
  • System Administration: Ansible, OpenStack, Salt
  • Scientific and Numeric: Pandas, IPython, SciPy

References