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

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"

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.

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")

Related

How to check if list of strings entered are in alphabetical order?

I have a program which takes a series of strings from user input and should print "Yes" if the strings entered are in alphabetical order and "No" if not. The program ends by the user entering an empty input. I can do this when I specify the number of inputs it should have, eg 2:
finished = False
while not finished:
print("Please enter a string: ")
s = input()
x = input()
if len(s) != 0:
if s < x:
print("Yes")
else:
print("No")
else:
finished = True
However I can't seem to get my code to work when there is an indefinite amount of strings that can be entered. My current working method is to append all the strings to a list and perform the checks there, but I'm not sure exactly how to write the if statement to check this:
lst = []
i = range(len(lst))
finished = False
while not finished:
print("Please enter a string: ")
s = input()
lst.append(s)
if len(s) != 0:
if lst[i:] < lst[i: - 1]:
print("Yes")
else:
print("No")
else:
finished = True
Is there an easy way to achieve this without deviating too far from the intended structure above?
lst is a list of strings, slicing syntax on that will get you a list of strings back. But you want a string instead. Since you're appending to the list, the latest string appended will be present in the [-1] index, and the previous one will be present in [-2] index.
Change lst[i:] < lst[i: - 1] to lst[-2] < lst[-1]
There's still another problem though, in the first iteration lst[-2] does not exist, because there is only one string that has been inputted, to get rid of this - take one input and append it to the list before the loop starts-
print("Please enter a string: ")
s = input()
lst.append(s)
finished = False
while not finished:
# rest of your code
You can use the following to always compare the new item to the last item in the existing list. Therefore it always checks, if the next item is in order
new_input = input()
existing_list = ...
if sorted(existing_list[-1], new_input)[-1] == new_input
existing_list.append(new_input)
print("Yes")
else:
print("No")
That way, you don't have to enter the value to the list before checking
I have made some changes to your code. There is no need for two inputs and a master list. The code is as below.
Assumptions
Assumes that items in the list are separated by a single space
The difference between a capital case character and small case character is not important. If this is not true and ASCII ordering is important then remove ".lower()" from the third line.
while True:
print("Please enter a string: ")
s = input().lower() ## To avoid confusion between sorting ABb Abb and like strings
if not s: ## If nothing is entered break out of loop
break
SplitString = s.split(" ") ##Get elements separated by "single" space into list
SortedString = " ".join(sorted(SplitString)) ##Sort the list and then join into string
if s == SortedString: ##If the sorted and joined string is same as original then the string was already sorted when entered
print("Yes")
else: ## Else it was not sorted when entered
print("No")
The output is as below
Please enter a string:
AAA AAB ABA ABC
Yes
Please enter a string:
AAA AAB ABC ABA
No
Please enter a string:
aaa aab aba abc
Yes
Please enter a string:
aaa aab abc aba
No
Please enter a string:

I need advice with while loop in python

I'm using python3 on mac.
I'm currently doing a project. However, I was trying to use "while = True" to continuously use the program until a condition is met. Please, tell me what am I missing in my code. Thanks!
import json
import difflib
from difflib import get_close_matches
data = json.load(open("project1/data.json"))
word = input("Enter a word or enter 'END' to quit: ")
def keyword(word):
word = word.lower()
while type(word) == str:
if word in data:
return data[word]
elif word == 'END'.lower():
break
elif len(get_close_matches(word, data.keys())) > 0:
correction = input("Did you mean %s insted? Enter Yes of No: " % get_close_matches(word, data.keys())[0])
if correction == "Yes".lower():
return data[get_close_matches(word, data.keys())[0]]
elif correction == "No".lower():
return "This word doesn't exist. Plese enter again. "
else:
return "Please enter 'Yes' or 'No: "
else:
return "This word doesn't exist. Please enter again."
print("Thanks!")
output = (keyword(word))
if type(output) == list:
for item in output:
print(item)
else:
print(output)
I think this might be the setup you are looking for.
def keyword(word):
if word in data:
return data[word]
elif len(get_close_matches(word, data.keys())):
correction = input(f"Did you mean {get_close_matches(word, data.keys())[0]} instead? y/n: ")
if correction == 'y':
return data[get_close_matches(word, data.keys())[0]]
elif correction == 'n':
return "This word doesn't exist. Please enter again."
else:
return "Please type 'y' or 'n': "
else:
return "This word doesn't exist. Please enter again."
while True:
word = input("Enter a word: ").lower()
if word == 'end':
print("Thanks!")
break
else:
print(keyword(word))
Looking at the source code and your question, it seems like what you want to achieve is basically to continuously accept input from the user until the user enters something like 'end'. One way to go about this is to separate out the while-loop logic from the function. The overarching while-loop logic is at the bottom half of the code, where we continuously accept input from the user until the user inputs some lower or upper case variant of 'end'. If this condition is not met, we proceed to printing out the result of the function call keyword(word).
Minimal modifications were made to the original keyword() function, but here are a few changes worthy of note:
The while type(word) == str is unnecessary, since the result stored from the input() function will always be a string. In other words, the condition will always return True.
Having return statements within a while loop defeats the purpose of a loop, since the loop will only be executed once. After returning the specified value, the function will exit out of the loop. This is why we need to separate out the loop logic from the function.
Although %s works, it's a relic of C. This might be a matter of personal choice, but I find f-strings to be much more pythonic.
You are using the worng condition.
type((3,4))== list
is False. You must use
type((3,4)) == tuple

How to detect floating numbers in a string and convert them into single intenger

I'm pretty new to python and I have a task to complete, but I could not find a way to do it so I'm asking you for help. This is my task: I have to take input from user, for example:
stackoverflow1.2312312321abcd42ds43
and append:
- floating number into floatList
- "42" into evenList
- and 43 into oddList
This is what my code looks like atm:
user_input = input("Please enter the text: ")
Code:
freeText = ""
floatList = []
evenList = []
oddList = []
for i in user_input:
if i.isdigit():
i += freeText
elif i != "":
floatList.append(i)
The main idea is:
Go through the input character by character (as you did with for i in ...)
While you are going through the input, build a string containing the number you have read so far (current_number).
Also, have a boolean variable that states whether the number read so far contains a decimal dot (has_decimal_dot).
If you encounter a digit, just append it to current_number and continue looking at the next character.
If you encounter a dot, also append it to current_number and remember you encountered a dot. Then, continue looking at the next character.
If finally you encounter a character that is not a digit nor a dot, you know the number you were reading has ended.
Then, if you encountered a dot, you know it was a float, so you convert the string to a float and append it to the floatlist.
If you didn't encounter a dot, current_number must be an integer, at least if it has a length > 0. Test modulo 2 to know whether it is even or odd.
After adding the number, you have to prepare for the next one. Set current_number again to an empty string, and has_decimal_dot to False
A trick to not have to do something special for the last number in the string, make sure the string doesn't end with a digit. For example by appending a space.
#user_input = input("Please enter the text: ")
user_input = "stackoverflow1.2312312321abcd42ds43"
# in the beginning, it is easier to test if you don't have to type the input every time
# when everything is working more or less, we can try with input from the user
floatList = []
evenList = []
oddList = []
user_input += " " # add a non-digit at the end so we don't have to handle the last number differently
current_number = ""
has_decimal_dot = False
for i in user_input:
if i.isdigit():
current_number += i # append the character to the string
elif i == ".":
current_number += i
has_decimal_dot = True
else: # not a digit and not a dot
if has_decimal_dot and len(current_number) > 1: # the nunber has a dot, but is not only a dot
floatList.append(float(current_number))
elif len(current_number) > 0: # we encountered a non-digit, and the number we were building is not empty
num = int(current_number)
if num % 2 == 0:
evenList.append(num)
else:
oddList.append(num)
current_number = "" # we just handled the number, now prepare for a next one
has_decimal_dot = False

I wished to check if an input is in the string and then print the output

I intended to let the program check if the input matches with any character in a str and then print out the result, the player input and the underscores in the correct places. This is my test code so far:
astring = "apple"
bstring = "_ " * 5
print(bstring)
my_input = input("enter a letter")
for i, n in enumerate(astring):
if my_input == i:
bstring[n] = my_input
else:
i = i + 1
print(bstring)
However, only the underscores are being printed out. Can anyone help me?
In your loop, you should be checking to see if the letter at your current index of your string is the same as the letter at the current index of your input string, to do this you can use:
if i < len(my_input) and my_input[i] == n:
Also, strings in Python are immutable, and so you can't change them via index. Instead, use an array of _, so that you can change what is at a particular index. Then, at the end, join each element in your list by a space.
Lastly, there is no need to increment i, as this is done for you by your for loop:
astring='apple'
bstring=['_']*len(astring)
print(bstring)
my_input = input('enter a letter')
for i,n in enumerate(astring):
if i < len(my_input) and my_input[i] == n:
bstring[i] = n
print(' '.join(bstring))
for i,n in enumerate(astring):
'i' is the index, 'n' is the character. You have it the other way around in 'if'.
hope it will help you
astring='apple'
bstring=["_" for i in range(len(astring))]
print(bstring)
my_input=input('enter a letter')
for i,n in enumerate(astring):
if my_input==n:
bstring[i]=my_input
else:
i=i+1
print(*bstring)

Palindrome logic in python: What is wrong with this program?

def isPalindrome(word):
l = len(word)
for i in range(l/2):
if(word[i] != word[i+l-1]):
return 0
return 1
def main():
print("\n\n\tTo Check if the word is a Palindrome\n\n")
word = raw_input("Enter a word : ")
if(isPalindrome(word) == 1):
print("It is a Palindrome")
elif:
print("It is not a Palindrome")
main()
In my opinion everything is right in the program. It goes good when I enter a word which is not a palindrome but when I enter a palindrome it gives an error like this:
Enter a word : madam
Traceback (most recent call last):
File "temp.py", line 16, in <module>
File "temp.py", line 6, in isPalindrome
IndexError: string index out of range
First thing that is wrong is: elif: - if you're using else-if you should provide a condition, the fix in this case it to change it to else:
Second, the if should be: if(word[i] != word[l-i-1]): in order for the function to work (check that each letter is equal to its equivalent in the word).
Third, less critical but still important: keep the styling:
remove redundant braces
use proper naming convention (snake-case - not camel-case)
use True/False as return values instead of 1/0
use floor division // (as AChampion mentioned in the comments)
Complete code (fixed):
def is_palindrome(word):
l = len(word)
for i in range(l//2):
if word[i] != word[l-i-1]:
return False
return True
def main():
print("\n\n\tTo Check if the word is a Palindrome\n\n")
word = raw_input("Enter a word : ")
if is_palindrome(word):
print("It is a Palindrome")
else:
print("It is not a Palindrome")
if __name__ == "__main__":
main()
Your logic for checking palindrome should be:
if(word[i] != word[l-1-i]):
return 0
It's okay to do l/2 if you're on python 2 but python 3 will produce the result as a floating point value.
Your code seems to be in py3.
And you need to give a condition to the elif block. Otherwise, change it to else.
Change word[i+l-1] to word[l-i-1]:
def isPalindrome(word):
l = len(word)
for i in range(l // 2):
if(word[i] != word[l-i-1]):
return 0
return 1
The goal is to get the word[l-i-1 to count down while i is counting up; hence, you need to subtract i rather than add it.
Also, I would change the l/2 to l // 2 so that it works in Python 3 as well.
Hope that helps :-)
You should round the l/2 value
def isPalindrome(word):
l = len(word)
for i in range(round(l/2)):
if(word[i] != word[i+l-1]):
return 0
return 1
print("\n\n\tTo Check if the word is a Palindrome\n\n")
word = input("Enter a word : ")
if(isPalindrome(word) == 1):
print("It is a Palindrome")
else:
print("It is not a Palindrome")

Categories