count letters in a loop and break with a special char - python

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

Related

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.

How to make sure a user can only input certain characters in Python?

In my program 6 letters will be randomly generated every time and given to the user. I want the user to then only be able to input using those 6 letters,and if they don't it will be an error. When I try to use a for loop it repeats the code the number of letters the user entered times. When I use regex it only accepts it if it is exactly the same. How could I fix this?
Code
from random_word import RandomWords
r = RandomWords()
print("WELCOME TO THE ANAGRAM GAME!")
word = r.get_random_word(minLength = 6, maxLength = 6)
print(word)
done = time.time() + 60 * 1
while time.time() < done:
q1 = input("Enter your anagrams")
if re.findall(word, q1):
print("Correct")
answers = []
answers.append(q1)
print(answers)
score = 0
else:
print("Wrong")
Compare the sets of letters:
if set(word) >= set(q1): # Same (or fewer) letters
Operator >= checks if the right operand is a subset of the left operand.
If you have those random letters in a list:
if set(userInput).issubset(set(randomLetters)):
#dosomething

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

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.

Python : Hang Man game

I am making a hang man game. I am trying to cycle through a word and have all the repeats in the letter be appended to my list. For example the word "hello": if the user types in "l" I want all the l's to be added to my list. Right now it is only finding one "l" and if the user types an "l" again it finds the second "l".
I also want the user not to be able to type in another letter if they previously already typed it in.
I have two lists one for right guesses and wrong guesses that store every guess. For example if a user types in "h" in "hello"
"h" is a right guess so it appends to [h] but if they type in "h" again it adds it to the list so it says ["h","h"]. The wrong box works the same way but for words that are wrong. If they type in "z" for the word "hello" it says ["z"] in the wrong box.
Here is my code:
import random
user_input = ""
turns = 5
print("Welcome to Advanced Hang Man!")
print("Use your brain to unscramble the word without seeing its order!")
words = ["hello","goolge","czar","gnat","relationship","victor","patric","gir","foo","cheese"]
# Picks a random word from the list and prints the length of it
random_word = (random.choice(words))
random_word_legnth = (len(random_word))
print("Hint! The length of the word is",random_word_legnth)
hold_random_word = [i for i in random_word]
while turns != 0 and set(right_guess) != set(hold_random_word):
user_input = input("Please type your guess one letter at a time:")
right_guess = []
wrong_guess = []
#Calculating every input
if len(user_input) == 1 and user_input.isalpha():
for i in user_input:
if i in hold_random_word:
right_guess.append(i)
else:
wrong_guess.append(i)
print("Correct guess", ''.join(right_guess))
print("Wrong guess", ''.join(wrong_guess))
I'm not sure what your direct question is, but thinking about a hangman game you want to take the users guess and parse the entire word or phrase they are guessing to see if their guess matches anywhere in the word. I made a hang man game below that will function as expected (minus any error handling) Let me know if any parts confuse you, and i can explain
import random
wordcomp = []
wordguess = []
#this is a word bank for all puzzles, they are randomly chosen
word_bank = ['guess this phrase', 'Lagrange', 'foo', 'another phrase to guess']
# This loop stores each letter in a list, and generates a blank list with correct spaces and blanks for user
rand_word = random.randrange(4)
for i in word_bank[rand_word]:
wordcomp.append(i)
if i == ' ':
wordguess.append(' ')
else:
wordguess.append('__')
print('I am thinking of a word,' , wordguess , ' it has ', len(wordguess), ' characters total, GOOD LUCK \n')
wordlist = wordcomp
count = 0
placeletter = 0
wrongguess = []
guesscount = 0
while wordlist != wordguess:
guess = input('please input a lower case letter within the english alphabet!') ##Check that input is one character, and lower case
guesscount = guesscount + 1
# This for loop scans through to see if the letter that was guessed is in the actual puzzle, and places in the correct spot!!
for t in wordcomp:
if t == guess:
wordguess[placeletter] = guess
placeletter = placeletter + 1
# This check tells them they already guessed that letter... then makes fun of them
if guess in wordguess:
pass
else:
wrongguess.append(guess)
while wrongguess.count(guess) > 1:
wrongguess.remove(guess)
print('you guessed the letter ' , guess , ' already, are you person that suffers short term memory loss...')
print('The word I am thinking of: ' , wordguess)
print('The letters you have already guess are: ', wrongguess)
placeletter = 0
# This tells them they finished the puzzle and the number of guesses it took, if its over 26, it calls them stupid for obvious reasons...
if guesscount >= 26:
print('you are an idiot if it took you more than 26 guesses..... now take a minute, sit silently, and think about why you are idiot if it took over 26 guesses... for hangman... where you guess the letters of the alphabet... YOU GET IT, stupid')
elif guesscount < 26:
print('Congrats you solved the puzzle, w00t!!')
if len(user_input) == 1 and user_input.isalpha():
for i in user_input:
if i in hold_random_word and i not in right_guess:
right_guess.append(i)
elif i not in hold_random_word or i not in wrong_guess:
wrong_guess.append(i)
elif i in hold_random_word:
# here user types something that is already typed and is a right_guess
pass
else:
# Types something wrong, that was already typed
pass
print("Correct guess", ''.join(right_guess))
print("Wrong guess", ''.join(wrong_guess))
It is not clear how you are taking inputs, but I think this code can be further optimized. Give it a shot.
Edit 1:
import random
user_input = ""
turns = 5
print("Welcome to Advanced Hang Man!")
print("Use your brain to unscramble the word without seeing its order!")
words = ["hello","goolge","czar","gnat","relationship","victor","patric","gir","foo","cheese"]
random_word = (random.choice(words))
random_word_legnth = (len(random_word))
print("Hint! The length of the word is",random_word_legnth)
hold_random_word = [i for i in random_word]
# This condition can lead to issues in situations like this - abc and aabbcc [sorry couldn't quickly come up with a good actual example :)]
while turns != 0 and set(right_guess) != set(hold_random_word):
user_input = input("Please type your guess one letter at a time:").strip()
right_guess = []
wrong_guess = []
#Calculating every input
if len(user_input) == 1 and user_input.isalpha():
# user_input is 1 letter so for i in user_input will execute only once
# Use the if structure as defined above
if user_input in hold_random_word:
right_guess.append(i)
else:
# this is missing
turns -= 1
wrong_guess.append(i)
print("Correct guess", ''.join(right_guess))
print("Wrong guess", ''.join(wrong_guess))
elif len(user_input) > 1:
print("Please type only one letter at a time")
elif not user_input.isalpha():
print("Please enter only valid English letters")
else:
# handle this however you want :)
pass

Python3x Integer and String Input

I want the user to input a number
Give a number : he types "10" -but...
Give a number : he types "I want to type 10"
i want the program to just "count" the integer. Because if he types a string the program will stop
import random
goal = random.randrange(1,10)
n = 1
tries = 0
name = input("Dose to onoma sou ")
print("A game in Python")
while n != 0 :
value = int(input("madepse poio einai to noumero:"))
n = abs(value - goal)
print(value,n)
tries = tries + 1
if n >= 4 :
print("den eisai koda")
elif n > 0 and n <= 3 :
print("eisai koda")
else :
print("to vrikes")
print ("to score sou einai: ",tries)
skoros = str(tries)
score = open('score.txt', 'a')
score.write(name)
score.write(' ')
score.write(skoros)
score.write("\n")
score.close
This will take any input and pull the first number out of it. \d matches any digit 0-9, and + means "one or more".
import re
while True:
user = input('Enter a number: ')
match = re.search(r'\d+',user)
if match:
value = int(match.group(0))
break
else:
print("I didn't see a number in that response.")
print(value)
Well, you could just manually loop through the string and store the position of the number using isdigit().
The following approach expects the number to be the only one in the string (multi digit allowed):
start = None
stop = None
for i in range(len(input)):
c = input[i]
if c.isdigit():
if start == None:
start = i
stop = i
try:
number = int(input[start:stop])
catch:
print("invalid input")
EDIT:
I guess there would be some nice and easy Regex solution, but I'll leave my hands off of it, as I am not too experienced with it...

Categories

Resources