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)
Related
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"))
So I was struggling with a question on how to ask for looped inputs. So when the user enters say 5 then the program will ask the user to enter the data 5 separate times. As I was looking through I found a program that solved that and I've tweaked it to suit my question and this is what I've gotten so far:
def doSomething():
x = int(input ("Enter how many words?\n"))
for count in range (x):
word1 = input ("Enter word1:\n")
doSomething()
This part of the program solves my initial problem of asking the user for their input as many times as they have stated, but my problem is how do I change the program so that when the user enters for x = 5 the then the program will ask the user to input Enter Word 1 and after the user enters the word the program asks for word 2 Enter Word 2 and so on until its asks for the amount of words the user asked for. So to be direct how do I change Enter Word 1 to Enter Word 2 and Enter Word 3 as the program loops the amount of times chosen by the user.
You can just get the number printed each time:
def doSomething():
x = int(input ("Enter how many words?\n"))
for count in range (x):
word1 = input (f"Enter word{count+1}:\n")
btw You need python 3.6 or higher for this.
You can use the formatting of strings or concatenation.
In the loop where you ask for input you can do any of the following
input("Enter word " + (count+1) + ":\n") - Using string concatenation
input("Enter word {0}:\n".format(count+1)) - Using .format() strings
input(f"Enter word {count+1}:\n") - Utilizing f-strings.
FYI, I'm adding 1 to each count because the range function starts from 0 and ends at n-1. Adding one will allow a range from 1 through n.
You should look up concatenation. Along with that take a look at f strings. These are very efficient ways of concatination
for count in range(1,x+1):
word1 = input (f"Enter word{count}:\n")
We can use an f string to achieve the required formatting.
def doSomething():
x = int(input ("Enter how many words?\n"))
for count in range (1, x+1): # count starts from 1 and goes till x
word = input (f"Enter word{count}:\n")
You can use a loop like this. Also, make sure to check that the first number the user inputs is actually a number.
while True:
try:
number_of_words = int(input('Enter the number of words: '))
break
except ValueError:
print('You must enter a number')
words = []
for word in range(number_of_words):
words.append(input(f'Enter word {word + 1}: '))
print(words)
You should use a list variable rather than five variables with separate names.
word = []
for count in range (x):
word[count] = input (f"Enter word[{count}]: ")
Now, word will contain someting like
['first', 'second', 'third', 'fourth', 'fifth']
Notice that the index is zero-based, so the first string 'first' is word[0] and 'second' is word[1]. You could loop over range(1, x+1) but you probably should not; to mask the "computer" numbering from the user, you can display count+1 to the user.
The design to require the user to decide ahead of time how much input to provide is unnecessary and rather cumbersome; a better design is to let them provide input into an ever-growing list until they separately indicate that they want to stop, by providing an empty input, or in a GUI by clicking a separate button.
I am beginner in python and trying to make a simple game in which the user has to guess the word/name by inputting characters of that word/name. The program will generate stars of the word length which the user has to guess.
When the user will input a character, the position of that character in stars will be changed to that character. For example, The word is my name "Vishwas", the program will generate 7 stars as the length of my name is 7, *******, when user will input i the output will be Correct *i***** like this.
Now the problem is my name has two 's' in it, the program is okay till 2 's' but when we input third 's' as input it just wastes that iteration, I want here output as "Incorrect" which I just don't know how to fix here otherwise all the code is okay.
Also, tell what function to use to let the program wait till the user inputs a character as C++ has getch function right now I have used time function.
import time
print("\t\t\t\t\t\t\tWelcome to name guessing game")
name = "shahzaib"
LengthOfWord = len(name)
stars = []
for x in range(LengthOfWord):
stars.append("*")
stars = ''.join(stars)
print(stars)
print("Enter a character")
chance = 2
y=0
LOW=LengthOfWord
while y < LOW:
if chance<0:
print("Game Over")
break
chr = input()
chr = chr.lower()
count = 0
for x in range(LengthOfWord):
if chr[0] == name[x]:
if stars[x] == name[x]:
continue
else:
stars = list(stars)
stars[x] = chr[0]
stars = ''.join(stars)
print("Correct\n",stars)
if stars == name:
print("Congratulations you won")
break
count+=1
if count == LengthOfWord:
print("Incorrect\n",chance,"Chance(s) left\n",stars)
chance -= 1
LOW=LOW+1
y+=1
time.sleep(3)
The program is pretty simple I think it should be easily understandable.
Your logic is too much complex, you don't have to use any time class to wait for user to input, in python we use input() simple. It will wait till infinity for user to input something.
This can be done simply like this:
name = 'shahzaib'
chances = 3
stars = ['*' for _ in name] # I kept it as a list so that we can replace * with char
print("\t\tWelcome to name guessing game")
# while there are chances and user hasn't guessed the whole name
while chances > 0 and '*' in stars:
user = input("\nEnter Character: ").lower()
# If correct
if user in name:
index = name.find(user) # find the first occurence of that char in name
name = name.replace(user, '.', 1) # now replace that char with some special character like '.'
stars[index] = user # replace the value in the stars list so that we can show it to the user
print("Correct\nName: " + ''.join(stars))
else:
chances -=1
print("Incorrect, {} chances left.".format(chances))
Your problem is when you have more than 1 occurrence of the same character in name. This problem arose because of your logic.
The solution as you can see is to replace the occurrence of the character with some special letter like . , :, ; etc, that will not be used in a name. This will also make the program more elegant as you will be guessing the character from left to right.
Ask me anything if you feel confused about the code.
This is what I am supposed to do:
Your friend wants to try to make a word ladder! This is a list of words where each word has a one-letter difference from the word before it. Here’s an example:
cat
cot
cog
log
Write a program to help your friend. It should do the following:
Ask your friend for an initial word.
Repeatedly ask them for an index and a letter.
You should replace the letter at the index they provided with the letter they enter.
You should then print the new word.
Stop asking for input when the user enters -1 for the index.
Here’s what should be happening behind the scenes:
You should have a function, get_index, that repeatedly asks the user for an index until they enter a valid integer that is within the acceptable range of indices for the initial string. (If they enter a number out of range, you should output invalid index.)
You should have another function, get_letter, that repeatedly asks the user for a letter until they enter exactly one lowercase letter. (If they enter more than one character, you should output Must be exactly one character!. If they enter a capital letter, you should output Character must be a lowercase letter!.)
You should store a list version of the current word in a variable. This is what you should update each time the user swaps out a new letter.
Each time you have to print the current word, print the string version of the list you are keeping in your variable.
Here’s what an example run of your program might look like:
Enter a word: cat
Enter an index (-1 to quit): 1
Enter a letter: o
cot
Enter an index (-1 to quit): 2
Enter a letter: g
cog
Enter an index (-1 to quit): 5
Invalid index
Enter an index (-1 to quit): -3
Invalid index
Enter an index (-1 to quit): 0
Enter a letter: L
Character must be a lowercase letter!
Enter a letter: l
log
Enter an index (-1 to quit): -1
This is my code right now:
word = str(input("your word: "))
print(word)
run = True
while run:
#ensure he enters a number not letter
while True:
try:
get_index = int(input("enter index: "))
break
except:
print("Character must be a lowercase letter!")
#check to see if the index is within the provided word lenght
while -1 < get_index < len(word):
#doesn't matter if he enters an uppercase letter becasue the lowermethod will turn it to lowercase
get_letter = str(input("enter letter: ")).lower()
#check to ensure he provides one letter only
while len(get_letter) == 1:
word = word[:get_index] + get_letter + word[get_index + 1 :]
print(word)
break
else:
print("Must be exactly one character!")
break
else:
#quits if the index is -1
if get_index == -1:
run = False
#if the index not -1 not in the length of the word ,prints invalid
else:
print("Invalid index")
There is something wrong with this code. It does everything right, but for some reason, CodeHS says it's wrong.
It does everything right
Umm... did you actually run your own program?
The very first time I ran it, I got this error:
File "sample.py", line 17, in <module>
while len(letter) == 1:
NameError: name 'letter' is not defined
The error happens in this code block:
get_letter = str(input("enter letter: ")).lower()
#check to ensure he provides one letter only
while len(letter) == 1:
You're saving the input as get_letter, but then you're checking len(letter), which is an unknown variable.
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