Python Forum
Generate Random operator, take user input and validate the user
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Generate Random operator, take user input and validate the user
#5
Instead of using eval(), using the operator module would look a little like this:
>>> import operator as op
>>> import random
>>> rand_ops = {"+": op.add, "-": op.sub, "/": op.truediv, "*": op.mul}
>>> num_one = random.randint(0, 100)
>>> num_two = random.randint(0, 100)
>>> op_key = random.choice(list(rand_ops.keys()))
>>> op_key
'+'
>>> print(f"what's {num_one} {op_key} {num_two} = ?")
what's 37 + 1 = ?
>>> answer = rand_ops[op_key](num_one, num_two)
>>> answer
38
mapypy likes this post
Reply


Messages In This Thread
RE: Generate Random operator, take user input and validate the user - by nilamo - Feb-03-2021, 08:41 PM

Possibly Related Threads…
Thread Author Replies Views Last Post
  How to Randomly Print a Quote From a Text File When User Types a Command on Main Menu BillKochman 12 573 Apr-12-2024, 11:51 AM
Last Post: deanhystad
  run SQL without user intervention python dawid294 0 229 Jan-19-2024, 01:11 PM
Last Post: dawid294
  WHILE LOOP NOT RETURNING USER INPUT AFTER ZerroDivisionError! HELP! ayodele_martins1 7 1,046 Oct-01-2023, 07:36 PM
Last Post: ayodele_martins1
  Help on the User Interface Afia 1 534 Jul-21-2023, 07:22 PM
Last Post: snippsat
  restrict user input to numerical values MCL169 2 906 Apr-08-2023, 05:40 PM
Last Post: MCL169
  user input values into list of lists tauros73 3 1,062 Dec-29-2022, 05:54 PM
Last Post: deanhystad
Information How to take url in telegram bot user input and put it as an argument in a function? askfriends 0 1,070 Dec-25-2022, 03:00 PM
Last Post: askfriends
Question Take user input and split files using 7z in python askfriends 2 1,076 Dec-11-2022, 07:39 PM
Last Post: snippsat
  validate large json file with millions of records in batches herobpv 3 1,253 Dec-10-2022, 10:36 PM
Last Post: bowlofred
  Create SQL connection function and validate mg24 1 935 Sep-30-2022, 07:45 PM
Last Post: deanhystad

Forum Jump:

User Panel Messages

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