Home > Blockchain >  for loop over a list
for loop over a list

Time:10-09

I have a function ask_phone_number() defined and a for loop inside the function. I want the for loop to iterate over a list (the list contains 1 string of characters). I have an elif statement in the for loop for counting the number of characters of the string in phone_number, but its returning 1 as the count. I guess this is happening because python interpreter sees the string itself as the only item in my list. My question is how can I tell python to count the characters of the string in phone_number list and not just the item in phone_number" PLEASE SEE CODE BELOW:

def ask_phone_number(correct, phone_number):
    while correct == False:
        phone_number = [input("Enter your phone number >>> ")]
        for ch in phone_number:
            if (" 1" not in ch):
                print("Make sure to enter ' 1' and your 10 digit US or Canada phone number")
            elif (phone_number.count(ch) < 12):
                print("Your phone number is incomplete")
            else:
                correct = True
    else:
        return phone_number


if __name__ == "__main__"
   ask_phone_number(False, "")

CodePudding user response:

Some issues:

  • Your code creates phone_number as a list. Drop the square brackets.

  • Once the above is fixed, your loop takes every character in the phone number and then counts how many times that character occurs in the phone number. So that will be at least 1 (because you took that character from it), but has obviously nothing to do with the number of digits in the phone number.

  • I don't see the utility to pass correct and phone_number as argument. The goal of the function is to ask the user for the phone number, so it should not be an argument. And whether it is correct or not is up to the function to determine, not an argument.

So:

def ask_phone_number():
    while True:
        phone_number = input("Enter your phone number >>> ")
        if not phone_number.startswith(" 1"):
            print("Make sure to enter ' 1' and your 10 digit US or Canada phone number")
        elif len(phone_number) < 12:
            print("Your phone number is incomplete")
        else:
            return phone_number

CodePudding user response:

phone_number.count(ch)

counts the number of times the string ch is in the list phone_number. This is always 1. You should use

elif len(ch) < 12:
  • Related