I want to assign word, translation, and notes to one index in the list, but I keep getting errors. I want to go increment the index each time it goes through the loop, assigning the variables to the same index. I'm new to Python so any help is appreciated. I want to be able to search for the words later so if there is a better way to do so please explain it.
num = 0
listOfWords = [[] for i in range(3)]
def WriteToFile():
word = ""
while word != "quit":
word = input(str("Enter the word: "))
if word != "quit":
listOfWords[num][num][num].append(word,translation,notes)
num += 1
else:
break
I think you're complicating yourself a bit much. You can append any number of lists to a listOfWords, and thus get the data structure you need.
Here's what I would, though I assume you define translation and notes elsewhere, I also input them:
listOfWords = []
word = ""
while word != "quit":
word = input(str("Enter the word: "))
if word != "quit":
translation = input(str("Enter the translation: "))
notes = input(str("Enter the notes: "))
listOfWords.append([word, translation, notes])
print(listOfWords)
Output:
Enter the word: Hola
Enter the translation: Hello
Enter the notes: greeting
Enter the word: Perro
Enter the translation: Dog
Enter the notes: animal
Enter the word: quit
[['Hola', 'Hello', 'greeting'], ['Perro', 'Dog', 'animal']]
I am working on an assignment where we have to ask the user for a word, and then if the word has a letter that repeats the initial letter in the word, such as: ApplesAuce (the A repeats), the program will store the word in the list and then print out the list when the user is done entering words.
I am getting this error
if word[0].lower() in word[1:].lower(): IndexError: string index out
of range
Here is my code:
wordlist = []
word = input("Please enter a hilariously long word: ")
# I said "hilariously long" to increase the likelihood of a repeat letter
while wordlist != '':
word = input("Please enter another hilariously long word: ")
if word[0].lower() in word[1:].lower():
wordlist.append(word)
word = input("Please enter another hilariously long word: ")
print("All of the words that had repeated first letters are: ")
print(wordlist)
Test for the presence of a word and break out of the while loop if it isn't there.
wordlist = []
msg = "Please enter a hilariously long word: "
# I said "hilariously long" to increase the likelihood of a repeat letter
while True:
word = input(msg)
if word:
if word[0].lower() in word[1:].lower():
wordlist.append(word)
else:
break
print("All of the words that had repeated first letters are: ")
print(wordlist)
Note also that wordlist is a list so the test while wordlist != "" will always be the case because a list is not a string
This should work.I have introduced the breaker that is quit or done will break the loop. I have also moved your first input inside which will add another if wordlist is populated.
wordlist = []
# I said "hilariously long" to increase the likelihood of a repeat letter
while 1:
word = input("Please enter {}hilariously long word: ".format('another ' if wordlist else ''))
# get out if done or quit is typed
if word in ('done','quit'):
break
if word[0].lower() in word[1:].lower():
wordlist.append(word)
print("All of the words that had repeated first letters are: ")
print(wordlist)
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.
How do I repeat the program so its asks for a another word and let it only print my sentences once?
usersentence= input("Please type in a sentence without punctuation: ")
word= input("Please enter a word you want to search for in the sentence: ")
words = usersentence.split(' ')
for (i, words) in enumerate(words):
if (words == word):
print("your word appears in position(s): ")
print(i+1)
else:
print("Sorry yout word does not seem to be here")
To repeat the code, we use loops. You can use for or while loop depending on your problem. If you wont to repeat part of your code a specific number of times, for loop is your answer. For example:
usersentence= input("Please type in a sentence without punctuation: ")
for i in range(3): # number of words you wont to search
word= input("Please enter a word you want to search for in the sentence: ")
words = usersentence.split(' ')
passed = False # Something to check if the word is found
for (i, words) in enumerate(words):
if (words == word):
print("your word appears in position(s): ")
print(i+1)
passed = True # The word has been found
if not passed:
print("Sorry yout word does not seem to be here")
I need the code to ask the user to enter a word and print them out in a sentence once stop is entered. I have the following code:
`a = input("Enter a word: ")
sentence = ()
while a != ("stop"):
sentence = sentence , a
a = input("Enter a word: ")
print (sentence)`
However I don't know how to set the variable 'Sentence' so that nothing prints at the start. How can I rectify this?
In order to get a string, you need to use raw_input() instead input() (input saves as int, double etc...).
Replace input() to raw_input().
In addition, sentence = () - saves tuple and sentence = sentence , a - adds more tuples and not a string as i think you want.
Try to explain again what you mean.
You can try the following:
a = input("Enter a word: ")
sentence = ""
while a != "stop":
sentence = sentence + " " + a
a = input("Enter a word: ")
print (sentence)
input (raw_input in python 2) will allow you to write strings without the need for quotes. Sentence has to be initialized to an empty string "", and concatenated as a string (here with a simple + ).