Python Forum
Forcing input from pre-defined list.
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Forcing input from pre-defined list.
#10
For newbie Smile

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.
Reply


Messages In This Thread
Forcing input from pre-defined list. - by scotty501 - Jun-17-2019, 12:46 PM
RE: Forcing input from pre-defined list. - by perfringo - Jun-18-2019, 01:07 PM

Possibly Related Threads…
Thread Author Replies Views Last Post
  Forcing matplotlib to NOT use scientific notation when graphing sawtooth500 4 436 Mar-25-2024, 03:00 AM
Last Post: sawtooth500
  difference between forms of input a list to function akbarza 6 1,108 Feb-21-2024, 08:02 PM
Last Post: bterwijn
  user input values into list of lists tauros73 3 1,102 Dec-29-2022, 05:54 PM
Last Post: deanhystad
  User input/picking from a list AnunnakiKungFu 2 2,361 Feb-27-2021, 12:10 AM
Last Post: BashBedlam
  Group List Elements according to the Input with the order of binary combination quest_ 19 6,589 Jan-28-2021, 03:36 AM
Last Post: bowlofred
  user input for multi-dimentional list without a prior iteration using input() Parshaw 6 2,834 Sep-22-2020, 04:46 PM
Last Post: Parshaw
  I need advise with developing a brute forcing script fatjuicypython 11 5,165 Aug-21-2020, 09:20 PM
Last Post: Marbelous
  Function to return list of all the INDEX values of a defined ndarray? pjfarley3 2 2,001 Jul-10-2020, 04:51 AM
Last Post: pjfarley3
  taking input doesnt print as list bntayfur 2 2,151 Jun-04-2020, 02:48 AM
Last Post: bntayfur
  python library not defined in user defined function johnEmScott 2 3,909 May-30-2020, 04:14 AM
Last Post: DT2000

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020