How do I get my code to repeat in a loop?

str = input("Enter the String")
l = len(str)
p = l-1
index = 0
while index < p:
    if str[index] == str[p]:
        index = index + 1
        p = p-1
        print("String is a Palindrome")
        break
    else:
        print("String is not a Palindrome")
        break

i need this to be able to ask the user if they would like to repeat the process or not but i cant figure it out because every time i try it only repeats the string "string is not a palindrome"

Upvotes: 0

Views: 111

Answers (2)

schetefan24
schetefan24

Reputation: 126

If you want your code to be able to repeat any task, you need to wrap it into a loop. Also you shouldn't use str as a name for a variable, because that name is used in python to create a new string.

one possible solution would be

repeat = True

while repeat:
    # your code
    
    repeat = input("repeat? (y for yes, everything else is tretaed as no)\n") == "y"

Further, I want to point out, that your code is not doing what you expect. A palindrome is defined as a String which reads backwards the same as forwards. In your code, you are actually just testing whether the first and last character are the same. In the if branch, the problem is not solved. The positive result can only be given at the end of the loop. Also, you don't cover the empty string (no output at all), which I would consider as a palindrome. some cases you could test:

  • ada -> correct positive
  • asd -> correct negative
  • asda -> false positive
  • "" -> nothing at all -a[arbitray string]a -> positive?

A correct implementation of the palindrome check would be something like this:

user_input = input("Enter the String\n")
    
    isPalindrome = True
    for i in range(len(user_input)//2):       # check till center from both ends
        if user_input[i] != user_input[-i-1]: # index -1 is last character
            isPalindrome = False
            break
    
    if isPalindrome:
        print("String is a Palindrome")
    else:
        print("String is not a Palindrome")

Upvotes: 0

ppwater
ppwater

Reputation: 2277

Are you looking for this:

while True:
    user_input = input("Enter the String")
    l = len(user_input)
    p = l-1
    index = 0
    while index < p:
        if user_input[index] == user_input[p]:
            index = index + 1
            p = p-1
            print("String is a Palindrome")
            break
        else:
            print("String is not a Palindrome")
            break
    gonext = input("continue?(no to exit) ")
    if gonext == "no":
        break
    elif gonext == "yes":
        continue

add a input and if statement to ask the user, and while True to repeat.

and str is a built-in from Python, so don't use it as variable name.

Upvotes: 1

Related Questions