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
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"))
I'm trying to program hangman and I run into a problem. In line 48 you see that I'm trying to copy the word that has been guessed so far. But the problem is when the program asks for the next letter. For example, if the user have guessed the letter 'h', it says h____ and the next turn I guess the letter e it says _e___ but I want it to say in this example he___.
word = 'hello'
guessed = False
guess_word = secret_word(word)
a = '____'
while guessed == False:
letter = ask_letter_from_user()
if is_the_letter_in_the_word(word, letter):
locatie_letter_in_woord = location_of_letter_in_word(word, letter)
a = replace(guess_word, locatie_letter_in_woord, letter)
print(a)
Seems like a and guess_word should actually be one variable.
You are passing guess_word to the replace function after every guessed letter, but you are never updating its value. Instead, you're updating a.
Get rid of a. Next time, give all your variables meaningful names, then you might realized that you have two variables for one purpose :-)
Instead of calling replace(guess_word, locatie_letter_in_woord, letter), simply do a = a[:locatie_letter_in_woord] + letter + a[locatie_letter_in_woord+1:]. This will prevent the previous letter from being overwritten.
Output:
wich letter do you want to try?: h
well done! you guessed the letter
youre guessed letters are: h
a: h___
wich letter do you want to try?: e
well done! you guessed the letter
youre guessed letters are: h,e
a: he__
Try this:
you can turn the word into a list and have each letter checked one by one
word = 'hello'
guessed = False
found = []
guess_word = secret_word(word)
while guessed == False:
guess= ask_letter_from_user()
if is_the_letter_in_the_word(word, letter):
print('well done! you guessed the letter')
word_as_list = list(guess_word)
indices = [i for i, letter in enumerate(word) if letter == guess]
for index in indices:
word_as_list[index] = letter
found.append(letter)
print('youre guessed letters are: ' + list_joining(found))
guess_word = "".join(word_as_list)
print(guess_word)
In line 47 in place of:
a = replace(guess_word, locatie_letter_in_woord, letter)
write
a = replace(a, locatie_letter_in_woord, letter)
wich letter do you want to try?: h
well done! you guessed the letter
youre guessed letters are: h
h___
wich letter do you want to try?: e
well done! you guessed the letter
youre guessed letters are: h,e
he__
wich letter do you want to try?:
Still, this program has a problem. When you are calling the function:
def location_of_letter_in_word(word, letter):
return word.find(letter)
Look carefully for the second l in hello; it will return the location of the first l.
I am trying to implement this code, I have a list of string, secret_word = [“the”,”blue”,”house”]
When the user pick the word, user_pick = input(“Pick the secret word: ”), if it is in the secret_word list, I will append to the new list, right_words = [] . If they want a clue for the word, It will print the number of letters of that word. Problem is that, I couldn’t get the number of letters of a specific string. For example: if the user picked : “the” correctly but ask for clue for the second word, how can I give the number of letters of the 2nd word. In this case, “blue”. Same way, if the user picked "blue" correctly and ask for clue for the 3rd one - the clue should print 5 for "house"
secret_word = ["the","blue","house"]
right_words = []
user_pick = input("Pick the secret word: ")
if user_pick in secret_word:
right_words.append(user_pick)
if secret_word not in right_words:
print("clue", "the number of letters in this word", len(right_words))
I get the 1 as a clue which is the length of the list after picking "the", but I need 4 letters for "blue" (if the user already selected "the" correctly), if the user picked, "blue" correctly, then 5 letters for "house" as a clue.
I really have no clue how I can make this code work! Kindly help please :) If anyone have any idea?
Keep a counter c that holds the number of correct guesses so far.
Then print out len(secret_word[c]).
Note that if user_pick in secret_word is probably semantically incorrect because it let's your user guess the elements of secret_word in any order.
Another version. The key is using a counter as you now know...then iterating over it. Count is by index so
while counter <=2
is actually 3 positions, 0,1,2 which matches the length of the secret_word list
secret_word = ["the","blue","house"]
right_words = []
counter = 0
while counter <=2:
user_pick = input("Pick the secret word: ")
if user_pick == secret_word[counter]:
right_words.append(user_pick)
if user_pick != secret_word[counter]:
print("clue", "the number of letters in this word:", len(secret_word[counter]))
counter -= 1
if len(right_words) == len(secret_word):
break
counter += 1
print(right_words)
Pick the secret word: the
Pick the secret word: wrong
clue the number of letters in this word: 4
Pick the secret word: blue
Pick the secret word: wrong
clue the number of letters in this word: 5
Pick the secret word: wrong
clue the number of letters in this word: 5
Pick the secret word: house
['the', 'blue', 'house']
Other note: you need to move the user input into the loop (so it repeats itself)
Try this:
import random
secret_word = ["the","blue","house"]
right_words = []
while len(secret_word) != 0: #a while loop so the user can have a few tries, the loop stops when the user guessed all of the words correctly
user_pick = input("Pick the secret word: ")
if user_pick in secret_word:
right_words.append(user_pick)
secret_word.remove(user_pick) #avoid a user picking the same word twice
else:
clue_input = input("Do you want a clue? y/n \n") #ask the user if they want a clue
if clue_input == 'y': #only runs in the case of 'y', so the user can just press enter for no
clue_word = random.choice(secret_word) #pick a random word from the secret words
print("Number of letters in a word: " + str(len(clue_word))) #print the length of that word to the user
Try the following:
secret_words = ["the", "blue", "horse"] # Yur secret words list
# Creating function that takes one parameter: word_index
def get_length_of_word(word_index):
global secret_words # Globalizing the variable
# If the following statement is difficult to understand, let me break it down for you
return len(secret_words[word_index])
'''
Lets assume word_index = 1
The statement: secret_words[word_index] will use the 1st item in our list (the list starts from 0)
In our case, the first item is 'blue' (not 'the', that is acually the 0th item)
The len() statement then takes the length of the string
Since it returns the value, you can assign it to a variable and use it later on
'''
print(get_length_of_word(1)) # Printing the length of the first word in our list ('blue').
# You could assign to a variable, with something like:
# length_of_second_word = get_length_of_word(1)
So I have this assignment where I need to get a string from the user and then store that string as a list. The program will then ask the user for an index and a letter. The letter will then be replaced in their initial word at the given index.
This is how it should work:
Enter a word: cat
Enter an index: 1
Enter a letter: o
Your new word is: cot
I can ask and store the users responses with functions correctly but I have a problem joining the list with this code:
word_list[index] = (letter)
word_string = "".join(word_list)
print (word_string)
index and letter are the variables that the user input
For some reason, the program only returns the letter variable that the user entered. How do I replace the letter they give at the index they give, then return the whole list as a string?
Entire Code:
### function that replaces letters
### at specificed indices
# function that asks user for an index
def get_index():
while True:
try:
index = int(input("Enter an index (-1 to quit): "))
if index == -1:
quit
elif index < -1:
print ("Must be higher than -1!")
except ValueError:
print ("Enter a valid index!")
return index
# function that asks user for a letter
def get_letter():
while True:
try:
letter = input("Enter a lowercase letter: ")
if letter.isupper():
print ("Must be a lower case letter")
except ValueError:
print ("Enter a valid letter!")
return letter
# ask the user for a word
my_word = input("Enter a word: ")
# variable that holds current word as a list
my_word_list = list(my_word)
# call the function get_index() and store it as a variable called index1
index1 = get_index()
# call the function get_letter() and store it as a variable called letter1
letter1 = get_letter()
# print the word they entered as a list
print (my_word_list)
# insert their letter into the list at the index they gave
my_word_list[index1] = letter1
# turn the list into a string
my_word_string = "".join(my_word_list)
# print the final string
print (my_word_string)
This should work (for Python 3)
word = input("enter a word")
letter = input("enter a letter")
index = input("enter an index")
# type conversion
word_list = list(word) # as input always returns a string, and we can't modify a string
index = int(index)
# changing the list
word_list[index] = letter
# converting back the list to string
word = "".join(word_list)
print(word)
As Joe pointed out, strings are not mutable... but lists are. Although strings act like lists sometimes, they are not. If you explicitly make your word a list of characters, then you're example works.
word = input('word: ')
index = int(input('index: '))
letter = input('letter: ')
word_list = list(word)
word_list[index] = letter
new_word = "".join(word_list)
print(new_word)
The reason you cannot replace characters directly is due to the immutability of strings. I.e. you cannot change them. So the way to replace a character at an index is to take a slice up to that index and then concatenate the character and then finally concatenate the rest of the string.
This method can be seen here:
word = "cat"
index = 1
replacement = "o"
new_word = word[:index] + replacement + word[index+1:]
#new_word --> 'cot'
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