Tuesday, 4 January 2022

Python Simple Calculator Program With Solution

Here is an example of a simple calculator program that performs addition, subtraction, multiplication & division using Python. 

            

The first step in this program is Defining functions:

    #Calculator Program Python

#The below while loop is to avoid running the console again and again, so that the user can perform calculations as per his wish. 

stop_calc = False

def add(a,b):

  return a +b;

def sub(a,b):

  return a-b;

def mul(a,b):

  return a*b;

def div(a,b):

  return a/b; 

After defining the basic functions above, we will use the below code to run the Python calculator program.

            #Below the while loop will run till the flag becomes true so that the user can use the calculator without having to run the calculator program and again & again

while stop_calc==False:

  val1 = int(input("What is the first number? "))

  val2 = int(input("What is the second number? "))

  print("+\n-\n/\n*")

            #In the below input we will get the values from the user on what operation he wants to perform and the appropriate function will be called from the above-defined ones 

  a = input("Please enter the operation you want to perform: ")

  if a=="+":

    answer = add(val1,val2)

  if a=="-":

    answer = sub(val1,val2)

  if a=="*":

    answer = mul(val1,val2)

  if a=="/":

    answer = div(val1,val2)

#The below print statement prints the final solution 

  print (f"{val1} {a} {val2} = {answer}")

  b = input("Please choose yes or no")

  if b=="no":

    stop_calc= True


Output: 

Monday, 3 January 2022

Python Docstring

What is Python Docstring?

The Python docstring is used to document a Python module, function, class, or method, as it will help the programmers to understand what it does without reading the details of the implementation. 


Check the example code below:

def check_leap(yearstring):

#Docstring is created using 3 double quotes like below 

  """ This is a sample doc string created to explain the user that this function calculates the leap year"""

  if year % 4 == 0:

    if year % 100 == 0:

      if year % 400 == 0:

        print("It is a leap year.")

      else:

        print("It is Not a leap year.")

    else:

      print("It is a leap year.")

  else:

    print("It is not a leap year.")


So when you call the above function it will show the docstring when you hover over it.