Python, list, index - python

I'm trying to write a small program for my python course(teaching myself), kinda like a dictionary using lists. One list has a phrase/word in it and the other list has the meaning of the phrase/word. Through user input the user can type the word they are searching for and the words meaning would be shown. I'm having trouble trying to get the meaning to be shown. My code is below: "aldo" is my first input(word), "my name" is my second input(meaning)
word = []
meaning = []
user_word = input("Enter word: ")
user_meaning = input("Enter Meaning: ")
print(word)
print(meaning)
word = word + [user_word]
meaning = meaning + [user_meaning]
user_search = input("What word/phrase would you like to search: ")
search_index = word.index(user_search)
print(user_search + meaning.index(search_index))

There are a few bugs/issues in your code.
Printing empty lists, not sure if this is intended as a check for debugging but you are printing the lists before appending values to them, so they will always be empty. So I'm assuming you want to print the user's input here; if not then first append the values and then print the lists.
Use list.append(item) instead of list = list + [item]
meaning.index(search_index) should be meaning[search_index] as list.index(item) returns index value for the first occurrence of that item in the list and not the value itself.
Lastly, not very important but more of a readability issue, make sure there is a space between the word and the meaning or some kind of deliminator.
Here's the code assuming the expected behaviour:
word = []
meaning = []
user_word = input("Enter word: ")
user_meaning = input("Enter Meaning: ")
print(user_word)
print(user_meaning)
word.append(user_word)
meaning.append(user_meaning)
print(word)
print(meaning)
user_search = input("What word/phrase would you like to search: ")
print(user_search)
search_index = word.index(user_search)
print(user_search, meaning[search_index])

.index() finds an index, not a value
Did you mean to use meaning[search_index]?
Also, to add to lists, using .append(value) is preferred over + [value]
user_word = input("Enter word: ")
user_meaning = input("Enter Meaning: ")
word.append(user_word.strip())
meaning.append(user_meaning)
user_search = input("What word/phrase would you like to search: ")
search_index = word.index(user_search.strip())
print(user_search + " " + meaning[search_index])

If you are trying to create dictionary, instead of list you can use dictionary to store words and meaning and later use it for searching word (for learning more about dictionary, you can look into documentation).
You can try following:
my_dictionary = {} # dictionary to store word and meaning
user_word = input("Enter word: ").lower() # .lower() for not being case sensitive
user_meaning = input("Enter Meaning: ").lower() # .lower()
# add word and meaning to dictionary
my_dictionary[user_word] = user_meaning
# search word
user_search = input("What word/phrase would you like to search: ").lower()
print("Meaning of {0} is: {1}".format(user_search, my_dictionary[user_search]))

Related

Printing individual letters in a list

I am writing a program that takes a statement or phrase from a user and converts it to an acronym.
It should look like:
Enter statement here:
> Thank god it's Friday
Acronym : TGIF
The best way I have found to accomplish this is through a list and using .split() to separate each word into its own string and am able to isolate the first letter of the first item, however when I try to modify the program for the following items by changing to print statement to:
print("Acronym :", x[0:][0])
it just ends up printing the entirety of the letters in the first item.
Here's what I have gotten so far, however it only prints the first letter of the first item...
acroPhrase = str(input("Enter a sentence or phrase : "))
acroPhrase = acroPhrase.upper()
x = acroPhrase.split(" ")
print("Acronym :", x[0][0])
Using re.sub with a callback we can try:
inp = "Peas porridge hot"
output = re.sub(r'(\S)\S*', lambda m: m.group(1).upper(), inp)
print(output) # PPH
acroPhrase = str(input("Enter a sentence or phrase : "))
acroPhrase = acroPhrase.upper()
x = acroPhrase.split(" ")
result = ''
for i in x:
word = list(i)
result+=word[0]
print(result)
The code needs to iterate through the .split result. For example, using a list comprehension:
inp = "Thank god its friday"
inp = inp.split()
first_lets = [word[0] for word in inp]

how to iterate through a string and change a character in it in python

I want to capitalize a char in a string, specifically using a for loop. Can someone show how this is done using the code below. or something simpler but still using for loop iterations
name = input("Enter name")
name_list = list(name)
for i in range(len(name_list)):
if i == name_list[3]:
name_list = name_list[3].upper
else:
name_list += i
print(name_list)
Assuming this is Python, you can it by assigning the newly uppercase letter to the list at the lowercase letter's index. For example, if we want to make every third letter upper case in the string enter name, then:
name = "enter name"
name_list = list(name)
for i in range(len(name_list)):
if i % 3 == 0:
name_list[i] = name_list[i].upper()
print(''.join(name_list))
Output:
EntEr NamE

Python - Assigning values to multidimensional list

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']]

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'

Python while loop to prompt until stop is entered

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 + ).

Categories