Syntax error python, not sure how to write the code - python

I am trying to write a code that tests a word to see if it is a palindrome or not. It is working but it prints NO in a loop before it gives the correct answer. I want it to just print the correct answer once.
I haven't really done anything, just checked the internet for some answers
x = str(input("enter the word:"))
w = ""
for i in x:
w = i + w
if x == w:
print("YES")
else:
print("NO")
It should print YES or NO once, now it prints many times before giving the correct answer.

indent the w= i + w line
x = str(input("enter the word:"))
w = ""
for i in x:
w = i + w
if (x==w):
print("YES")
else:
print("NO")

Please correct your indentation to make it possible to trouble shoot.
At first glance it appears your “if” statement is nested in side your “for” loop, thus checking for the palindrome after each letter is added.

If you put the if else inside the loop, its bound to print the result multiple times. Keep it out of the loop and it will print just once.

Welcome to the Community!
A shorter way to do this could be:`
x = str(input("enter the word:"))
if (x==x[::-1]):
print("YES")
else:
print("NO")
You may want to look into string slicing in python :)

Mark B already solved your issue but here is an additional method out of interest.
word = input("Enter word")
reverse = word[::-1]
if word == reverse:
print("Yes, plaindrome")
else:
print("No, not palindrome")

Use your for loop to create a new string ( reverse of string x ). Use conditional outside the for loop. Also, check for uppercase entry.

Related

How do I return "Yes" if all words in the sentence are lowercase?

I can currently have my code return "Yes" for each character, but I'm not sure how to make the code return just ONE Yes at the end of the code, if every word in the sentence was lowercase. Here's what I have
sentence = "hello thEre is this aLL lowercase"
sent = sentence.split(" ")
lower = False
for wd in sent:
for ch in wd:
if ch.islower():
print("Yes")
lower = True
if not ch.islower():
print("No")
lower = False
I know I cannot have print("Yes") in the loop because it will print everytime, but I don't know how to do it any other way. Thanks for any help.
Here is one way to approach the solution.
I’m intentionally not providing any explanation, because it will help your learning to research the concepts on your own. Look into:
List comprehension
The all() function
Boolean tests
Sample code:
s = ‘lower case statement’
result = all([i.islower() for i in s.split()])
print('Yes' if result else 'No')
>>> ‘Yes’
I recommend taking each part of the short code apart to discover how it’s working.
Simplified:
Personally, I don’t mind sharing this in an educational setting, because part of learning to write Python (and code in general) is learning to write it efficiently. That said, here’s a simplified solution:
print('Yes' if s.islower() else 'No')
>>> ‘Yes’
If you only care about it being all lowercase then the first time you find a capital letter you should break out of the loop. Then only print yes if lower is true outside the loop.
I'm assuming this is an exercise, so I won't give any code.
You need to have a variable "any non-lowercase word found" that is set to false before the loop and set to true if a word is found that is not lowercase. If the variable is still false after the loop you can print "yes", otherwise not.
Maybe if you have written the code to implement this you will find that it can be optimized.
You can use isLower(), just remember to remove spaces
def checkLower(string):
string = string.replace(" ","")
print(string)
for i in string:
if i.islower() == False:
return "no"
return "yes"
You can simply do this way using .islower() because The islower() methods return True if all characters in the string are lowercase, Otherwise, It returns False.
sentence = "hello thEre is this aLL lowercase"
if(sentence.isLower()):
print('Yes')
else:
print('No')
sentence = "hello there this is all lowercase"
sent = sentence.split(" ")
lower = True
for wd in sent:
for ch in wd:
if not ch.islower():
lower = False
if lower:
print("Yes")
if not lower:
print("No")
I don't have much idea about python and how it works but here is the logic i added to the code provided.
Right now you are printing "Yes" every time you find a lowercase word.
def isAllLower(sentence):
sent = sentence.split(" ")
lower = False
for wd in sent:
for ch in wd:
if ch.islower():
lower = True
if not ch.islower():
lower = False
if lower == True:
print("Yes")
elif lower == False:
print("No")
isAllLower("hello thEre is this aLL lowercase")
The simplest by far way is to compare the lowered by default sentence using the lower() function, with the initial function!
def SentenceisLower(sentence):
sentencelower = sentence.lower()
if (sentence == sentencelower):
print("Yes!")
Where there is no reply in any other outcome!

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)

String Index Out Of Range (Python) I have made bounds too

import time
password=input("What's your password?")
ans = ""
password=password.lower()
alpha = "abcdefghijklmnopqrstuvwxyz"
n = 0
a=0
starttime=time.time()
while ans !=password:
print(a)
for i in range(len(password)):
letter=alpha[n]
ans+=letter
if ans[a] != password[a]:
print(ans)
ans = ans.replace(ans[a],"")
n+=1
break
else:
a+=1
print(ans)
n=0
break
print("Password Found!")
endtime=time.time()
time=endtime-starttime
print("It took " + str(time) + " seconds!")
This is my code, sorry if i'm not posting it right (first time here). But let's digress, It seems i get an error of string index out of range
Traceback (most recent call last):
File "C:\Users\admin\Documents\Letter word cracker.py", line 15, in <module>
if ans[a] != password[a]:
IndexError: string index out of range
I was wondering how to fix this, because its been eating at my brain for days. Any help would be appreciated, thanks!
Ok, I don't know why you are trying to do this, what you are trying to do, the error is here due to this line
ans = ans.replace(ans[a],"") ---> X
what replace will do, is replace all the occurrences of a particular character from the array, while you only need to remove the last.
For example :-
If ans = "naa",
now replace will replace both 'a' while based on your logic you only want to remove the last element. because you have already matched till "na" and now in process of matching the third element.
You could probably do :-
ans = ans[:-1]
But again, this is a very very bad way to do this, because strings are immutable so you are basically creating and destroying strings every iteration.
One advice I would give is using list of characters instead of a string, it would not give a significant boost to the runtime for your program, for whatever reason you are using this.
EDIT:-
Also the for loop is unnecessary, as it is always breaking after first iteration. thanks #TigerHawk
import time
password=input("What's your password?")
ans = []
password=password.lower()
alpha = "abcdefghijklmnopqrstuvwxyz"
n = 0
a=0
starttime=time.time()
while "".join(ans) !=password:
letter=alpha[n]
ans.append(letter)
if ans[a] != password[a]:
ans.pop()
n+=1
else:
a+=1
n=0
print("Password Found!")
endtime=time.time()
time=endtime-starttime
This is a little better and more condensed version. From what I understand, you want to brute force a character string to compare it to a password.
import time
password=input("What's your password?")
password=password.lower()
alpha = "abcdefghijklmnopqrstuvwxyz"
starttime=time.time()
for letter in range(len(password)):
for index in range(len(alpha)):
if alpha[index] == password[letter]:
print "Letter",letter,"Found."
next
print "Password Found!"
endtime=time.time()
time=endtime-starttime
print "It took",time,"seconds!"
There are a few issues per the previous post, but the IndexError is happening because you are comparing each element of each list, and when one list runs out, it raises the IndexError exception. Wrap that part of the code in an if() that checks to see whether there are any more elements left over.
This will not fix the entire program, and in fact, you'll likely need a better way to do this comparison... I'm just explaining why the IndexError is happening.
if (ans[a] and password[a]):
if ans[a] != password[a]:
print(ans)
ans = ans.replace(ans[a],"")
n+=1
break
You should really go through your logic to understand why it isn't working, but there are many improvements you can make to your code. I have implemented a working version with a few improvements below.
from time import time
import string
#this will only work for a-z no whitespace, caps, numbers, etc.
pwd = raw_input("What is your password? ")
pwd = pwd.lower()
#create list of password for easier iterability
password = list(pwd)
#alphabet will have a-z lowercase
alphabet = list(string.ascii_lowercase)
#empty list to start
guess = []
#start timer
start = time()
#outer loop through password
for char in password:
#inner loop through alphabet
for letter in alphabet:
if letter == char:
guess.append(letter)
break
#print correct guess as string
end = time()
print "It took " + str(end - start) + " seconds to solve this password."
#verify correctness
print "".join(guess)
print pwd

What happens when loop gets to the end?

I am python beginner, with no previous programming knowledge. I apologize for the name of the topic, but I simply could not make a better one.
Here is what I want:
letter = "w" # search for this letter in the list bellow
listL = ["z","b","y","a","c"]
for let in listL:
if let == letter:
print "found it"
break
else:
if let == listL[-1]:
print "nope can't find it"
continue
I have a list of letters, and I want to search for a particular letter in that list.
If I find the letter, then everything is ok, and the for loop should stop.
If I do not find it, I would like the loop to stop that current iteration, and try with the next letter in the list. If not a single letter in the list has that particular letter, then it should print "nope can't find it".
The upper code works. But I was wondering if this could be wrote a bit clearly? And by clearly I do not mean "advanced", but scholar way, an-example-from-the-book way.
Thank you.
Python offers an else statement for the for loop that is executed if the loop ends without being broken:
for let in llistL:
if let == letter:
print("Found it!")
break
else:
print("nope could'nt find it")
That would be the "scholar way" for a for loop, however if you just test the presence of an element in a list, Arkady's answer is the one to follow.
How about just:
if letter in listL:
print "found it"
else:
print "nope..."
Simply use in
if let in listL:
print("Found it")
else:
print("Not found")
edit : you were faster by 30 s, congrats ;)
Your loop will keep looping until it either breaks (found it!) or the list is exhausted. You do not need to do anything special to "stop that current iteration, and try with the next letter in the list". We don't need a continue when a letter doesn't match, this will happen automatically as long as there are more letters to check.
We only want to display "nope can't find it" after we've searched through the entire list, so we don't need to check until the end. This else statement corresponds to the for loop, instead of the if in your previous code.
letter = "w" # search for this letter in the list bellow
listL = ["z","b","y","a","c"]
for let in listL:
if let == letter:
print "found it"
break #found letter stop search
else: #loop is done, didn't find matching letter in all of list
print "nope can't find it"
There is actually a for: else: construct in Python, where the else runs if the for loop doesn't break:
for let in listL:
if let == letter:
print("Found it")
break
else:
print("Not found")
Alternatively, you can use list.index, which will give the index of an item if found in a list and raise a ValueError if it isn't found:
try:
index = listL.index(letter)
except ValueError:
print("Not found")
else:
print("Found it")

Advice on python program

So i had to write a program that asks for a user input (which should be a 3 letter string) and it outputs the six permutations of the variations of the placements of the letters inside the string. However, my professor wants the output to be surrounded by curly brackets whereas mine is a list (so it is square brackets). How do i fix this? Also, how do I check if none of the letters in the input repeat so that the main program keeps asking the user to enter input and check it for error?
Thank you
The only datatype im aware of that 'natively' outputs with { } is a dictionary, which doesnt seem to apply here. I would just write a small function to output your lists in the desired fashion
>>> def curlyBracketOutput(l):
x = ''
for i in l: x += i
return '{' + x + '}'
>>> curlyBracketOutput(['a','b','c'])
'{abc}'
ok, for one thing, as everyone here has said, print '{'. other than that, you can use the following code in your script to check for repeated words,
letterlist = []
def takeInput(string):
for x in string:
if x not in letterlist:
letterlist.append(x)
else:
return 0
return 1
then as for your asking for input and checking for errors, you can do that by,
while(True): #or any other condition
string = input("Enter 3 letter string")
if len(string)!=3:
print("String size inadequate")
continue
if takeInput(string):
arraylist = permutation(string) #--call permutation method here
#then iterate the permutations and print them in {}
for x in arraylist: print("{" + x + "}")
else:
print("At least one of the letters already used")
The answer to both question is to use a loop.
Print the "{" and then loop through all the elements printing them.
But the input inside a loop and keep looping until you get what you want.
Curly brackets refers to a dict?
I think a
list(set(the_input))
should give you a list of unique letters. to check if they occur more than once
and
theinput.count(one_letter) > 1
should tell you if there is mor than one.
>>> chars = ['a','b','c']
>>> def Output(chars):
... return "{%s}" % ''.join(chars)
...
>>> print Output(chars)
{abc}
>>>
Or just do something tremendously kludgy:
print repr(YourExistingOutput).replace("[", "{").replace("]", "}")

Categories