mahnoor iqbal mahnoor iqbal - 1 year ago 108
Python Question

how do you equal a str's length to a certain number/length of digits

I was using the if not equal to code but I needed the equal to code specifically for lengths from some previous posts I have tried this code of len(pin(4)) however this somehow still doesn't work
thank you in advance

pay =input("card or cash")
if pay ==("card"):
pin = str(input("enter your pin number"))
while True:
if len(pin)!=4:
str(input("not four digit try again"))
if len(pin(4)):
print("payment cleared")
print("payment cleared")

Answer Source

There are several problems with your code, starting with the formatting. You may use essentially any form of tabbing or spacing in python, but the convention and general best practice is to use 4 spaces.

Next, the line. if pay ==("card"): is unnecessarily confusing. if pay == "card": is much clearer and functions identically.

The first big error you make is to ask for the pin outside of the loop. Since your pin = str(input("enter your pin number")) occurs outside of your while True: loop, your program will only accept input once, then will enter an infinite loop unless the else clause of len(pin)!=4 occurs.

The line str(input("not four digit try again")) makes absolutely no sense. Here, you are accepting input in a line which you surely instead meant to use the print statement instead, and on top of that you are unneccessarily converting the value entered via input into a string. A simple print("not four digits! try again.") will suffice here.

The line if len(pin(4)): should throw an error if run, as there is no builtin called pin which you should be able to call with pin(4). The correct syntax would be if len(pin) == 4:.

I made a couple changes in the code below besides those described above to help with usability. I first convert the value of pin to integer to check if the value is a number. I assume that it is not inappropriate to represent a value which must clearly be a number as an integer in your example, but if you really want it to be a string you could use regex to check if it is a number or not with the re module. Something like if re.match('[0-9]{4}', pin): would work in this case.

pay = input("card or cash")
if pay == "card":
    while True:
            pin = int(input("enter your pin number: "))
            if len(str(pin))!=4:
                print("not four digits! try again.")
                print("payment cleared")
        except ValueError:
            print('not a valid number! try again.')
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download