For newbie
Before you start coding you must have idea (a.k.a algorithm) how to solve problem at hand. If you don't have solution which can be expressed in spoken language there are very slim chances that you will be able to write code which delivers expected results.
Following requires 3.6 <= Python as f-strings are used.
task: 'take from user two numbers and operation and perform calculation and print it out'
Task should be broken into smaller subtasks:
- how to take user input
- how to perform calculation
- how to print result
Little thinking about taking user input makes it obvious, that numbers must be validated as well as operator (we don't want to multiply 'a' with 'b' etc).
So how do we validate? In Python it is usually done by try...except. This is called EAFP style:
Let's define that we will accept only integers. We should try to convert user input into int and in case of ValueError (user input is not convertible to int) we inform user that int must be entered. We wrap it into while True loop which will continue until value which can be converted into integer is entered (alternatively we might limit number of entrances or some specific input which cancels the loop).
Something like that:
Now we have user input validation for integers and operator and we are ready to roll:
Before you start coding you must have idea (a.k.a algorithm) how to solve problem at hand. If you don't have solution which can be expressed in spoken language there are very slim chances that you will be able to write code which delivers expected results.
Following requires 3.6 <= Python as f-strings are used.
task: 'take from user two numbers and operation and perform calculation and print it out'
Task should be broken into smaller subtasks:
- how to take user input
- how to perform calculation
- how to print result
Little thinking about taking user input makes it obvious, that numbers must be validated as well as operator (we don't want to multiply 'a' with 'b' etc).
So how do we validate? In Python it is usually done by try...except. This is called EAFP style:
Quote:EAFP
Easier to ask for forgiveness than permission. This common Python coding style assumes the existence of valid keys or attributes and catches exceptions if the assumption proves false. This clean and fast style is characterized by the presence of many try and except statements. The technique contrasts with the LBYL style common to many other languages such as C.
Let's define that we will accept only integers. We should try to convert user input into int and in case of ValueError (user input is not convertible to int) we inform user that int must be entered. We wrap it into while True loop which will continue until value which can be converted into integer is entered (alternatively we might limit number of entrances or some specific input which cancels the loop).
Something like that:
def validate(request): while True: answer = input(request) try: return int(answer) except ValueError: print(f'Expected integer but input was {answer}')Parameter 'request' is useful if we need different texts displayed for user:
validate('Enter first number: ') validate('Enter second number: ')If you prefer, you can do it as oneliner:
first, second = validate('Enter first number: '), validate('Enter second number: ')Now about validating operator. As noisefloor already showed, easiest way is to use built-in operator module with dictionary. As we already have validate function we should consider whether we try to modify it to use for operator validation as well or write standalone function. Let's try latter:
import operator ops = {'+': operator.add, '-': operator.sub, '*': operator.mul, '**': operator.pow, '/': operator.truediv} def operation(request): while True: answer = input(request) try: return ops[answer] except KeyError: print(f'Expected operator but input was {answer}')As you can see these functions are quite similar and they actually can be merged into one but I think as this is for newbie we will pass this option (you will see below why ops dictionary is outside of function)
Now we have user input validation for integers and operator and we are ready to roll:
first, second = validate('Enter first number: '), validate('Enter second number: ') op = operation(f"Enter operation (one from: {', '.join(ops.keys())}): ") # ensures that only defined operators are listed print(f'Answer is {op(first, second)}')
I'm not 'in'-sane. Indeed, I am so far 'out' of sane that you appear a tiny blip on the distant coast of sanity. Bucky Katt, Get Fuzzy
Da Bishop: There's a dead bishop on the landing. I don't know who keeps bringing them in here. ....but society is to blame.
Da Bishop: There's a dead bishop on the landing. I don't know who keeps bringing them in here. ....but society is to blame.