My append command doesn't work python - 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

Related

(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 doesn't my code for CodeHS 8.3.8: Word Ladder pass the autograder?

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.

Why can't the index at which I want to replace a letter, be a variable in python?

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'

how to only allow letters to be used python statment

I'm making a Morse code program:
def main ():
morse_code = {"a":".-","b":"-...","c":"-.-.","d":"-..","e":".","f":"..-.","g":"--.","h":"....","i":"..","j":".---","k":"-.-","l":".-..",
"m":"--","n":"-.","o":"---","p":".--.","q":"--.-","r":".-.","s":"...","t":"-","u":"..-","v":"...-","w":".--","x":"-..-","y":"-.--","z":"--.."}
phrase = input("please enter your word or words: ")
for key in phrase:
print("your word or sentence translated to morse code is : ")
print(morse_code[key], end = " ")
if phrase == int or float:
print("try the input")
retry()
def retry ():
main()
retry()
main()
How do I print an error if someone enters a number?
This is what you need:-
morse_code = {"a":".-","b":"-...","c":"-.-.","d":"-..","e":".","f":"..-.","g":"--.","h":"....","i":"..","j":".---","k":"-.-","l":".-..",
"m":"--","n":"-.","o":"---","p":".--.","q":"--.-","r":".-.","s":"...","t":"-","u":"..-","v":"...-","w":".--","x":"-..-","y":"-.--","z":"--.."}
phrase = input("please enter your word or words: ")
if any(char.isdigit() for char in phrase):
print("try the input")
else:
print("your word or sentence translated to morse code is : ")
code = ' '.join(morse_code[key] for key in phrase)
print(code)
You can use str.isdigit
for key in phrase:
if not key.isdigit():
print("your word or sentence translated to morse code is : ")
print(morse_code[key], end = " ")
You can check if the input is between a and z by doing:
try:
index = ord(key.lower())
if index >= 97 and index <= 122:
# Do your thing
except TypeError:
# Wrong input
The TypeError shouldn't happen, it's just good practice to wrap code with errors handling.
Or, you can do:
if not key.isdigit():
# Key isn't between 0 and 9. Can be uppercase or a symbol, though.
if ord(key.lower()) >= 97 and ord(key.lower()) <= 122:
# Do your thing. It's pretty much the same as before but with one more step.
Your first problem you will have is that the if statement is A: after the printing out of the Morsecode version of the letter, and B: it is outside of the for loop completely.
You can rectify this by putting it in the for loop before the printing like so:
phrase = input("please enter your word or words: ")
print("your word or sentence translated to morse code is : ")
for key in phrase:
if phrase == int or float:
print("try the input")
else:
print(morse_code[key], end = " ")
However the above code still won't work, as the way you are checking if the current letter being printed out is a int or float isn't how you do it.
The easiest method is to change the codition of the if statement to if key.isdigit():
This will leave you with this final block of code:
phrase = input("please enter your word or words: ")
print("your word or sentence translated to morse code is : ")
for key in phrase:
if key.isdigit:
print("try the input")
else:
print(morse_code[key], end = " ")
This now works, however, lets say I enter abc123. The output I would get is .-
-...
-.-.
try the input
try the input
as the code is running the forloop regardless of if there are numbers in the input or not. To prevent this, you should check the input for numbers, before you have the for loop printing out the morse code.
phrase = input("please enter your word or words: ")
while not phrase.isalpha():
phrase = input("invalid input: ")
print("your word or sentence translated to morse code is : ")
for key in phrase:
print(morse_code[key], end = " ")
If you need any help, let me know!
Using isdigit() will solve your problem also use break to receive new input
morse_code = {"a":".-","b":"-...","c":"-.-.","d":"-..","e":".","f":"..-.","g":"--.","h":"....","i":"..","j":".---","k":"-.-","l":".-..",
"m":"--","n":"-.","o":"---","p":".--.","q":"--.-","r":".-.","s":"...","t":"-","u":"..-","v":"...-","w":".--","x":"-..-","y":"-.--","z":"--.."}
Morse_Parse=[]
phrase = input("please enter your word or words: ")
print("your word or sentence translated to morse code is : ")
for key in range(0,len( phrase)):
if phrase[key].isdigit():
print("you inderted an digit , Try another input")
break
else:
Morse_Parse.append(morse_code[phrase[key]]+" ")
print("Morse for your input is "Morse_Parse)
using flag will improve print task
morse_code = {"a":".-","b":"-...","c":"-.-.","d":"-..","e":".","f":"..-.","g":"--.","h":"....","i":"..","j":".---","k":"-.-","l":".-..",
"m":"--","n":"-.","o":"---","p":".--.","q":"--.-","r":".-.","s":"...","t":"-","u":"..-","v":"...-","w":".--","x":"-..-","y":"-.--","z":"--.."}
Morse_Parse=[]
phrase = input("please enter your word or words: ")
print("your word or sentence translated to morse code is : ")
flag=1
for key in range(0,len( phrase)):
if phrase[key].isdigit():
print("you inderted an digit , Try another input")
flag=0
break
else:
Morse_Parse.append(morse_code[phrase[key]]+" ")
if flag==1:
print("Morse for your input is "Morse_Parse)
how to only allow letters
How do I print an error if someone enters a number?
The second case is covered easily by checking .isdigit on each character as others mentioned. But I will cover the first case.
Start by defining a string of valid characters. Assuming your valid character set is lowercase a-z, this would be the same as string.ascii_lowercase
import string
valid_characters = string.ascii_lowercase # a-z
def char_valid(c):
'''Check if a character is valid, returns True/False'''
return c in valid_characters
def phrase_valid(phrase):
'''Check if the phrase is valid, returns True/False'''
return all(char_valid(char) for char in phrase)
while True:
user_phrase = input('Enter some characters')
if phrase_valid(user_phrase):
# If the phrase is valid, end the loop
break
else:
print('That was not a valid phrase')
# the loop continues and will ask for input again
This pattern works any time you want to keep asking for input until it is valid.

Categories