Why can't I append something to a list? [closed] - python
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 2 years ago.
Improve this question
I am currently having a bug with my code, and I need help fixing it.
Basically, when I try and append something to a list, it only works for certain arguments.
Here is a snipet(NOT the full code):
elif sentencearray[x] == " ":
lengthlist.append(len(longestword))
wordlist.append(str(*longestword))
longestword.clear()
When I try and run my code, wordlist.append(str(*longestword)) works, but lengthlist.append(len(longestword)) doesn't. All the variables are defined. It's just that when I try and print lengthlist, it turns out empty, even though I JUST appended something in it. I'm pretty sure the lines are tabbed the same. Can somebody PLEASE explain why this is happening?
P.S if it's some stupid mistake, I'm fairly new at python, so I might make some of these mistakes here and there.
Here is the full code:
# Online Python - IDE, Editor, Compiler, Interpreter
sentence = input("enter sentence here: ")
sentencearray = list(sentence)
sentencelength = len(sentencearray)
x = 0
y = 0
counter = 0
numvowels = 0
numletters = 0
numuppercase = 0
vowels = ['a','e','i','o','u','A','E','I','O','U']
uppercaseletters = ['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']
letters = ['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', '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']
valuelist = [0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0]
knownletters = []
longestword = []
wordlist = []
lengthlist = []
knownletters.append(sentencearray[x])
for x in range(0,len(sentencearray)):
for y in range(0,10):
if sentencearray[x] == vowels[y]:
numvowels += 1
for x in range(0,len(sentencearray)):
for y in range(0,26):
if sentencearray[x] == uppercaseletters[y]:
numuppercase += 1
for x in range(0,len(sentencearray)):
for y in range(0,52):
if sentencearray[x]==letters[y]:
longestword.append(sentencearray[x])
for z in range(0,len(knownletters)):
if sentencearray[x] != knownletters[z]:
counter += 1
if counter == len(knownletters):
numletters += 1
knownletters.append(sentencearray[x])
counter = 0
elif sentencearray[x] == " ":
lengthlist.append(len(longestword))
wordlist.append(str(*longestword))
longestword.clear()
for a in range(0,len(sentencearray)):
for b in range(0,51):
if sentencearray[a] == letters[b]:
x += 1
valuelist[b] = valuelist[b] + 1
print("# of vowels:" + str(numvowels))
print("# of uppercase letters: "+ str(numuppercase))
print("# of unique letters: " + str(numletters+1))
print("# of times the most frequent letter appears: "+ str(max(valuelist)))
print(longestword)
print(len(longestword))
print(lengthlist)
print(wordlist(max(lengthlist)))
print(knownletters)
print(x)
You can also check it out at:
https://www.online-python.com/5TYKzmJO9g
I know this isn't what you asked for exactly... but there are so many Python features you're missing out on I couldn't resist putting together a 'more pythonic' example.
It's not entirely complete (I don't have your spec) and specifically it will treat numbers and special characters as 'letters', there are a number of ways you could exclude them.
vowels = ['A','E','I','O','U']
raw_sentence = input("Enter Sentence Here")
char_usage = {}
uppercase_count = 0
vowel_count =0
for char in raw_sentence:
#Take an uppercase copy of our character for later
upper_char = char.upper()
#instead of `valuelist`, we maintain a dictionary of character:occurance
if upper_char in char_usage:
char_usage[upper_char]+=1
else:
char_usage[upper_char]=1
#Instead of checking against a list, if a character == character.upper() it's upper case
if upper_char==char:
uppercase_count +=1
#use 'in' to check if a character is a vowel
if char.upper() in vowels:
vowel_count +=1
print("Number of Vowels",vowel_count)
print("Number of Uppercase Letters",uppercase_count)
#the largest value in our char_usag dictionary answers this question:
print("# times most frequently used letter appears",max(char_usage.values()))
#and the length of the dictionary answers the next:
print("Unique Letters", len(char_usage))
#use 'split' to split a string into words by white-space
sentence = raw_sentence.split() #convert string into a list of words
#Print the longest word:
print("Longest Word:", max(sentence, key=len))
Related
How to select certain characters in a string in Python?
My name is Shaun. I am 13 years old and trying to learn python. I am trying to make a program that finds vowels in an input and then prints how many vowels there are in the input the user gives. Here is the code: s = (input('Enter a string: ')) # Let the user give an input (has to be a string) Vwl = [] # Create an array where we will append the values when the program finds a vowel or several vowels for i in s: # Create a loop to check for each letter in s count_a = 0 # Create a variable to count how many vowels in a count_e = 0 # Create a variable to count how many vowels in e count_i = 0 # Create a variable to count how many vowels in i count_o = 0 # Create a variable to count how many vowels in o count_u = 0 # Create a variable to count how many vowels in u The function below is pretty long to explain, so summary of the function below is to find a vowel in s (the input) and make one of the counters, if not some or all, increase by 1. For the sake of learning, we append the vowels in the array Vwl. Then, it prints out Vwl and how many letters there are in the list by using len. if s.find("a" or "A") != -1: count_a = count_a + 1 Vwl.append('a') elif s.find("e" or "E") != -1: count_e = count_e + 1 Vwl.append("e") elif s.find("i" or "I") != -1: count_i = count_i + 1 Vwl.append("i") elif s.find("o" or "O") != -1: count_o = count_o + 1 Vwl.append("o") elif s.find("u" or "U") != -1: count_u = count_u + 1 Vwl.append("u") print(Vwl) print(f"How many vowels in the sentence: {len(Vwl)}") For some odd reason however, my program first finds the first vowel it sees, and converts the whole string into the first vowel it finds. Then it prints down the wrong amount of vowels based on the array of vowels in the array Vwls Could someone please help me?
The reason your code only prints out the first vowel is because the if statements you coded are not inside a loop, that part of the code runs once and then it finishes, so it only manages to find one vowel. Here are couple ways you can do what you are trying to do: Way 1: Here is if you just want to count the vowels: s = input() vowel_counter = 0 for letter in s: if letter in "aeiou": vowel_counter+=1 print(f"How many vowels in the sentence: {vowel_counter}") Way 2: Use a python dictionary to keep track of how many of each vowel you have s = input() vowel_dict = {} for letter in s: if letter in "aeiou": if letter not in vowel_dict: vowel_dict[letter]=0 vowel_dict[letter]+=1 print(f"How many vowels in the sentence: {sum(vowel_dict.values())}") print(vowel_dict)
Coding Hangman in Python
I'm having trouble with this hangman coding. When I run the code, it asks the question "Type in a letter a - z", but when I type in a letter, instead of it putting a letter, it just ask the same question from the beginning without letting me know if the letter is correct or not. import random possibleAnswers = ["page","computer","cookie","phishing","motherboard","freeware","bus","unix","document","hypertext","node","digital","worm","macro","binary","podcast","paste","virus","toolbar","browser"] random.shuffle(possibleAnswers) answers = list(possibleAnswers[1]) display = [] display.extend(answers) for i in range(len(display)): display[i] = "_" print ' '.join(display) print "\n\n\n\n" count = 0 while count < len(answers): guess = raw_input("Type in a letter a - z: ") guess = guess.upper() for i in range(len(answers)): if answers[i] == guess: display[i] = guess count += 1 print ' '.join(display) print "\n\n\n"
It does tell you, after a fashion. The problem is that your entire word list is lower-case, but you specifically change all of your input guesses to upper-case. Those cannot match, so there's never a "correct" guess. Change the word list to capitals, or change your conversion from upper to lower.
Hangman in Python - Replace multiple characters in single string based on index python
Trying to create a game called hangman in Python. I've come a long way, but the 'core' functionality is failing me. I've edited out all the parts which are irrelevant for this question. Here it comes: picked = ['yaaayyy'] length = len(picked) dashed = "-" * length guessed = picked.replace(picked, dashed) while tries != -1: input = raw_input("Try a letter: ") if input in picked: print "Correct letter!" found = [i for i, x in enumerate(picked) if x == input] for item in found: guessed = guessed[:item] + input + guessed[i+1:] print guessed Upon calling this script, python creates a variable named guessed containing 7 dashes ------- It asks the user for a letter and if the letter is correct, it will replace the - with the correct letter. But not keeping the previous letters. The word to be guessed is yaaayyy Output of code: Word is 7 characters: ------- Try a letter: a Correct letter! -aaa Try a letter: y Correct letter! yyyy Goal: Word is 7 characters: ------- Try a letter: a Correct letter! -aaa--- Try a letter: y Correct letter! yaaayyy
This code seems to be slightly wrong: found = [i for i, x in enumerate(picked) if x == input] for item in found: guessed = guessed[:item] + input + guessed[i+1:] That last line should probably be: guessed = guessed[:item] + input + guessed[item+1:] EDIT This seems simpler to me: for i, x in enumerate(picked): if x == input: guessed = guessed[:i] + input + guessed[i+1:] EDIT 2 I'm not sure if this is clearer or not, but it's probably a little more efficient: guessed = ''.join(x if picked[i] == input else c for i, c in enumerate(guessed))
Assuming you're using python3 you can solve it by simply doing: user_input = input() guessed = ''.join(letter if user_input == letter else guessed[i] for i, letter in enumerate(picked))
python improving word game
Im working on a word game. The purpose for the user is to guess a 5 letter word in 5 attempts. The user can know the first letter. And if he doesn't get the word correct, but if he has a letter in the correct place he gets to know this. This is my code: import random list_of_words = ["apple","table", "words", "beers", "plural", "hands"] word = random.choice(list_of_words) attempts = 5 for attempt in range(attempts): if attempt == 0: tempList = list(word[0] + ("." * 4)) print("The first letter of the word we are looking for: %s" % "".join(tempList)) answer = raw_input("What is the word we are looking for?:") if len(answer) != 5: print ('Please enter a 5 letter word') Else: if answer != word: wordlist = list(word) answerlist = list(answer) for i in range(min(len(wordlist), len(answerlist))): if wordlist[i] == answerlist[i]: tempList[i] = wordlist[i] print(tempList) else: print("correct, you have guessed the word in:", attempt, "attempts") if answer != word: print("Sorry maximum number of tries, the word is: %s" % word) I have two questions about this code: The first one is a small problem: If the user gives a 6 or 4 letter word it will still print the word. While I'd rather have it that the word is just ignored and the attempt isnt used.. If a letter is given correct (and also the first letter) it doesnt become a standard part of the feedback. Trying to get this with temp but of yet its not working great. Any suggestions to clean up my code are also appreciated! Thanks for your attention
I made some changes in your code, now it's working according to your specification. I also wrote a couple of explaining comments in it: import random list_of_words = ["apple", "table", "words", "beers", "plural", "hands"] word = random.choice(list_of_words) # changed the loop to a 'while', because i don't want to count the invalid length answers # and wanted to exit the loop, when the user guessed correctly attempts = 5 attempt = 0 correct = False while attempt < attempts and not correct: if attempt == 0: # i stored a working copy of the initial hint (ex: "w....") # i'll use this to store the previously correctrly guessed letters tempList = list(word[0] + ("." * 4)) print("The first letter of the word we are looking for: %s" % "".join(tempList)) answer = raw_input("What is the word we are looking for?:") if len(answer) != 5: print("Please enter a 5 letter word") else: if answer != word: # i simplified this loop to comparing the wordlist and answerlist and update templist accordingly wordlist = list(word) answerlist = list(answer) for i in range(min(len(wordlist), len(answerlist))): if wordlist[i] == answerlist[i]: tempList[i] = wordlist[i] print(tempList) else: correct = True print("Correct, you have guessed the word in %s attempts" % (attempt + 1)) attempt += 1 if answer != word: # also i used string formatting on your prints, so is prints as a string, and not as a tuple. print("Sorry maximum number of tries, the word is: %s" % word)
There are several problems with the code. Just 1 for now. I notice in the sample output you are entering five letter words (beeds and bread) and it still prints out Please enter a 5 letter word. These two lines: if len(answer) != 4: print ('Please enter a 5 letter word') Surely this should be: if len(answer) != 5: print ('Please enter a 5 letter word') continue This would catch an invalid input and go round the loop again.
Answering your specific questions: You will need to have a for loop around your input, keeping the user in that loop until they enter a word of appropriate length If you move guessed letters to the correct places, it is trivial to win by guessing "abcde" then "fghij", etc. You need to think carefully about what your rules will be; you could have a separate list of "letters in the guess that are in the answer but in the wrong place" and show the user this. To keep the display version with all previously-guessed characters, keep a list of the display characters: display = ["." for letter in answer], and update this as you go. Other problems you have: Too much hard-coding of word length (especially as len("plural") != 5); you should rewrite your code to use the length of the word (this makes it more flexible). You only tell the user they've won if they guess the whole answer. What if they get to it with overlapping letters? You could test as if all(letter != "." for letter in display): to see if they have got to the answer that way. Your list comprehension [i for i in answer if answer in word] is never assigned to anything.
Testing string against a set of vowels - Python
This is a module in my program: def runVowels(): # explains what this program does print "This program will count how many vowels and consonants are" print "in a string." # get the string to be analyzed from user stringToCount = input("Please enter a string: ") # convert string to all lowercase letters stringToCount.lower() # sets the index count to it's first number index = 0 # a set of lowercase vowels each element will be tested against vowelSet = set(['a','e','i','o','u']) # sets the vowel count to 0 vowels = 0 # sets the consonant count to 0 consonants = 0 # sets the loop to run as many times as there are characters # in the string while index < len(stringToCount): # if an element in the string is in the vowels if stringToCount[index] in vowels: # then add 1 to the vowel count vowels += 1 index += 1 # otherwise, add 1 to the consonant count elif stringToCount[index] != vowels: consonants += 1 index += 1 # any other entry is invalid else: print "Your entry should only include letters." getSelection() # prints results print "In your string, there are:" print " " + str(vowels) + " vowels" print " " + str(consonants) + " consonants" # runs the main menu again getSelection() However, when I test this program, I get this error: line 28, in runVowels stringToCount = input("Please enter a string: ") File "<string>", line 1 PupEman dABest ^ SyntaxError: unexpected EOF while parsing I tried adding a + 1 to the "while index < len(stringToCount)" but that didn't help either. I'm pretty new to python and I don't really understand what's wrong with my code. Any help would be appreciated. I researched this error, all I found out was that EOF stands for end of file. This didn't help at all with resolving my problem. Also, I understand that sometimes the error isn't necessarily where python says the error is, so I double-checked my code and nothing seemed wrong in my eyes. Am I doing this the round-about way by creating a set to test the string elements against? Is there a simpler way to test if string elements are in a set? Question resolved. Thank you to all!
Looks like you're using Python 2. Use raw_input(...) instead of input(...). The input() function will evaluate what you have typed as a Python expression, which is the reason you've got a SyntaxError.
As suggested use raw_input. Also you don't need to do this: while index < len(stringToCount): # if an element in the string is in the vowels if stringToCount[index] in vowels: # then add 1 to the vowel count vowels += 1 index += 1 # otherwise, add 1 to the consonant count elif stringToCount[index] != vowels: consonants += 1 index += 1 # any other entry is invalid else: print "Your entry should only include letters." getSelection() Strings in Python are iterable, so you can just do something like this: for character in stringToCount: if character in vowelSet : # Careful with variable names, one is a list and one an integer, same for consonants. vowels += 1 elif character in consonantsSet: # Need this, if something is not in vowels it could be a number. consonants += 1 else: print "Your entry should only include letters." This should do just fine. Using a while is not necessary here, and very non-Pythonic imho. Use the advantage of using a nice language like Python when you can to make your life easier ;)
You can count the vowels like so: >>> st='Testing string against a set of vowels - Python' >>> sum(1 for c in st if c.lower() in 'aeiou') 12 You can do something similar for consonants: >>> sum(1 for c in st if c.lower() in 'bcdfghjklmnpqrstvwxyz') 26
Also, if stringToCount[index] in vowels: should read if stringToCount[index] in vowelSet:
Here's another way you could solve the same thing: def count_vowels_consonants(s): return (sum(1 for c in s if c.lower() in "aeiou"), sum(1 for c in s if c.lower() in "bcdfghjklmnpqrstvwxyz")) To wit: >>> count_vowels_consonants("aeiou aeiou yyy") (10, 3) >>> count_vowels_consonants("hello there") (4, 6) Python truly is grand. The errors in your file run as follows (plus some suggestions): stringToCount = input("Please enter a string: ") This should be raw_input if you want what the user typed in as a string. stringToCount.lower() The .lower() method returns a new string with its letters lowered. It doesn't modify the original: >>> a = "HELLO" >>> a.lower() "hello" >>> a "HELLO" vowelSet = set(['a','e','i','o','u']) Here you could just as easily do: vowelSet = set("aeiou") Note you also don't strictly need a set but it is indeed more efficient in general. # sets the vowel count to 0 vowels = 0 # sets the consonant count to 0 consonants = 0 Please, you don't need comments for such simple statements. index = 0 while index < len(stringToCount): You usually don't need to use a while loop like this in python. Note that all you use index for is to get the corresponding character in stringToCount. Should instead be: for c in stringToCount: Now instead of: if stringToCount[index] in vowels: vowels += 1 index += 1 You just do: if c in vowels: vowels += 1 elif stringToCount[index] != vowels: consonants += 1 index += 1 # any other entry is invalid Not quite right. You're checking that a character doesn't equal a set. Maybe you meant: elif c not in vowels: consonants += 1 But then there'd be no else case... Got to fix your logic here. print "In your string, there are:" print " " + str(vowels) + " vowels" print " " + str(consonants) + " consonants" The above is more pythonically written as: print "In your string, there are: %s vowels %s consonants" % ( vowels, consonants) # runs the main menu again getSelection() Not sure why you're calling that there - why not call getSelection() from whatever calls runVowel()? Hope that helped! Enjoy learning this great language.
Bah, all that code is so slow ;). Clearly the fastest solution is: slen = len(StringToCount) vowels = slen - len(StringToCount.translate(None, 'aeiou')) consonants = slen - vowels ...note that I don't claim it's the clearest... just the fastest :)