Python While Loop Function Multiple Conditions [duplicate] - python

This question already has answers here:
How to test multiple variables for equality against a single value?
(31 answers)
Closed 11 months ago.
I am trying to create a function that takes two words and returns them if conditions are met. Word 1 has to be a certain number of characters, word 2 has to begin with a certain letter. I can get it to work with one condition but am confused when I have to meet two. This is what I have so far. Example below
Enter a 4 letter word: two
Enter a 4 letter word: wall
Enter a word starting with B: apple
Enter a word starting with B: boxes
['wall', 'boxes']
def twoWords(lenLet, strtLet):
input1 = str(input("Enter a word that is 4 letters long: "))
while len(input1) != 4:
input1 = str(input("Enter a word that is 4 letters long: "))
if len(input1) == 4:
break
input2 = str(input("Enter a word that begins with b: "))
while firstletter(input2) != 'b' or 'B':
input2 = str(input("Enter a word that begins with b: "))
if firstletter(input2) == 'b' or 'B':
break
return input1 and input2
print(twoWords()

You were on the right track, but you can't do firstletters(input) == 'b' or 'B'. What you could to is transform to lower case and then check against 'b' using input2[0].lower() != 'b' or you could use input2[0] not in ('b', 'B') to check for both.
A side note: You don't need to cast the result of input() to str as it already is a str. And I am not sure what you want to return but input1 and input2 does not make much sense. If you want to return both words (in a tuple) use return (input1, input2). If you just want to say that the input was correct you could use return True. The return statement will only be reached if both words meet your conditions otherwise your program will be in an infinite loop.
Please note, that I have replaced your firstletters() function with input[0] which works for the first character. If you want to check for a couple of characters you could also use str.startswith().
def twoWords(lenLet, strtLet):
# no need to cast to str, input always returns a str
input1 = input(f"Enter a word that is {lenLet} letters long: ")
while len(input1) != 4:
input1 = input(f"Try again. Enter a word that is {lenLet} letters long: ")
if len(input1) == 4:
break
input2 = input(f"Enter a word that begins with {strtLet}: ")
while input2[0].lower() != 'b':
input2 = input(f"Try again. Enter a word that begins with {strtLet}: ")
if input2[0].lower() == 'b':
break
# you will be stuck in an infinite loop as long as the conditions are not met
# only when the conditions are met you will arrive here so you can just return true
return True
print(twoWords(4, "b"))

Related

Why doesn't if any(var0) == any(var1) work?

I'm very new to programming, and more new to Python, and I'm having a hard time figuring this out. I'm trying to make a simple text hangman game, and I'm trying to validate player1's input. Here's what I have so far.
a = 0
int = ["1","2","3","4","5","6","7","8","9","0"]
while a == 0:
print("Please choose any word by typing it here:")
d = input()
d = list(d)
print(d)
if any(int) == any(d):
print("Invalid input. Please choose a non-number with no spaces or special characters.")
I can't figure why, whether I include a number in my response or not, it always meets my any(int) == any(d) condition. I know I must just be misunderstanding how any() works.
You are right: the issue is with how you use the any() function. any() returns either True or False depending on whether or not any of the elements in its iterable argument are True, in other words if they exist and are not False or an empty list or empty string or 0. This will always evaluate as True for int because int does contain an element that is True and the same will happen for d unless you do not give any input when the input() function prompts you (you hit return without typing anything). What your conditional is basically asking is the following:
if True==True
To fix this, just change your code to the following:
a = 0
int = ["1","2","3","4","5","6","7","8","9","0"]
while a == 0:
print("Please choose any word by typing it here:")
d = input()
print(d)
for letter in d:
if letter in int:
print("Invalid input. Please choose a non-number with no spaces or special characters.")
break
The easiest solution, however, does not involve the int list at all. There is actually a special method in python that can gauge whether or not a string has a number (or special character) in it, and this method, .isalpha() can be used to streamline this process even further. Here's how to implement this solution:
while True:
d = input("Please choose any word by typing it here: \n")
print(d)
if not d.isalpha():
print("Invalid input. Please choose a non-number with no spaces or special characters.")
Try this:
a = 0
ints = ["1","2","3","4","5","6","7","8","9","0"]
while a == 0:
print("Please choose any word by typing it here:")
word = input()
word_list = list(word)
if any(letter in ints for letter in word_list):
print("Invalid input. Please choose a non-number with no spaces or special characters.")

(Python): Else not executing in while loop?

My code loops like this:
filtered = [] #creates another empty list for the user input letters
substring1 = input("Please enter the first letter you know: ").lower()
substring2 = input("Please enter the second letter you know - (If you don't have a second, just hit enter): ").lower()
substring3 = input("Please enter the third letter you know - (If you don't have a third, just hit enter): ").lower()
substring4 = input("Please enter the fourth letter you know - (If you don't have a fourth, just hit enter): ").lower()
substring5 = input("Please enter the fifth letter you know - (If you don't have a fifth, just hit enter): ").lower()
# adds up the length of characters from each input of the 5 user input lines
length_of_all = len(substring1) + len(substring2) + len(substring3) + len(substring4) + len(substring5)
def while_do_stuffs():
while length_of_all <= 5: # while loop to check if length of all is 5 or less
break
else:
print("Too many characters! Total of all 5 lines must be less than or equal to 5!")
for string in five_letter_words:
# this next line is basically saying look for all strings in the latter 5 (or less) user inputs, and search them against the 5 letter word list
if substring1 in string and substring2 in string and substring3 in string and substring4 in string and substring5 in string:
filtered.append(string) # modify the word list to *only* include words that contain the matching letters from the (up to) 5 inputs.
print(filtered) #print final output of 5 letter words matching the letters provided in the user input
I'm basically trying to make it execute the last 5 lines of code if the while statement is true, otherwise print the message after else and try again.
What am I doing wrong here? I'm sure it's something really simple but I'm too much of a beginner here to figure it out.
You re using while loop and function in wrong way.
Add your first input functions inside the while loop, then check the length of the string with if else. If the condition is True, break from the loop and execute the rest of the code. Else go back to retry with continue. With the given info I don't see any need to use a function.
filtered = [] #creates another empty list for the user input letters
while True:
substring1 = input("Please enter the first letter you know: ").lower()
substring2 = input("Please enter the second letter you know - (If you don't have a second, just hit enter): ").lower()
substring3 = input("Please enter the third letter you know - (If you don't have a third, just hit enter): ").lower()
substring4 = input("Please enter the fourth letter you know - (If you don't have a fourth, just hit enter): ").lower()
substring5 = input("Please enter the fifth letter you know - (If you don't have a fifth, just hit enter): ").lower()
# adds up the length of characters from each input of the 5 user input lines
length_of_all = len(substring1) + len(substring2) + len(substring3) + len(substring4) + len(substring5)
if length_of_all<= 5: # while loop to check if length of all is 5 or less
break
else:
print("Too many characters! Total of all 5 lines must be less than or equal to 5!")
continue
five_letter_words= "hello"
for string in five_letter_words:
# this next line is basically saying look for all strings in the latter 5 (or less) user inputs, and search them against the 5 letter word list
if substring1 in string and substring2 in string and substring3 in string and substring4 in string and substring5 in string:
filtered.append(string) # modify the word list to *only* include words that contain the matching letters from the (up to) 5 inputs.
print(filtered) #print final output of 5 letter words matching the letters provided in the user input
Also you can make a single string by concatenating substrings and check the lenght at once, instead of adding lenght of each substring individually.
length_of_all = len(substring1 +substring2 +substring3 +substring4 +substring5)

how does one check if a letter is used after input?

I am supposed to write a program that asks the user to enter a word with 5 letters and then check whether the third letter is e or not.
input('Enter word with 5 letters:'
if [2] == e:
print("the third letter is e")
but nothing happens after I input a word with 5 letters.
Corrected code should be like this:
word = input('Enter word with 5 letters: ')
if word[2] == 'e':
print("the third letter is e")
Try this,
user_input = input('Enter word with 5 letters:')
if user_input[2] == 'e':
print("the third letter is e")
You need to save the value, in this case the input, into a variable and then access its letters with [].
userInput = input('Enter word with 5 letters: ')
if userInput[2] == 'e':
print("the third letter is e")
You always have to save values, information and actions into variables if you want to use or modify them further on.
In Python you can read strings like arrays.
For example:
myString = "abcdef"
print(myString[3])
Your result will be d
So what you have to do is
1st take the input and save it to a variable like this
string_input = input()
2nd check if the third letter is 'e' or not
if(string_input[2]=='e'):
print("Third letter is e")
Note: string[] returns char value

Why does my list get assigned the value of "none" when using a reverse operations?

I am new to python and I am trying to create a program the will tell a user if the word they enter is a palindrome. When I execute my code, it outputs the following:
Please enter a word. I will tell you if that word is a palindrome or not: hannah
Please enter a word. I will tell you if that word is a palindrome or not: hannah
This word is not a palindrome
None['n', 'a', 'h']
Process finished with exit code 0
Im not sure why the list within cal_tableRev is saving as "none". Any ideas on how I might fix this would be a great help!
user_input = input("Please enter a word. I will tell you if that word is a palindrome or not: ").lower()
cal_table1 = []
cal_table2 = []
for letter in user_input:
cal_table1.append(letter)
inputSize = len(cal_table1)
Calsize = inputSize / 2
if inputSize % 2 != 0:
print("The word has an odd number of letters and, therefore, it is not a palindrome. Please enter a new word")
for letters in cal_table1[0:int(Calsize)]:
cal_table2.append(letters)
cal_tableRev = str(cal_table2.reverse())
frontHalf = str(cal_tableRev)
backHalf = str(cal_table2)
calulated_word = str(frontHalf) + str(backHalf)
if user_input == calulated_word:
print("This word is a palindrome")
else:
print("This word is not a palindrome")
print(calulated_word)
The function reverse() reverses a given list but returns the value None which you then assigned to cal_tableRev
try:
cal_tableRev = copy.deepcopy(cal_table2)
cal_tableRev.reverse() #reversing without assigning the None value
cal_tableRev=str(cal_tableRev)
It looks like you are doing a lot of work python can make easier for you. Take a look at these commands I ran in a python console:
>>> word='tenet'
>>> backwards=''.join(reversed(word))
>>> word == backwards
True
>>> word='pizza'
>>> backwards=''.join(reversed(word))
>>> word == backwards
False
>>> word
'pizza'
>>> backwards
'azzip'

My append command doesn't work python

Here is my code:
letters = ['a','b','c']
print("here are the letters you already searched",letters)
letter = input("please enter a letter")
print(letter)
letters = letters.append(letter)
It won't append it to the list. I also tried this:
letters = ['a','b','c']
print("here are the letters you already searched",letters)
letter = input("please enter a letter")
print(letter)
letters.append(letter)
Your first example won't work because you're using letters = letters.append which with = is trying to reassign the letters variable, your second example is the correct one, but...
...what you might be looking for is a loop so you can continuously enter letters, while True: is one way of creating a loop:
letters = ['a','b','c']
while True:
print("here are the letters you already searched",letters)
letter = input("please enter a letter: ")
letters.append(letter)
to have an option to break out of the loop use break
letters = ['a','b','c']
while True:
print("here are the letters you already searched",letters)
print("type '_done_' to finish")
letter = input("please enter a letter: ")
if letter == "_done_":
break
letters.append(letter)
Use raw_input (with your second example) instead:
letter = raw_input("please enter a letter")
letters.append(letter)
You were probably entering a letter like d when asked for input when it actually should have been "d" (which will append properly). raw_input will always convert your letter to a string, so you may enter it like d. Please read over the difference:
input() interprets and evaluates the input which means that if the user enters an integer, an integer will be returned, if user enters string, string is returned.
raw_input() takes exactly what the user typed and passes it back as a string. It doesn’t interpret the user input. Even an integer value of 10 is entered or a list is entered its type will be of string only.
Source

Categories