What is wrong with my Python program using the find command? - python

I am trying to type in a list of names and then determine which ones contain the letter "e" or the letter "E" but it always just returns as 0. Can somebody tell me why?
def count_contain_e():
num_names = int(input("How many names are you going to enter: "))
count = 0
for i in range(num_names):
name = input("Enter middle name: ")
if (name.find("e") >= 0):
count += 1
return count
def main():
num_w_e = count_contain_e()
print "The number of middle names with the letter e is " + str(num_w_e)
main()

You have a problem with indentation. The if should be on the same level as name assignment (1 more tab than currently).

The problem is the identation of if statement.
What you need is insert the if inside the for in order to analyze all the names that you input, like this:
for i in range(num_names):
name = input("Enter middle name: ")
if (name.find("e") >= 0):
count += 1
Right now in the if you are only analyzing the last name because in the loop you are rewriting the variable all the time before to do the find method.
And for sure, if you want to count the capital letter too, you need to add it to the if condition, if not the program only counts the lower letter.

Related

count letters in a loop and break with a special char

I have a small problem here, i´m developing a program for children with special care so can they learn the ABC and a basic math with first contact with a PC, this one requests the user to input a string in a loop and counts the times that we insert a word, in my case i provide the letter "a". and sums every letter in the final
So the problem is that my code isn't breaking the loop if we input the "." it doesn't stop and not counting correctly, does it misses a sum ? i cant figure it out what is wrong and not understand why it´s not stopping
thank you for all the help
while True:
string = input("Insert the text :> " )
count = 0
for x in string :
if x == "a":
count = count + 1
continue
if x == ".":
break
print("the count is" +str(count))
when the program is running i input the examples under
> Insert the text :> banana
1 1 1
Insert the text :> after
1
Insert the text :> .
the count is 0
the expected is to sum all the letters at the end, and gives to me when i put a word e returns the number of A´
for example
input banana 3
input after 1
the count is 4
Like Oliver said, you need to put everything in the while loop. However, you also need to break out of the while loop. I would do it with a variable like so.
running = True
while running:
string = input("Insert the text :> " )
count = 0
for x in string :
if x == "a":
count = count + 1
continue
if x == ".":
running = False
print("the count is" + str(count))
The following code should work:
searchLetter = "a"
stopLetter = "."
totalCount = 0
while True:
string = input("Insert the text :> ")
subCount = string.count(searchLetter)
totalCount += subCount
if string.count(stopLetter) != 0:
break
print(subCount)
print("The count is " + str(totalCount))
We're using built-in str.count() function to see how many times a letter appears in a given word or line.
If the stopLetter (in this case .) appears, we instantly break out of the while loop. Otherwise, we keep accepting input.
You need to put all of your code inside the while loop:
while True:
string = input("Insert the text :> " )
count = 0
for x in string :
if x == "a":
count = count + 1
continue
if x == ".":
break
print("the count is" +str(count))
If you are considering counting every alphabet and asking the user to input a letter to find out how many times it appears, you can use a built-in function called Counter from the collections library.
from collections import Counter
while True:
string = input("Insert the text :> " )
if string == ".":
break
dictionary = Counter(string.lower())
answer = input("Press 'y' to start counting!")
while answer.lower() == 'y':
letter = input("What letter do you want to check? ")
print("the count is" , dictionary[letter])
answer = input("Do you wish to continue to check the letter? [y/n]")
The range of answers is all struggling with exit-condition and char-counting, including UI-improvements and case-sensitivity.
Divide and Conquer
I thought it would help to split you project into small isolated and testable functions. This way you can:
find bugs easier next time
easily extend for new features
Solution
def count_char(s, char, stop_char):
count = 0
for letter in s:
if letter == stop_char:
return None
elif letter == char:
count = count + 1
return count
def ask_and_count(letter, stop_char):
s = input("Counting '{letter}'s for your input (enter {stop_char} to quit):")
counted = count_char(s, letter, stop_char)
if counted is None:
return None
print(f"Counted {counted} 'a's.")
return counted
letter = 'a'
stop_char = '.'
runs = 0
while runs >= 0:
# debug-print: print(f"Run #: {runs}")
count = ask_and_count(letter, stop_char)
if count is None:
break # alternatively set runs = -1
{total}")
total += counted
# debug-print: print(f"Run #: {runs} + Counted: {count} = Total:
# Loop exited because user entered stop_char
print(f"Runs: {runs}, Total sum of '{letter}'s counted: {total}.")
This was the console dump for a test-run:
Counting 'a's for your input (enter . to quit): a
Counted 1.
Counting 'a's for your input (enter . to quit): aa
Counted 2.
Counting 'a's for your input (enter . to quit): bcdaaa
Counted 3.
Counting 'a's for your input (enter . to quit): a.a
Counted 2 when finding stop-char. Will quit without adding and display previous total.
Runs: 4. Total sum of 'a's counted: 6.
Useful patterns
defined a lot of functions (learn about def keyword arguments and return)
the exit-condition has now 2 alternatives: break # alternatively set runs = -1
plenty of informal printing done using f-strings (very useful, since Python 3.6)
added features: parameterised chars, run counter, improved UI

why does the index of "list_of_letters" not update for every while loop with "guessed_letter_string"? The problem occurs in the Try: section

Hangman. As you probobly understand i am new to coding and python, sorry for bad code.
The best way i can think of to describe this problem is through the following way: In the "try:" section i try to index = list_of_letters.index(guesssed_letter_string). i want to check if the guessed_letter_string is in list_of_letters: i earlier in the code translate the input from well the only input() in the code to guessed_letter_string (its the same thing). when you input a letter in the middel of the word it works like index[3] but when you input the first letter in the word the index locks at 0 and every other letter replaces it. is there a way to fix this
import random
list_of_words = ["mom", "dad", "sister", "brother"]
random_word = random.choice(list_of_words)
list_of_letters = list(random_word)
print(random_word)
print(list_of_letters)
rounds_failed = 1
rounds_max = 16
list_of_letters_guessed = []
under_grejer = []
count_of_right_letters_list = []
print(f"You have {rounds_max - rounds_failed} rounds left to find out the word")
for every in list_of_letters:
under_grejer.extend("_")
while True:
if rounds_failed == rounds_max:
print("To many attempts, no more rounds")
break
if len(list_of_letters) == 0:
print("YOU FUCKING WON")
break
print(f"This is round: {rounds_failed}")
print(" ".join(under_grejer))
print("Letters that are correct(not in order): "+", ".join(count_of_right_letters_list))
print("List of letters guessed: "+", ".join(list_of_letters_guessed))
guess = input("NAME A Letter: ")
guess_letters_list = (list(guess))
guess_count_letters = len(guess_letters_list)
if guess_count_letters > 1:
print("Dummy you just need to input a letter, nothing else")
guesssed_letter_string = " ".join(guess_letters_list)
try:
index = list_of_letters.index(guesssed_letter_string)
print("Congrats you got the letter: " + guesssed_letter_string)
print(f"thats the {index + 1}nd letter in the word")
rounds_failed += 1
count_of_right_letters_list.extend(guesssed_letter_string)
print(index)
list_of_letters.pop(index)
under_grejer[index] = guesssed_letter_string
except ValueError:
print("try again mate that letter was not in the word")
list_of_letters_guessed.append(guesssed_letter_string)
rounds_failed += 1
continue
It's not about the first letter only. Your problem is that with list_of_letters.pop(index) you remove the guessed letter form list_of_letters; parts of your code rely on this to check if you guessed all occurrences of that letter before already, but on the other hand this reduces the index of all letters behind the guessed one for later iterations.
For example, for brother, if you guess r it correctly says position 2, but if you then guess o next, it again says position 2 because your list_of_letters now reads ["b","o","t","h","e","r"].
You could either try to work with list_of_letters_org = list_of_letters.copy() which you will never change, and pick the right one for every task, or you could for example change the program structure by adding a list of booleans that store which letters were guessed already.

Why does my code keep on looping like this when I'm using functions?

So I'm trying to make a Hangman console game and im trying to check how many tries I have left and then later add a game over function if tries left. One part of it is working the stringcount function is working properly until I have to call the goAgain function, I'll explain the issue lower in the document
import time
hangmanSolved = "What 'eva hh"
chosingletter = input("Input a letter you would like to try! ")
def goAgain(defaultTries):
defaultTries -= 1
print("Head drawn!", defaultTries, "tries left ")
stringcount()
# if a letter is in, and how many letters are in
def stringcount():
count = 0
lettersIn = hangmanSolved.count(chosingletter)
for i in hangmanSolved:
if i == chosingletter:
count = count + 1
if not count:
print("There are no ", chosingletter, "'s in this sentence! ")
time.sleep(1)
goAgain(defaultTries=5)
elif count == 1:
print("There is only one ", chosingletter, " in this sentence! ")
else:
print("There is ", lettersIn, chosingletter, "'s in this sentence! ")
stringcount()
When I run the code and guess a wrong letter, or rather when I have to call goAgain function it keeps on looping me this output:
Input a letter you would like to try! j
There are no j 's in this sentence!
Head drawn! 4 tries left
There are no j 's in this sentence!
Head drawn! 4 tries left
How can I fix this looping, and the tries counter?!?
So first of all the counter is wrong because you are using a local variable. When the method is called with defaultTries = 5 it will always start at 5 even though you have done defaultTries -= 1.
To fix this you need to read up and assign a global variable outside of the scope so that whenever the user is wrong that global variable gets subtracted.
Furthermore, I am unsure as to why you would use the time module here. What is your goal by doing this?
What you are trying to do is loop through the sentence and check if the letter the user inputs exists inside the sentence. There are easier ways to go about this.
You can use string.indexOf('a'). where 'a' you can change it to the letter you are searching for (the user's input). It returns the index of the first occurrence of the character in the character sequence represented by this object, or -1 if the character does not occur.
I would start with changing those things first!
Every time you call goAgain you call it with defaultTries set to 5. Then, in that function, it subtracts one, leaving you with 4. Then it calls stringount which again calls goAgain which will call stringcount and so on. There's nothing that breaks out of the loop.
So you need to change three things:
Don't pass in the same value of defaultTries every time you call goAgain. You want to allow that variable to decrease.
Git rid of the goAgain function. Instead put that logic in stringcount itself.
Check the value of the number of tries remaining and if it's zero, print out some kind of message, but don't call stringcount in that branch.
def stringcount(tries = 5):
count = 0
tries =- 1
if tries == 0:
print("No tries remaining")
else:
lettersIn = hangmanSolved.count(chosingletter)
for i in hangmanSolved:
if i == chosingletter:
count = count + 1
if not count:
print("There are no ", chosingletter, "'s in this sentence! ")
time.sleep(1)
stringcount(tries)
elif count == 1:
print("There is only one ", chosingletter, " in this sentence! ")
else:
print("There is ", lettersIn, chosingletter, "'s in this sentence! ")
stringcount()
A few other things you can consider changing:
The standard formatting in Python is PEP8 and you should review those. For example, Python convention is to use snake_case instead of camelCase. So you would use something like default_tries instead of defaultTries for example.
It's probably more explicit to check if count == 0 than it is to check if not count.
I think you don't need the loop that updates the variable count. Just use lettersIn (which you should rename as letters_in or, better, just call this count). Now you also don't need to set count==0 at the top of the function.
You're having problems because you are basically using a recursive strategy but you haven't defined a base case, and also because you reinitialize your defaultTries variable to 5 every time you call the goAgain() function. A base case is a condition where you tell a recursive function to stop. In this case tries needs to be 0. Here's an example of what your code might look like:
def goAgain(tries):
tries -= 1
if tries==0:
print("You lose")
return None
print("Head drawn!", tries, "tries left ")
stringcount(tries)
def stringcount(defaultTries=5): #This is how you set default args
chosingletter = input("Input a letter you would like to try! ")
count = 0
lettersIn = hangmanSolved.count(chosingletter)
for i in hangmanSolved:
if i == chosingletter:
count = count + 1
if not count:
print("There are no ", chosingletter, "'s in this sentence! ")
time.sleep(1)
goAgain(defaultTries)
It's up to you whether you want to keep goAgain() and stringcount() separate. I think it makes sense to keep them separate because I can imagine you want to check how many tries are in goAgain and then print new statements accordingly, like "left arm drawn!" etc.

Finding the next entity in a list python

I am relatively new to python and I have searched the web for an answer but I can't find one.
The program below asks the user for a number of inputs, and then asks them to input a list of integers of length equal to that of the number of inputs.
Then the program iterates through the list, and if the number is less than the ToyValue, and is less than the next item in the list the variable ToyValue increments by one.
NoOfToys=0
ToyValue=0
NumOfTimes=int(input("Please enter No of inputs"))
NumberList=input("Please enter Input")
NumberList=NumberList.split(" ")
print(NumberList)
for i in NumberList:
if int(i)>ToyValue:
ToyValue=int(i)
elif int(i)<ToyValue:
if int(i)<int(i[i+1]):
NoOfToys=NoOfVallys+1
ToyValue=int(i[i+1])
else:
pass
print(NoOfVallys)
Here is an example of some data and the expected output.
#Inputs
8
4 6 8 2 8 4 7 2
#Output
2
I believe I am having trouble with the line i[i+1], as I cannot get the next item in the list
I have looked at the command next() yet I don't think that it helps me in this situation.
Any help is appreciated!
You're getting mixed up between the items in the list and index values into the items. What you need to do is iterate over a range so that you're dealing solidly with index values:
NoOfToys = 0
ToyValue = 0
NumOfTimes = int(input("Please enter No of inputs"))
NumberList = input("Please enter Input")
NumberList = NumberList.split(" ")
print(NumberList)
for i in range(0, len(NumberList)):
value = int(NumberList[i])
if value > ToyValue:
ToyValue = value
elif value < ToyValue:
if (i + 1) < len(NumberList) and value < int(NumberList[i + 1]):
NoOfToys = NoOfVallys + 1
ToyValue = int(NumberList[i + 1])
else:
pass
print(NoOfVallys)
You have to be careful at the end of the list, when there is no "next item". Note the extra check on the second "if" that allows for this.
A few other observations:
You aren't using the NumOfTimes input
Your logic is not right regarding NoOfVallys and NoOfToys as NoOfVallys is never set to anything and NoOfToys is never used
For proper Python coding style, you should be using identifiers that start with lowercase letters
The "else: pass" part of your code is unnecessary

Python: Select Only Parts of an input?

Sorry...I'm kind of a programming noob. I was looking at some problem sets online and I found THIS ONE. I wrote this much:
import random
powerball=random.randint(1,42)
a=random.randint(1,53)
b=random.randint(1,53)
c=random.randint(1,53)
d=random.randint(1,53)
e=random.randint(1,53)
(f,g,h,i,j)=x=input("Your 5 Chosen Numbers:")
My problem is that I don't know how to make the program print something like "Please enter 5 numbers separated by only a comma" if more or less than five are entered. Also how would I do that if I wanted it to display a different message every other time they made that mistake?
Try this approach:
input_is_valid = False
while not input_is_valid:
comma_separated_numbers = raw_input("Please enter a list of 5 numbers,separated by commas: ")
numbers = [int(x.strip()) for x in comma_separated_numbers.split(",")]
if len(numbers) != 5:
print "Please enter exactly 5 numbers"
else:
input_is_valid = True
Looking at your link I'd say:
import random
while True:
sets = input('how many sets? ')
if type(sets) == int:
break
else:
pass
for i in range(sets):
ri = random.randint
powerball = ri(1,42)
other_numbers = sorted(ri(1,53) for i in range(5))
print 'your numbers:','\t',other_numbers,'\t','powerball:','\t',powerball
It seems that's more or less what he asks from you.
If I'm correct, you want the user to submit his series so to see if its one of the sets extracted (amirite?)
then it could be fine to do:
import random
while True:
sets = input('how many sets? ')
if type(sets) == int:
break
else:
pass
while True:
myset = raw_input('your 5 numbers:').split()
if len(myset) != 5:
print "just five numbers separated ny a space character!"
else:
myset = sorted(int(i) for i in myset)
break
for i in range(sets):
ri = random.randint
powerball = ri(1,42)
numbers = sorted(ri(1,53) for i in range(5))
print 'numbers:','\t',numbers,'\t','powerball:','\t',powerball
if numbers == myset:
print "you won!" ##or whatever the game is about
else:
print "ahah you loser"
EDIT: beware this doesn't check on random generated numbers. So it happens one number can appear more than once in the same sequence. To practice you may try avoiding this behavior, doing so with a slow pace learning some python in the way it could be:
make a set out of a copy of the list "numbers" -- use set()
if its length is less than 5, generate another number
check if the new number is in the list
if it is, then append it to the list. if its not unique yet, GOTO point 1 :-)
sort the whole thing again
there you go
happy reading the docs!
My proposition:
import random
import sys
powerball=random.randint(1,42)
a=random.randint(1,53)
b=random.randint(1,53)
c=random.randint(1,53)
d=random.randint(1,53)
e=random.randint(1,53)
bla = ["\nPlease enter 5 numbers separated by only a comma : ",
"\nPlease, I need 5 numbers separated by only a comma : ",
"\nPLEASE, 5 numbers exactly : ",
"\nOh gasp ! I said 5 numbers, no more nor less : ",
"\n! By jove, do you know what 5 is ? : ",
"\n==> I warn you, I am on the point to go off : "]
i = 0
while i<len(bla):
x = raw_input(warn + bla[i])
try:
x = map(int, x.split(','))
if len(x)==5:
break
i += 1
except:
print "\nTake care to type nothing else than numbers separated by only one comma.",
else:
sys.exit("You wanted it; I go out to drink a beer : ")
(f,g,h,i,j)=x
print f,g,h,j,i
.
Some explanation:
.
for_stmt ::= "for" target_list "in" expression_list ":" suite
["else" ":" suite]
A break statement executed in the first suite terminates the loop without executing the else clause’s suite. A continue statement executed in the first suite skips the rest of the suite and continues with the next item, or with the else clause if there was no next item.
http://docs.python.org/reference/compound_stmts.html#index-801
.
.
x = map(int, x.split(','))
means that the function int() is applied to each element of the iterable which is the second argument.
Here the iterable is the list x.split(',')
Hence, x is a list of 5 integers
In Python 3, there is no more raw_input() , it has been replaced by input() that receives characters, as raw_input() in Python 2.
.
.

Categories

Resources