Mike
Mike

Reputation: 11

control structure + Python

the following is an exercise on "Control Structures".

I am sure it can be done in many different ways and that my (incomplete) solution is far from ELEGANT.

At the moment I can include all the "cases" except when a string includes one or more consecutive dots "..." in which case it should print "Password" insted it currently print "Transaction".

please see text and code below and thanks much in advance for looking into it.

exercise: Imagine you're writing a cash register application. To make interaction easier on the user, it doesn't have separate areas for passwords, PIN numbers, or cash totals -- instead, it looks at what the cashier enters and infers whether it's their PIN number, their password, or the cash total for a transaction.

The register makes this decision with the following rules:

Write a function named interpretCashier. interpretCashier should take one parameter as input, which will always be a string initially.

If the string entered represents a PIN number, return "PIN". If the string entered represents a transaction amount, return "Transaction". If the string entered represents a password, return "Password".

code:

**symbols = ["£", "$", "%", "&", "A", "a", "b", "z", "!", "@", ".."]**
**def interpretCashier(input):
     for i in input:
       if i ==".":
         return "Transaction"
       elif input.isdigit():
        return "PIN"
       if i in symbols:
            return "Password"**
**print(interpretCashier("24.59"))
print(interpretCashier("123456"))
print(interpretCashier("my$......$$w0rd"))**
    

Upvotes: 1

Views: 146

Answers (1)

bigkeefer
bigkeefer

Reputation: 661

A few side-notes: PEP 8 likes variable names and function names to be snakecase, separated by an underscore for multiple words (although there are exceptions and so it is not enforced; also I realise your exercise gave you the name to use, to be fair).

Also, and much more important, avoid using keywords (input in your code above) as variable names, as this will cause you some very confusing issues.

The code below is one way to solve your issue:

import decimal

def interpret_cashier(string):
    if string.isdigit():
        return "PIN"
    try:
        decimal.Decimal(string)  # Try to convert into a decimal, if it succeeds return "Transaction"
        return "Transaction"
    except decimal.InvalidOperation:
        # Conversion didn't work, so string must contain other characters, so return "Password"
        return "Password"

print(interpret_cashier("24.59"))
print(interpret_cashier("123456"))
print(interpret_cashier("my$......$$w0rd"))

Upvotes: 0

Related Questions