if statement not executing in while loop - python

I have to write a program that gets multiple strings one after the other that is terminated by the sentinel DONE, and then print this list of strings right justified to the length of the biggest string. Here is my code:
user = input("Enter strings (end with DONE):\n")
totalString = ""
while True:
if user.lower() == 'done':
break
else:
totalString = totalString + user + " "
user = input("")
lst = totalString.split(" ")
max = 0
for i in range(len(lst)):
if len(lst[i]) > max:
max = len(lst[i])
for i in range(len(lst)):
print("{:>{derp}}".format(lst[i],derp=max))
The issue I'm having is that the if statement in the while loop never executes, so it just gets stuck in that loop.

NB: Assumes that code was for Python 2.x, which might not be a case.
Firstly with input(), you are expecting a numeric value and not a string.
Just changing your input() to raw_input() did the trick for me.
As pointed in the comment, maybe the OP is using Python 3.
This question on SO explains the differences in Python 2.x and 3.x wrt input() and raw_input().

As you're using cmd to run your code so the string returned by input contains a return character(\r) as well.
So when the user enters "done", input() actually returns "done\r".
A simple solution is to use str.strip here:
user = input("").strip("\r")

Related

compare user input to list of key words

I want to take user input and compare it to a list of key words through a function, if any of the words input by the user match a key word, the condition is met and breaks the loop. If none of the words match a key word, then the console asks for input again. I have been manipulating this loop and have either gotten it to continuously ask for input no matter if a key word is met or validate every word input. Any advice on how to correct it would be great appreciated.
def validated_response(user_complaint):
valid_list = user_complaint.split()
while True:
if user_complaint == "stop":
break
for valid in valid_list:
if valid.lower() not in user_complaint.lower():
print("Response not recognized, please try again")
input("Enter response: ")
continue
else:
print("response validated: ")
break
return True
This function will continue getting user input until the input matches "kwrd1", "kwrd2", or "kwrd3":
def get_input():
keywords = ['kwrd1', 'kwrd2', 'kwrd3']
user_input = None
while True:
user_input = input()
if user_input in keywords:
break
return user_input
If you are matching it against a python keyword, there is a builtin keyword module:
import keyword
def get_input():
user_input = None
while True:
user_input = input()
if keyword.iskeyword(user_input):
break
return user_input
You are always reaching the else statement if the first element in valid_list is not a substring of the user_complaint string. That means you're always breaking out of the for loop and reentering the infinite while loop. Try this instead:
def validated_response(user_complaint):
valid_list = user_complaint.split()
if user_complaint == "stop":
return
inp = input("Enter response: ")
while inp.lower() not in valid_list:
inp = input("Enter response: ")
The provided code has a number of problems. The example does also not show how the function would be called, but I assumed you'd want to call it with a text that has all the keywords you're looking for.
The first problem is you are calling input, but not storing its return value, so you're not actually collecting the user input.
Secondly, you're comparing the various parts of valid_list to the contents of user_complaint.lower(), but that means you're compare a string to the characters in another string - not what you want.
Thirdly, you're asking for new input in a single clause of a condition, inside your loop, so this will lead to messages printing repeatedly and the user having to enter new text before all the comparisons are done.
Finally, you're mixing continue, break and return in a way that doesn't work. continue tells Python to move on to the next cycle of a loop, skipping any remaining code in the current cycle. break tells Python to get out of the current block (in this case the loop). return tells Python to exit the function altogether and return a provided value (or None if none is provided).
Here is an example that more or less follows the structure you set up, but with all of the problems remedied:
def validated_response(keywords):
valid_list = keywords.split()
while True:
user_input = input('Enter response: ').lower().split()
if user_input == ['stop']:
return False
for valid in valid_list:
if valid.lower() in user_input:
print('response validated: ')
return True
print('Response not recognized, please try again')
print(validated_response('trigger test'))

What am I doing wrong here? (Python 3) (Beginner)

I'm new to python and I'm trying to create a program that lets the user send words to the program and it will add them to a list then make the list a string and print it.
class joinString():
op_list = [] # this is what i was told to do to initialize a list
def init(self): # idk what this is used for to be honest
print("Hello")
def main(self):
string_in = "" # string input
print("Enter strings, to stop enter a '0'")
while string_in != '0': #while loop checks if string equals '0', stop
string_in = input("String: ") #asks user for inputs
joinString().op_list.append(string_in)
final_string = ''.join(joinString().op_list) # makes final string
print("Final Product: " + final_string) # prints final string
if __name__ == "__main__": #idk what a name is
test = joinString()
test.main()
# I took AP computer science A (coding in java) and scored pretty well but I
# didn't know where to go from there so I'm trying to learn java.
In your main you're using joinString() when you should be using self. A larger issue is that you're writing Java style code in Python. Here's a more Pythonic solution to your problem:
print('Type a word then hit enter. Leave blank to exit.')
words = []
while True:
word = input('Word: ')
if not word:
break
words.append(word)
print(*words)
First we print out a message telling the user how to use the program. We use the empty string to indicate that the users wants to exit.
print('Type a word then hit enter. Leave blank to exit.')
Then we create an empty list, words, to store the user's input.
words = []
Next, we enter an infinity loop (don't worry we'll break out of it later).
while True:
We ask the user to enter a word and store it in word.
word = input('Word: ')
In Python, the empty string is false. So we check if the user entered nothing.
if not word:
If they enter nothing, we break out of the infinite loop.
break
If they entered something, we add the word they entered to the end of words and loop back around.
words.append(word)
Be default, print() puts a space between each object it prints. So, we use the * operate to pass each element of words as an argument to print(). This causes each word to be printed with a space between them.
print(*words)
Hope that helps you learn Python.
Your main method should refer to the instance with self rather than instantiating another instance of joinString with joinString().
Replace:
joinString().op_list.append(string_in)
with:
self.op_list.append(string_in)
and replace:
final_string = ''.join(joinString().op_list)
with:
final_string = ''.join(self.op_list)
Also, the init method should be spelled __init__, and is used to initialize the object when it's being instantiated.
class joinString():
op_list = []
def main(self):
string_in = "" # string input
print("Enter strings, to stop enter a '0'")
while True:
string_in = input("String: ") #asks user for inputs
if string_in == '0':
break
joinString().op_list.append(string_in)
final_string = ''.join(joinString().op_list) # makes final string
print("Final Product: " + final_string) # prints final string
if __name__ == "__main__":
test = joinString()
test.main()
This code is working on my end. I changed your while condition because it was adding 0 to the final string

using raw_input in a while loop and assigning it to a variable?

is42= False
while(raw_input()):
d = _
if d == 42:
is42 = True
if not is42:
print d
for this python block of code I want to use outside of the interactive prompt mode. So I can't use _ as the last output. How do I assign raw_input to a variable? I'm doing an exercise off a site. about 5 values is the input and I'm suppose to spit some output out for each corresponding input value. What's the best way to take in this input to do that?
This appears to be very inefficient logic. Do you really need the is42 status flag as well? If not, you might want something like
stuff = raw_input()
while stuff:
if stuff != "42":
print stuff
stuff = raw_input()
Does that fix enough of your troubles?
Hi and welcome to Python!
The raw_input() function returns the input read as a string. So where you have d = _, you can replace that with d = raw_input(). A question I have for you is why you had it inside the while condition? If you wanted it to keep asking the user for a number over and over, then replace while(raw_input()): with while True:.
One more thing, raw_input() always returns a string. So if you run print '30' == 30, you'll see that a string representation of 30 is not equal to the number representation of 30. But that's not a problem! You can turn the return value of raw_input() into an integer type by replacing d = raw_input() with d = int(raw_input()).
Now there will be another problem when the user gives you an input that can't be converted to an integer, but handling that can be an exercise for you. :)
Final code:
is42= False
while True:
d = int(raw_input())
if d == 42:
is42 = True
if not is42:
print d
is42=False
while(!is42):
d = int(raw_input("Enter a number: "))
is42 = d==42
print "d = ", d
That should do it if I understand the requirements of your problem correctly.

how to check if string is palindrome of another string

I am trying to check if a string that is passed in to a function is a palindrome of the second string that is passed in. Google defines a palindrome to be a word that is the same spelled forwards or backwards.
def palindrome(strA, strB):
if (strA == strB and strA[::1] == strB):
print "true"
else:
print "false"
if __name__ == '__main__':
palindrome("sirap", "paris")
In the code above, I am attempting to check if the given string is equal to the second string both forwards and backwards yet the test i give it in main returns false. Any ideas on what im missing?
You check if 'sirap' is the same as 'paris' as well as checking if reversed 'sirap' is the same as 'paris'. You just have too many things in your if:
if strA[::-1] == strB:
print "true"
else:
print "false"
What you had would work if you passed in a palindrome as well as its reverse, the same thing. For example, palindrome("stats", "stats") would print "true", but I don't think that's what you had in mind. You will also notice that I used strA[::-1] instead of strA[::1]. That is because strA[::1] starts at the beginning and goes to the end, but you want to go backwards, so you should use -1.
You could even do it in one line:
print ("false", "true")[str[::-1] == strB]
I did a similar test using the "100 projects" to learn python (useful for learning any language)
You could do something like this, and just run the script. For this I just made some changes to the original palindrome script I wrote.
print "This will check if its a palindrome"
inputstring = raw_input("String1: ")
inputstring2 = raw_input("String2: ")
inputstring = inputstring.lower()
inputstring2 = inputstring.lower()
revstring = inputstring[::-1] #Reverses the string
if revstring == inputstring2:
print "Yes: " + revstring
else:
print "No: " + revstring

Why wont this Python code pop/delete element from a list?

Python code:
PeoplesNames = []
while len(PeoplesNames) < 3:
person = input('Enter your name: ')
PeoplesNames.append(person)
print PeoplesNames
if 'Dan' in PeoplesNames:
PeoplesNames.pop('Dan')
print PeoplesNames
From my understanding this should run through the while loop (which it does) until the list hits length of 3 (which it does) then print the list (which it does) then hit the if statement and delete dan from the list and then print the new list (which it does not)
do i need to nest the if statement or something else?
thanks
list.pop() #used to pop out the top of the stack(list) or
list.pop(index) #can be an index that needed to be pop out, but
list.remove(item) # removes the item specified
Try with the below solution
if 'Dan' in PeoplesNames:
PeoplesNames.remove('Dan')
print PeoplesNames
or - keeping EAFP in mind - you could:
PeoplesNames = [];
while len(PeoplesNames) < 3:
person = raw_input('Enter your name: ')
PeoplesNames.append(person)
print PeoplesNames
try:
PeoplesNames.remove('Dan')
except ValueError:
pass
print PeoplesNames
also note that in python 2.7 you need to use raw_input() instead of input().

Categories