-2

I'm making a calculator on Python 3.4. The calculator will ask the user to enter a number. I want to restrict this so they can only enter a number (which I am fine about) or to press the 'C' key to clear the calculator. I seem to be getting stuck with allowing the C as well as any integer. Anyone suggest any way of going about this?

Thanks

P.Morris
  • 3
  • 1
  • 2
    What have you got so far? Maybe we can build on that, instead of creating everything from scratch – Mathias711 Apr 26 '16 at 06:59
  • Please [edit] your question and add the code you have tried. –  Apr 26 '16 at 07:00
  • 1
    Enter one digit at a time, or enter a whole number like 1337 and then press enter? Also, what to do if the user enters e.g. "42C" - valid number 42, valid command "C" or invalid? And what about decimal points? Support them or restrict input to integers? – Byte Commander Apr 26 '16 at 07:05

2 Answers2

0

You could use this code, assuming the user shall be able to enter numbers consisting of several digits like 1337, but no decimal points. Inputs being mixed of digits and "C" are invalid, "C" only gets detected if the input contains only the letter "C" and nothing else. Leading and trailing whitespaces are ignored.

def get_input():
    inp = input("Enter a number or 'C' to clear: ").strip()
    if inp.upper() == "C":
        return "C"
    if inp.isdigit():
        return int(inp)
    else 
        return None

This function will return the entered number as integer, or the string "C", or None if the input was invalid.

Byte Commander
  • 6,506
  • 6
  • 44
  • 71
-1

Assuming you're taking in the user inputs one by one:

import string
allowed = string.digits+'C'
if input in allowed:
    doSomethingWith(input)

Is this what you're looking for?

plsnoban
  • 351
  • 5
  • 17
  • Works only if the input is a single digit. It will not allow inputs such as `42`. – Byte Commander Apr 26 '16 at 07:03
  • It really depends on how he's implementing it. For this calculator I'm assuming he's reading the inputs one by one and appending to a string for display. – plsnoban Apr 26 '16 at 07:11