Skip to main content

Posts

Showing posts from May, 2018

Python Unittest

Unittest library helps you to test your program and inform you whether it is working fine. It is useful to recheck if a program is running fine when you make certain changes to any related code. Making a test file makes testing easy. All you need to do later is run this file and it will inform you if a program that you are testing is working fine with all possible inputs. Here is an example of Unitest file working on another file: CAP.PY FILE def capitalizing_text(text):     '''     Input string's first letter is capitalized.     '''     return text.cap() TEST_CAP.PY FILE #importing unitest library import unittest import cap class TestCap(unittest.TestCase): #functions in test file must start with the word 'test'     def test_one_word(self):         text = 'python' #running the program         result = cap.capitalizing_text(text) #The following line checks if the result and expected result match ...

Python Pylint Installation and Usage

🐍  Pylint scans though your python file and provides a report on how well the program is written. It will give you a detailed analysis if your program is following universal code writing rules. It will report errors as well as styling that does not adhere to universal python program writing standards. Process to install Pylint and run it on your program: Install Pylint by running 'pip instal pylint' on your Command Prompt Write a program in a file and save it on your computer Run Pylint on your file by running the following on your Commad Prompt: pylint filename.py

Python Try, Except, Else, Finally Examples

🐍  Below are some of the examples to display use of Try, Except, Else, Finally Example — Try, Except try:     for i in ['a','b','c']:         print(i**2) except TypeError:     print("Inside except. One or more of the list elements are not of type integer.") Example — Try, Except, Finally x = 5 y = 0 try:     z = x/y except ZeroDivisionError:     print("Inside Except. Denomibator cannot be 0 to execute division. Please update the denominator.") finally:     print("Inside finally.") Example — Try, Except, Else def ask():     while True:         try:             result=int(input("Enter an integer to square:"))         except ValueError:             print("Inside except. That is not an integer. Try again.")             continue         else:     ...

Python Try, Except, Else, Finally

🐍  When an error is reported by Python, you certainly don't want the code to stop abruptly. You would want some actions to be taken if an error is reported. For this, 'Try' is used in Python. 'Try' executes a code. 'Except' captures errors and carries out actions when a certain or any error is reported in the lines executed by Try. 'Else' is optional and follows Except. Lines in Else is executed if no errors are reported. 'Finally'  comes at the end and is optional too. Lines in Finally are executed irrespective of errors found or not. Example: #Runs on Jupyter Notebook while True:       try:            result = int(input("Provide an integer:"))       except:            print("That is not an integer.")           continue       else:           print(f"The integer you entered is {result}")      ...

TensorFlow Introduction

What is TensorFlow? TensorFlow is an open source library Used for numerical computation It was introduced by Google Brain Team Primarily used for machine learning and deep neural network research Nodes in TensorFlow represent operations, example addition, multiplication Tensors flow through nodes Leverages CPUs and/or GPUs Version 1.2 was recently released It is a data-flow-graph based system Scale-able across computer clusters Provides ecosystem for graph visualization, serving production models, etc. What is a Tensor? A tensor is an n-dimensional matrix. Examples: Rank 0 Tensor: 1 Rank 1 Tensor: [1,2] Rank 2 Tensor: [[1,2],[3,4]] How to install TensorFlow? Got to  https://www.tensorflow.org/install/  to install TensorFlow

Be a programmer and be fit

A programmer's job leads her/him to a sedentary lifestyle. This causes weight gain. I have been following a diet plan and exercise routine that helps me stay fit while being a programmer. DIET - THINGS I EAT Yoghurt - half a liter - morning Moth Sprouts - 200 grams - brunch Moong Dal - 1 bowl - late lunch Eggs - 4 - mid meal Spinach Tomato Juice - 1 glass - dinner Cucumbers - anytime Fruit - 1 - anytime EXERCISE Follow Lumowell 30 min exercise on YouTube - on waking up Jog/Run/Walk in breaks - 10,000 steps Install Google Fit and Healthify Apps to keep a track of your steps, calories, and to educate yourself on health.  You can follow a similar routine and stay fit while having a great career.

Python Use of — if __name__=='__main':

🐍  if __name__=='__main': is used to find if a program is run directly or is being called from another program.  if __name__=='__main' returns true if it is run directly. Under  if __name__=='__main': you can put the lines of code you want to execute if a program is run directly. Here is an example to understand the usage. We are creating two files. One will have functions. Other will call these functions. We will then run file one directly and then run file two and call functions from file one in file two. one.py #RUN ON COMMAND PROMPT: python one.py def func():     print('func() in one.py') print('in one.py') if __name__ == "__main__":     print('one.py is being run directly') else:     print('one.py has been imported') two.py #RUN ON COMMAND PROMPT: python two.py import one print('in two.py') one.func() if __name__ == "__main__":     print('two.py is being run directly') else:     print(...

Python Create Package and Call Functions in Package

🐍  Can be run in command prompt. Create a folder and add a blank __init__.py file in it. This is how a package is created. A package can have a sub-package. Add another folder inside a package and add a blank __init__.py file in it. This is how you create a subpackage. Add .py file in the package and write a function in the file. Now you can access this function by importing the function from the package in any of your program. program.py from package_one import package_program from  package_one .sub package_one  import  package_subprogram package_program .main_report() package_subprogram .sub_report() package_program.py - Save this file in package_one package/directory def main_report():     print("Hey I am function inside  package_program program  in package_one package") subpackage_program.py   - Save this file in subpackage_one sub-package/sub-directory def main_report():     print("Hey I am function inside sub package_program ...

Python Bank Account Class that Deposits and Withdraws

🐍  Can be run on Jupyter Notebook #CLASS OF BANK ACCOUNT class Account: #STORING OWNER NAME AND BALANCE DATA ON CREATION OF OBJECT     def __init__(self, owner, balance=0):         self.owner=owner         self.balance=balance #RETURNS ACCOUNT INFORMATION ON CALLING THE OBJECT     def __str__(self):         return f'Account owner   : {self.owner}\nAccount balance : {self.balance}' #FUNCTION TO DEPOSIT AMOUNT IN ACCOUNT     def deposit(self, dep_amt=0):         self.balance+=dep_amt         return f'Successfully deposited {dep_amt}. The balance now is {self.balance}' #FUNCTION TO WITHDRAW AMOUNT FROM ACCOUNT     def withdraw(self, drw_amt=0): #WORKS ONLY IF THERE IS SUFFICIENT BALANCE         if drw_amt<=self.balance:             self.balance-=drw_amt         ...

Python Class to Calculate Distance and Slope of a Line with Coordinates as Input

🐍  Can be run on Jupyter Notebook #CLASS DESIGNED TO CREATE OBJECTS THAT TAKES COORDINATES AND CALCULATES DISTANCE AND SLOPE class Line:     def __init__(self,coor1,coor2):         self.coor1=coor1         self.coor2=coor2 #FUNCTION CALCULATES DISTANCE     def distance(self):         return ((self.coor2[0]-self.coor1[0])**2+(self.coor2[1]-self.coor1[1])**2)**0.5 #FUNCTION CALCULATES SLOPE         def slope(self):         return (self.coor2[1]-self.coor1[1])/(self.coor2[0]-self.coor1[0]) #DEFINING COORDINATES coordinate1 = (3,2) coordinate2 = (8,10) #CREATING OBJECT OF LINE CLASS li = Line(coordinate1,coordinate2) #CALLING DISTANCE FUNCTION li.distance() #CALLING SLOPE FUNCTION li.slope()

Tic Tac Toe Game in Python

🐍  Can be run on Jupyter notebook #IMPORTING USEFUL LIBRARIES from IPython.display import clear_output import random #DISPLAYING THE TIC TAC TOE def display_board(board):     clear_output()     print(f' {board[7]} | {board[8]} | {board[9]} ')     print('-----------')     print(f' {board[4]} | {board[5]} | {board[6]} ')     print('-----------')     print(f' {board[1]} | {board[2]} | {board[3]} ') #GAME BEGINS def player_input():     print('NEW GAME | Press 0 to End Game') # VARIABLE TO  STORE THE SPOT PLAYER HAS CHOSEN     num=0 # VARIABLE TO   KEEP A COUNT OF SPOTS FILLED     count=0 #VARIABLE TO STORE SYMBOL OF PLAYER CURRENTLY PLAYING     xo='#' #VARIABLE TO STORE YES OR NO TO PLAY AGAIN     yn='*' #RANDOM FIRST TURN OF PLAYERS     turn=bool(random.getrandbits(1)) #RESETTING BOARD     test_board = ['#','1','2','3','4','5','6','7','8','9'] #D...