Getting the Error Despite Correct Output - python-3.x

getting this error meassage despite having exactly same output as expected output.
* ERROR: Expected to find a number in the line Available Letters: abcdefghijklmnopqrstuvwxyz.
Check to be sure your lines match up with the expected output!!! *
MY CODE:
def hangman(secretWord):
print ("Welcome to the game, Hangman!")
print ("I am thinking of a word that is " + str(len(secretWord)) + " letters long" )
lettersGuessed=[]
guesses = 8
p = " "
while guesses > 0:
print ("You have " + str(guesses) + " guesses left")
print ("Available Letters: " + str(getAvailableLetters(lettersGuessed))),
user_input = input("Please guess a letter: ")
user_input = str(user_input)
user_input = user_input.lower()
if user_input in lettersGuessed:
print ("Oops! You've already guessed that letter: " + str(getGuessedWord(secretWord, lettersGuessed)))
else:
lettersGuessed.append(user_input)
if user_input in secretWord:
print ("Good guess: " + str(getGuessedWord(secretWord,lettersGuessed)))
if isWordGuessed(secretWord, lettersGuessed):
break
else: continue
else:
print("Oops! That letter is not in my word: " + str(getGuessedWord(secretWord, lettersGuessed)))
guesses = guesses - 1
p = str(getGuessedWord(secretWord, lettersGuessed))
p = p.split(" ")
p = "".join(p)
p = str(p)
if p == secretWord:
print ("Congratulations, you won!")
return
else:
print ("Sorry, you ran out of guesses. The word was " + secretWord + ".")
return

Check each line and "be sure your lines match up with the expected output".
It's possible the automated system that is checking the output requires the lines of output must exactly match their "correct output" including the ----------- lines, and you're code doesn't print those lines.
Easy as:
print ("I am thinking of a word that is " + str(len(secretWord)) + " letters long" )
print ("-----------") ### <---- Add this one line
lettersGuessed=[]
and
print ("Good guess: " + str(getGuessedWord(secretWord,lettersGuessed)))
print ("-----------") ### <---- Add this one line
if isWordGuessed(secretWord, lettersGuessed):
It's possible that you'll need to add that one line in other conditions within the code, as in the else: conditions.
And as always to make debugging easier, less repetition and cleaner code, you could assign that output to a variable and print it when needed:
def hangman(secretWord):
line_break = "-----------"
...
print ("I am thinking of a word that is " + str(len(secretWord)) + " letters long" )
print (line_break)
, etc.
Hope this helps.

Related

Improving in function clarity and efficiency in python

I am very new in programming so I need help in "cleaning up my code" if the code is a mess if not then please recommend some better commands that accomplish the same purpose of any line or multiple lines.
Here is my program.
import random
def random_num():
lower_bound = input("what is your lower bound: ")
upper_bound = input("What is your upper bound: ")
trials = input("How many time would you like to try: ")
random_number = random.randint(int(lower_bound),
int(upper_bound))
user_input = input(
"What is the number that I am thinking in the range "
+ lower_bound + "-" + upper_bound + " (only " + trials + " tries): ")
ending = "Thanks For Playing"
continue_game = "That's it. Do you want to continue the game?
(Yes/No): "
count = 0
while True:
answer = int(user_input)
if count == int(trials) - 1:
lost = input("Sorry you have lost " + continue_game).lower()
if lost in ["yes"]:
random_num()
else:
return ending
else:
if answer == random_number:
win = input(continue_game).lower()
if win in ["yes"]:
random_num()
else:
return ending
elif answer >= random_number:
user_input = input("The number is smaller than that: ")
else:
user_input = input("The number is bigger than that: ")
count += 1
print(random_num())

Program doesn't work if fed with a large amount of data

#This program takes in a text file and whatever the ser types in ; it searches for the specific word or phrase and then print out in which line this word or phrase is located .
If i feed it a text file with 20 lines , it produces normal results
As soon as i give it a 3000 worded document it produces error
Can anyone explain this
while True:
search = str(input("==>"))
line_number = 1
fslope = open("searching_in_a_textfile")
for line in fslope:
if search.lower() in line:
print("tHE LINE NUMBER IS ", line_number)
print("THE LINE SAYS : " + line)
line_number = line_number + 1
continue
if search.upper() in line:
print("tHE LINE NUMBER IS ", line_number)
print("THE LINE SAYS : " + line)
line_number = line_number + 1
continue
if search.title() in line:
print("tHE LINE NUMBER IS ", line_number)
print("THE LINE SAYS : " + line)
line_number = line_number + 1
continue
else:
line_number = line_number + 1
continue
print("END OF PRIOCESS")
First lets make it simple: (this code is almost the same as yours)
lines = []
with open('searching_in_a_textfile') as f:
lines = f.readlines()
while True:
search = input('==>')
if not search:
break
for line_number, line in enumerate(lines, 1):
if search.lower() in line.lower():
print('tHE LINE NUMBER IS ', line_number, '\nTHE LINE SAYS :', line)
print("END OF PRIOCESS")
Now when the input is '' (empty string / no input) the process will stop.
if you can add your error it could be very helpful.

Code running despite no input being given (python)

When the user enters nothing, it is supposed to loop back and ask the question again. It performs correctly with every other type of input.
Here is the code:
string = ""
def str_analysis(string):
while True:
if string.isdigit():
if int(string) > 99:
print(str(string)+ " is a pretty big number!")
break
else:
print(str(string)+ " is a smaller number than expected")
break
elif string.isalpha():
print(string + " is an alphabetical character")
break
elif string == "":
print("")
else:
print(string + " is a surprise! It's neither all alpha nor all digit characters!")
break
print(str_analysis(input("Enter word or integer: ")))
There are a few things in your code that make no sense.
1:
print(str_analysis(input("Enter word or integer: ")))
You are trying to print the output of a function that has no return value
2:
It cant loop back and ask the question again, because the input is not taken inside of the function.
3:
If the string is empty you dont break the code but constantly print newlines.
Here is some code wich I think should do what you wanted:
def str_analasys():
while True:
string = input("Enter word or integer: ")
if string == '':
continue
elif string.isdigit():
if int(string) > 99:
print(str(string)+ " is a pretty big number!")
else:
print(str(string)+ " is a smaller number than expected")
elif string.isalpha():
print(string + " is an alphabetical character")
else:
print(string + " is a surprise! It's neither all alpha nor all digit characters!")
break
str_analasys()
This because when string is empty you are just printing an empty ""
elif string == "":
print("")
# break it here or take input again
# break or string = input()

moving between indexes in a list in python

In Python, I populate info from a file to a list and then print the first index in the list, now I want to print the next index from the list without multiple my code.
How can I promote the index i'm printing?
question = open("questions.txt", "r")
print(question.readlines()[0])
tanswer = open("answers.txt", "r")
correct_answer = float(tanswer.readlines()[0])
uanswer = float(input("Write the answer: "))
if correct_answer==uanswer:
print("Amazing " + str(correct_answer) + " is the correct answer")
else:
print("Wrong " + str(uanswer) + " is not correct, Try again please. ")
As far as I understood, you are trying to split the lines.
let's say
line = '1000 2000 3000'
line = line.split(' ')
then you will get line[0]
Try this I hope this helps.
Use zip:
with open("questions.txt") as ques, open("answers.txt") as ans:
for q, a in zip(ques, ans):
print(q)
uanswer = input("Write the answer: ")
if float(a) == float(uanswer):
print("Amazing " + str(a) + " is the correct answer")
else:
print("Wrong " + str(uanswer) + " is not correct, Try again please. ")

Python 3.7: How do I check if a user input is in a specific format, like "XdY", then if invalid ask again for input?

I'm trying to write a dice roller as practice. I've tried to look into try, except, while, but neither works as I intend it - before asking if the user wants to continue, I'd want to check if the user input is valid, and if not, return to user_number1. Am I looking at this from the wrong angle? What can I do with this?
Sorry for the possibly stupid question, I'm pretty new to this.
import random
print("Welcome to the dice roller!")
def roller():
user_number1 = input("Please input the dice you want to use in the following format: XdY > ")
user_number_fin = user_number1.split("d")
num1 = int(user_number_fin[0])
num2 = int(user_number_fin[1])
if num1 == 1:
result1 = random.randint(num1, num1*num2)
print("Your roll is: " + str(result1) + " (" + str(num1) + "d" + str(num2) + ")" )
else:
dice_number = 1
list_of_results = []
while dice_number <= num1:
result2 = random.randint(num1, num2)
list_of_results.append(result2)
dice_number += 1
print("Your roll is: " + str(sum(list_of_results)) + " (" + str(num1) + "d" + str(num2) + ", " + str(list_of_results)+ ")")
def shouldi():
roller()
usercont = input("Do you want to continue? y/n > ")
while usercont in ["Y", "y"]:
roller()
usercont = input("Do you want to continue? y/n > ")
if usercont in ["N", "n"]:
print("Thank you for using the dice roller. Bye!")
quit()
else:
print("That is not a valid input.")
usercont
Something like below is an alternate approach to using regex. If you're comfortable with regex then I would prefer using that instead of this. This is only an alternate approach.
def roller():
user_number1 = input("Please input the dice you want to use in the following format: XdY > ")
if("d" in user_number1):
if(len(user_number1) == 3):
user_number_fin = user_number1.split("d")
num1 = int(user_number_fin[0])
num2 = int(user_number_fin[1])
else:
print("Your input not in valid format. Use the format XdX")
You can use regular expressions and write a function that does exactly what you need then you can use it within your roller() function:
import re
def get_number():
user_number1 = input("Please input the dice you want to use in the following format: XdY > ")
user_number_fin = re.match("^(\\d*)d(\\d+)$",user_number1,re.I)
if not user_number_fin: get_number()
if user_number_fin.group(1) =='': num1 = 1
else: num1 = int(user_number_fin.group(1))
num2 = int(user_number_fin.group(2))
if num1>num2:
print("\n\tSorry--side to roll must be less than the number of sides!!")
get_number()
return {'num1':num1,'num2':num2}
This can accept d4 ie taking the default side if not given to be 1, and cannot accept 4d3 ie the side to be rolled must be less than the number of sides present in the dice.

Resources