Wednesday, January 15, 2020

File Handling

Welcome Friends!

Being a programmer, it is important that we should be able to read and write data to a file. In today's blog, we will discuss how we can read and write to a file. 

There are various modes to open a file. For example:

  • w - to create a new file and write. If the file exists, it will overwrite it.
  • a - to append at the end of the file.
  • r - to read the file

Let's first create a new file
# Open a txt file with name as 'sample'
text_file = open('sample.txt', 'w')

for i in range(1, 10): 
    # Write to a file  
    text_file.writelines("Hello there! We are at line number {}\n".format(i))

# close the file
text_file.close()

To append the file, change the mode from "w"(write) to "a". 
# Open a txt file with name as 'sample'
text_file = open('sample.txt', 'a')

for i in range(1, 10): 
    # Write to a file  
    text_file.writelines("Hello there! We are at line number {}\n".format(i))

# close the file
text_file.close()

To read the file line by line, use the mode as "r".
# Open a txt file with name as 'sample'
text_file = open('sample.txt', 'r')

for each_line in text_file: 
    # Read to a file  
    print(each_line)

# close the file
text_file.close()


I hope you have enjoyed this. Stay tuned for more update.


Saturday, January 11, 2020

Exception Handling

Welcome Friends!

Today we are going to discuss Exception Handling. Well, sometimes our python or user don't respond to the code it is designed and result in errors or exceptions. Let's take an example to understand it better. Suppose our program expects 2 numbers and it performs addition on these numbers and gives the result. Now, if a user enters a number and a string, python will not be able to convert string to a number and will throw an error. To capture these and display a meaningful message on screen we use try and except in python.
num_1 = int(input("Enter 1st number: "))
num_2 = int(input("Enter 2nd number: "))
total = num_1 + num_2
print("Sum of two numbers are {}".format(total))

Now, if we run this we will get an error if we provide a string as an input.
Enter 1st number: 78
Enter 2nd number: u89
Traceback (most recent call last): 
    File "D:/Python_Data/new2python.py", line 3, in <module>
      num_2 = int(input("Enter 2nd number: "))
    ValueError: invalid literal for int() with base 10: 'u89'

No one would like to see this kind of messages. Let's display some meaningful message by capturing this kind of scenario.
try:
    num_1 = int(input("Enter 1st number: "))
    num_2 = int(input("Enter 2nd number: "))
    total = num_1 + num_2 
    print("Sum of two numbers are {}".format(total))
except: 
    print('Invalid number entered. Please try again')

And if we run this and make a mistake, we will see a message that the user has entered an invalid number and can retry.
Enter 1st number: 44
Enter 2nd number: r55
Invalid number entered. Please try again

Well, this can be put inside a while loop so that it will keep repeating until the user provides a valid input.

Let's take another scenario, our program will ask the user to provide two numbers and the program will divide these numbers and displays results. What if the user enters 0 (zero), in this case, we need to display a different error message. Let's try to fix it.
try:
    num_1 = int(input("Enter 1st number: "))
    num_2 = int(input("Enter 2nd number: "))
    total = num_1 / num_2 
    print("Division of two numbers are {}".format(total))
except ValueError: 
    print('Invalid number entered. Please try again')
except ZeroDivisionError: 
    print('Cannot divide by zero. Please try again')
except: 
    print('Something really went wrong')

If we run the above code, we will be able to capture the specific error message.
Enter 1st number: 43
Enter 2nd number: 0
Cannot divide by zero. Please try again

By now you must be wondering, how can we know the exception values we need to use? It's simple, just run your code without try and except and once you get the error message, it will let you know the type of message you can use to capture these kinds of scenarios.

When the code goes in production, there can be unknown errors and in that case, we don't want to see a generic error message rather we would also like to capture the exception. To capture the exception and display, let's try this one out.
try:
    num_1 = int(input("Enter 1st number: "))
    num_2 = int(input("Enter 2nd number: "))
    total = num_1 / num_2 
    print("Division of two numbers are {}".format(total))
except ValueError: 
    print('Invalid number entered. Please try again')
except Exception as e: 
    print('Something really went wrong.\nError message: {}'.format(e))

Now we know how to handle and capture the exceptions, there is one last piece remaining in this section. The final block is known as finally. so it goes like, 
   try: 
      ... 
   except: 
      ... 
   finally: 
      ... 

Like the name suggests, it will be executed irrespective if there is an error or not. In our above example, after the user has provided the numbers and after displaying, we would like to display a thank you note for taking their time to test. Let me show you how we can write it up.


try:
    num_1 = int(input("Enter 1st number: "))
    num_2 = int(input("Enter 2nd number: "))
    total = num_1 / num_2 
    print("Division of two numbers are {}".format(total))
except ValueError: 
    print('Invalid number entered.')
except ZeroDivisionError: 
    print('Cannot divide by zero.')
except Exception as e: 
    print('Something really went wrong.\nError message: {}'.format(e))
finally: 
    print('Thank you for your time. Have a good day!')

I hope you have enjoyed this. In our next post, we will discuss how to open and write to a file. Stay tuned. 

Monday, January 6, 2020

Functions

Welcome Friends!

Today we are going to discuss Functions. Functions are a set of instructions or a program that performs a specific task. Then one may ask, how is it different from what we were doing until now? Well, a function is used to segregate the tasks and avoid duplication of activity. Let's take a simple example to illustrate its use.

Assume, if I want to calculate how much money we can save at the end of 2 years. The program will ask the user for the principal amount and rate of interest and program will calculate simple interest and will display the amount and then will again ask the user again for the amount invested for the second year and will display the amount saved by end of 2nd year. A typical approach will be, 
Get the rate of interest from the user for 1st Year
Calculate Simple Interest
Calculate the Amount
Display the amount and Interest
Get the principal from the user for 2nd Year
Get the rate of interest from the user for 2nd Year
Calculate Simple Interest
Calculate the Amount
Display the amount and Interest

Let's see how a function can help us here.
Call function 1 to get user principal and rate of interest
call function 2 to calculate and display simple interest and Amount
Call function 1 to get user principal and rate of interest
call function 2 to calculate and display simple interest and Amount

function 1:
    Get the principal from user
    Get the rate of interest from the user

function 2:
    Calculate interest
    Calculate the Amount
    Display Amount and Interest
Syntax:
The function is defined using the keyword def, and it will return the value with the return keyword
   def function_name(arguments):
       do something here ...
       return value

Let's now write our program using the function.
def get_details_from_user():
    principal_amount = float(input("Enter the principal amount: "))
    rate = float(input("Enter the rate of interest: ")) 
    return principal_amount, rate
    
def calculate_and_display_simple_interest(principal_amount, rate):
    interest = principal_amount * rate * 1/100  
    amount = interest + principal_amount 
    print("Your interest on $" + str(principal_amount) + " is " + str(interest)) 
    print("Your amount at the end of year is: " + str(amount) + "\n")
    
def main(): 
    # get user details for 1st year from user  
    principal_amount, rate = get_details_from_user() 
    
    # Calculate and display the amount and simple interest  
    calculate_and_display_simple_interest(principal_amount, rate) 
    
    # get user details for 2nd year from user  
    principal_amount, rate = get_details_from_user() 
    
    # Calculate and display the amount and simple interest  
    calculate_and_display_simple_interest(principal_amount, rate)

main()

I hope you have enjoyed this. In our next post, we will discuss exception handling. Stay tuned. 

Sunday, January 5, 2020

Formatting

Welcome Friends!

Let's see more in the formatting of strings today.

There are various ways in which we can format the text being displayed using the print statement.
For example, if we want to print the price of flowers as $3.50.
item_name = "flower"
item_price = 3.5
item_name = "flower"
item_price = 3.5
print("1. Price for", item_name, "is $", item_price)
print("2. Price for " + item_name + " is $" + str(item_price))
print("3. Price for {} is ${}".format(item_name , item_price))
print(f"4. Price for {item_name} is ${item_price}")

If we run this, we will see our output as:
1. Price for flower is $ 3.5
2. Price for flower is $3.5
3. Price for flower is $3.5
4. Price for flower is $3.5

You can use whichever option you like or can remember it. The item price doesn't look quite right. We now need to round this to 2 decimal places. Let's try it out.
item_name = "flower"
item_price = 3.5
print("1. Price for", item_name, "is $", "{:.2f}".format(item_price))
print("2. Price for " + item_name + " is $" + "{:.2f}".format(item_price))
print("3. Price for {} is ${:.2f}".format(item_name, item_price))
print(f"4. Price for {item_name} is ${item_price:.2f}")

And the result for this will be:
1. Price for flower is $ 3.50
2. Price for flower is $3.50
3. Price for flower is $3.50
4. Price for flower is $3.50

Let's take another example of formatting. In this case, I will use option 3 but you can use any of the options and it will work the same way.
name = "Learning Python"
date = "05-Jan-2020"
item_name_1 = "Flowers"
item_name_2 = "Cake"
item_price_1 = 33.50
item_price_2 = 9.99
tax = .05 * (item_price_1 + item_price_2)
total = tax + item_price_1 + item_price_2
print("{:>30}: {:<25}".format("Name", name))
print("{:>30}: {:<25}".format("Purchase Date", date))
print("{:>30}: ${:>6.2f}".format(item_name_1, item_price_1))
print("{:>30}: ${:>6.2f}".format(item_name_2, item_price_2))
print("{:>30}: ${:>6.2f}".format("Tax (5%)", tax))
print("{:>30}: ${:>6.2f}".format("Total Price(including 5% tax)", total))

Let's see its output.
                         Name: Learning Python
                Purchase Date: 05-Jan-2020
                      Flowers: $ 33.50
                         Cake: $  9.99
                     Tax (5%): $  2.17
Total Price(including 5% tax): $ 45.66

I hope you have enjoyed this. In our next post, we will discuss functions. Stay tuned.