0

I'm a newbie in coding and Python in general and would like to know how to make my code loop itself when a user enters an invalid input. My code currently looks like this (and yes it is a simple calculator based on what I learned in the past few hours. Criticism is welcome):

from string import ascii_letters


class simplecalc:
    print('This is only a simple calculator! Enter two numbers pls!')
    num_1 = input('Enter no.1: ')
    num_2 = input('Enter no.2: ')
    operator = input('What operation do you want to do?: ')
    
    if operator == '+':
        calc_result = float(num_1) + float(num_2)
        print(calc_result)
    elif operator == '-':
        calc_result = float(num_1) - float(num_2)
        print(calc_result)
    elif operator == '/':
        calc_result = float(num_1) / float(num_2)
        print(calc_result)
    elif operator == '*':
        calc_result = float(num_1) * float(num_2)
        print(calc_result)
    else:
        print('WrongInput')

Thanks for those who will answer!

Barmar
  • 741,623
  • 53
  • 500
  • 612
crumby
  • 1
  • https://www.w3schools.com/python/python_while_loops.asp – Andrew Ryan Oct 19 '22 at 15:57
  • Welcome to stack overflow! I will say, this is very clean, clear, and concise code for just starting out, so well done! The only change I might suggest to save some repetitive typing is to convert to float when you first take the input (unless you have a reason not to do so later in the code) `num_1 = input('Enter no.1: ')` -> `num_1 = float(input('Enter no.1: '))` – G. Anderson Oct 19 '22 at 16:01
  • 1
    Thank you! Didn't know you could actually do that in Python. Thank you for the suggestion! – crumby Oct 19 '22 at 16:08

0 Answers0