-2

I wrote the code to store history results using python, This code works correctly. but I want to display history the same as the below picture. in this program only shows the output values for history. But I need the entire process of the calculation history not only the final output value. please help me.

Question image Please see the Question

Please look at this image I want to make it as the Expected output.

last_calculation = []
while True:
  print("Select operation.")
  print("1.Add      : + ")
  print("2.Subtract : - ")
  print("3.Multiply : * ")
  print("4.Divide   : / ")
  print("5.Power    : ^ ")
  print("6.Remainder: % ")
  print("7.Terminate: # ")
  print("8.Reset    : $ ")
  print("8.History  : ? ")
  
  def add(x,y):
      return x+y

  def substract(x,y):
      return x-y

  def multiply(x,y):
      return x*y

  def divide(x,y):
      return x/y

  def power(x,y):
      return x**y

  def remainder(x,y):
      return x%y

  def history():
    global last_calculation
    if last_calculation == []:
        print("No past calculations to show")
    else:
        for i in last_calculation:
            print(i)  #for single line

  
 
  # take input from the user
  choice = input("Enter choice(+,-,*,/,^,%,#,$,?): ")
  print(choice)
  if choice == "#":
    #program ends here
    print("Done. Terminating")
    exit()
  if choice == "$":
    continue

  if choice=='?':
   history()
   continue

  try:
    a=input("Enter first number: ")
    print(a)
    if a == "#":
      #program ends here
      print("Done. Terminating")
      exit()
    a=float(a)
        
    b=input("Enter second number: ")
    print(b)
    if b == "#":
      #program ends here
      print("Done. Terminating")
      exit()
    b=float(b)
        

  except ValueError:
   continue



  if choice == "+":
      result = add(a, b)
      last_calculation.append(result)
      print(a, '+', b, '=', add(a,b))
      

  elif choice == "-":
      result = substract(a, b)
      last_calculation.append(result)
      print(a, "-", b, "=", substract(a,b))

  elif choice == "*":
      result = multiply(a, b)
      last_calculation.append(result)
      print(a, "*", b, "=", multiply(a,b))

  elif choice == "/":
      if b == 0.0:
          last_calculation.append(result)
          print("float division by zero")
          print(a, "/", b, "=" " None")
      else:
          result =  divide(a, b)
          last_calculation.append(result)
          print(a, "/", b, "=", divide(a,b)) 
       
  elif choice == '^':
      result = power(a, b)
      last_calculation.append(result)
      print(a, "^", b, "=", power(a,b))

  elif choice == "%":
      result = remainder(a, b)
      last_calculation.append(result)
      print(a, "%", b, "=", remainder(a,b))

  else :
      print("Unrecognized operation")
favthor
  • 1
  • 1

1 Answers1

0

I have a few small notes about how you could improve the readability of your code, as well as the root cause of your issue. There are a couple parts of your code that work, but are slightly more difficult to read than they need to be.

  1. I'm not sure what the point is in having separate functions for each operation. Since they're all one line operations and are all only called in one other place in the code, you could simply put the body of your functions now into the place where they are called.

  2. Rather than using long if-elif-else structures, you could use a match-case statement. (they're called switch-case statements in other languages. See this post.

  3. Using While True is generally considered bad practice. It's more readable and for more involved projects more maintainable to have an exit condition in your while loop definition

The cause of your problem is that in your code, last_calculation is only being append-ed with the result of your calculation, not the actual string that you are displaying. See the altered code below:

last_calculation = []
while True:
  print("Select operation.")
  print("1.Add      : + ")
  print("2.Subtract : - ")
  print("3.Multiply : * ")
  print("4.Divide   : / ")
  print("5.Power    : ^ ")
  print("6.Remainder: % ")
  print("7.Terminate: # ")
  print("8.Reset    : $ ")
  print("8.History  : ? ")
  
  def add(x,y):
      return x+y

  def substract(x,y):
      return x-y

  def multiply(x,y):
      return x*y

  def divide(x,y):
      return x/y

  def power(x,y):
      return x**y

  def remainder(x,y):
      return x%y

  def history():
    global last_calculation
    if last_calculation == []:
        print("No past calculations to show")
    else:
        for i in last_calculation:
            print(i)  #for single line

  
 
  # take input from the user
  choice = input("Enter choice(+,-,*,/,^,%,#,$,?): ")
  print(choice)
  if choice == "#":
    #program ends here
    print("Done. Terminating")
    exit()
  if choice == "$":
    continue

  if choice=='?':
   history()
   continue

  try:
    a=input("Enter first number: ")
    print(a)
    if a == "#":
      #program ends here
      print("Done. Terminating")
      exit()
    a=float(a)
        
    b=input("Enter second number: ")
    print(b)
    if b == "#":
      #program ends here
      print("Done. Terminating")
      exit()
    b=float(b)
        

  except ValueError:
   continue



  if choice == "+":
      resultStr = a + '+' + b + '=' + add(a,b)
      last_calculation.append(resultStr)
      print(resultStr)
      

  elif choice == "-":
      resultStr = a + '-' + b + '=' + substract(a,b)
      last_calculation.append(resultStr)
      print(resultStr)

  elif choice == "*":
      resultStr = a + '*' + b + '=' + multiply(a,b)
      last_calculation.append(resultStr)
      print(resultStr)

  elif choice == "/":
      if b == 0.0:
          resultStr = a + '/' + b + '=' + 'none'
          last_calculation.append(resultStr)
          print(resultStr)
      else:
          resultStr = a + '/' + b + '=' + divide(a,b)
          last_calculation.append(resultStr)
          print(resultStr)
       
  elif choice == '^':
      resultStr = a + '^' + b + '=' + power(a,b)
      last_calculation.append(resultStr)
      print(resultStr)


  elif choice == "%":
      resultStr = a + '%' + b + '=' + remainder(a,b)
      last_calculation.append(resultStr)
      print(resultStr)

  else :
      print("Unrecognized operation")

And with the alterations I suggested:


last_calculation = []
choice = "Doesn't matter what I put here"
while choice != "#":
  print("Select operation.")
  print("1.Add      : + ")
  print("2.Subtract : - ")
  print("3.Multiply : * ")
  print("4.Divide   : / ")
  print("5.Power    : ^ ")
  print("6.Remainder: % ")
  print("7.Terminate: # ")
  print("8.Reset    : $ ")
  print("8.History  : ? ")
  
  def history():
    global last_calculation
    if last_calculation == []:
        print("No past calculations to show")
    else:
        for i in last_calculation:
            print(i)  #for single line

  
 
  # take input from the user
  choice = input("Enter choice(+,-,*,/,^,%,#,$,?): ")
  print(choice)
  match choice:
    case "#":
        #program ends here
        print("Done. Terminating")
        continue
    case "$":
        continue

    case '?':
        history()
        continue
    
    case _:
        try:
            a=input("Enter first number: ")
            print(a)
            if a == "#":
                #program ends here
                print("Done. Terminating")
                continue
                a=float(a)
                
            b=input("Enter second number: ")
            print(b)
            if b == "#":
                #program ends here
                print("Done. Terminating")
                continue
            b=float(b)
        except ValueError:
            continue
    

        match choice:

            case  "+":
                resultStr = a + '+' + b + '=' + (a+b)
                last_calculation.append(resultStr)
                print(resultStr)
                
            case "-":
                resultStr = a + '-' + b + '=' + (a-b)
                last_calculation.append(resultStr)
                print(resultStr)

            case "*":
                resultStr = a + '*' + b + '=' + (a*b)
                last_calculation.append(resultStr)
                print(resultStr)

            case "/":
                if b == 0.0:
                    resultStr = a + '/' + b + '=' + 'none'
                    last_calculation.append(resultStr)
                    print(resultStr)
                else:
                    resultStr = a + '/' + b + '=' + (a/b)
                    last_calculation.append(resultStr)
                    print(resultStr)
                
            case '^':
                resultStr = a + '^' + b + '=' + (a**b)
                last_calculation.append(resultStr)
                print(resultStr)


            case "%":
                resultStr = a + '%' + b + '=' + (a%b)
                last_calculation.append(resultStr)
                print(resultStr)

            case  _:
                print("Unrecognized operation")
luke
  • 465
  • 1
  • 14
  • I got your points and I will refer to those when I am practicing coding. but this code has some errors. please help me to solve this. after I input 2 numbers code has not executed correctly. error is, ***Run error*** Traceback (most recent call last): File "__tester__.python3", line 80, in resultStr = a + '+' + b + '=' + add(a,b) TypeError: unsupported operand type(s) for +: 'float' and 'str' – favthor Jul 12 '22 at 06:44
  • @favthor the type error is telling you that the add() function is being passed one float, and one string, so python can't add them together (what is 2.6 + "hi"?). See [this page](https://www.w3schools.com/python/python_casting.asp) and be sure that any variables you cast to a float are actually strings of floats (e. g. "2.6" and not "hi"), or handle the errors that casting "hi" could cause. – luke Jul 12 '22 at 13:28