def main():
print("You haved activated Weather Pro 3.0")
rain_inputs()
rain_calc()
def rain_inputs():
global rain
rain = []
for x in range(1, 13):
try:
rain_meter = float(input("What is the rainfall? "))
rain.append(rain_meter)
if x == 4:
print("8 more months to go!")
elif x == 7:
print("5 more months to go!")
elif x == 9:
print("2 more to go! Smash those keys!")
elif x == 13:
return
except Exception as err:
err = ("You should be putting in numbers!")
print(err)
rain_calc is supposed to calculate the total of all listed inputs.
def rain_calc():
rain_math =(rain[0] + rain[1] + rain[2] + rain[3])
rain_math2 =(rain[5] + rain[6] + rain[7] + rain[8])
rain_math3 =(rain[9] + rain[10] + rain[11] + rain[12])
rain_total =(rain_math + rain_math2 + rain_math3)
print(rain_total)
main()
The error occurs in rain-math3:
Programming/RainFall.py", line 30, in rain_calc rain_math3 =(rain[9] + rain[10] + rain[11] + rain[12])
IndexError: list index out of range
rain[12] is out of range because rain only has 12 elements in it. You missed rain[4], so you probably wanted this:
def rain_calc():
rain_math =(rain[0] + rain[1] + rain[2] + rain[3])
rain_math2 =(rain[4] + rain[5] + rain[6] + rain[7])
rain_math3 =(rain[8] + rain[9] + rain[10] + rain[11])
rain_total =(rain_math + rain_math2 + rain_math3)
print(rain_total)
Related
My code for now works as desired where the user can input a level 1-3 depending on how hard they would like it to be (1-3 being the amount of digits the numbers will have in the math equation), and then must solve math equations. Those math equations will output EEE if the answer is incorrect and everything works as planned if you correctly answer the question as it exits the function and adds one total_correct_answers variable at the bottom, then will prompt you with another equation. However, if you input an incorrect answer and then a correct answer, you will just be prompted with the same question over and over again without the try loop being truly broken out of and total_correct_answers not being incremented positively by 1. The incrementation block of code is at lines 61-65, and the equation code is lines 30-49.
import random
def main():
ten_questions()
def get_level():
while True:
try:
level_input = int(input("Level: "))
if level_input in [1,2,3]:
return level_input
except:
pass
def integer_generator(level):
if level == 1:
x = random.randint(0,9)
y = random.randint(0,9)
elif level == 2:
x = random.randint(10, 99)
y = random.randint(10, 99)
else:
x = random.randint(100, 999)
y = random.randint(100, 999)
return x, y
def question_generator(x, y):
real_answer = x + y
wrong_counter = 0
while True:
try:
answer_given = input(str(x) + " + " + str(y) + " = ")
if int(answer_given) == real_answer:
if wrong_counter == 0:
return True
elif int(answer_given) == real_answer and wrong_counter != 0:
break
else:
while wrong_counter < 2:
print("EEE")
wrong_counter +=1
break
else:
print(str(x) + " + " + str(y) + " = " + str(real_answer))
print("False, that was last attempt")
break
except:
print("EEE")
pass
def ten_questions():
num_of_questions = 0
total_correct_answers = 1
my_level = get_level()
correct_answers = question_generator(*integer_generator(my_level))
while num_of_questions <= 8:
question_generator(*integer_generator(my_level))
num_of_questions +=1
if correct_answers == True:
total_correct_answers +=1
print("Score: " + str(total_correct_answers))
if __name__ == "__main__":
main()
Because of your line 36:
if int(answer_given) == real_answer: happens when someone answers correctly, wether they are right or wrong. So it enters the if, and then faces if wrong_counter == 0: which discards wrong answers. So just replace those two lines with if int(answer_given) == real_answer and wrong_counter == 0: and you are good to go.
So, i am trying to write a code to not only do arithmetic equations, but also, give feedback if there is an error as well as give me 3 tries max. any advice?
arithmetic=input("Enter an arithmetic operation:")
arithmetic= arithmetic.replace(" ", "")
w=arithmetic.split('/')
x= arithmetic.split('-')
y=arithmetic.split('+')
z=arithmetic.split('*')
if ("+" in arithmetic):
a= int(y[0])
b= int(y[1])
sum = a + b
print("The result is = " + str(sum))
elif ("*" in arithmetic):
a= int(z[0])
b= int(z[1])
result = a * b
print("The result is = " + str(result))
elif ("/" in arithmetic):
a= int(w[0])
b= int(w[1])
result = a / b
result = round(result,3)
print("The result is = " + str(result))
elif ("-" in arithmetic) and (len(x)==3):
a= int(x[1])
b= int(x[2])
result = a + b
result = result * (-1)
print("The result is = " + str(result))
elif ("-" in arithmetic) and (len(x)==2):
a= int(x[0])
b= int(x[1])
result = a - b
print("The result is = " + str(result))
#tries = 0
#while(tries < 3):
# arithmetic=input("Enter an arithmetic operation:")
# match = arithmetic.find('+')
# print(match)
# if(match == -1):
# print ("Invalid")
# tries += 1
# else:
# tries= 3
I tried to add the while in the beginning. However, when i put an input such as 11 and 12 without the + sign, it just printed the input without giving me an error. why is that?
tries = 0
while tries < 3:
arithmetic = input("Enter an arithmetic operation:")
arithmetic = arithmetic.replace(" ", "")
w = arithmetic.split('/')
x = arithmetic.split('-')
y = arithmetic.split('+')
z = arithmetic.split('*')
try:
if ("+" in arithmetic):
a = int(y[0])
b = int(y[1])
sum = a + b
print("The result is = " + str(sum))
elif ("*" in arithmetic):
a = int(z[0])
b = int(z[1])
result = a * b
print("The result is = " + str(result))
elif ("/" in arithmetic):
a = int(w[0])
b = int(w[1])
result = a / b
result = round(result, 3)
print("The result is = " + str(result))
elif ("-" in arithmetic) and (len(x) == 3):
a = int(x[1])
b = int(x[2])
result = a + b
result = result * (-1)
print("The result is = " + str(result))
elif ("-" in arithmetic) and (len(x) == 2):
a = int(x[0])
b = int(x[1])
result = a - b
print("The result is = " + str(result))
else:
print("Invalid")
tries += 1
continue
break
except ValueError: # for case split not working good due cases like first input is a negative number
print("Invalid")
tries += 1
At the end of your if / else if chain, just add:
else:
print("invalid")
tries += 1
Replace everything you have inside your while loop currently with the uncommented code above it and that should work.
def kaprekar_num(num):
count = 0
while count <= num:
n = 1
sqr = n ** 2
digits = str(sqr)
length = len(digits)
for x in range(1, length):
left = int("".join(digits[:x]))
right = int("".join(digits[x:]))
if (left + right) == n:
print("Number: " + str(n) + ", Left: " + str(left) + " + " + " Right: " + str(right) + " = " + str(n))
n += 1
count += 1
else:
n += 1
kaprekar_num(5)
hello guys,
I'm new to python programming and I got a task in class to print the first 5 kaprekar numbers.
(I only have C programming background...)
I have a problem with the "for x in range..." line.. the code doesn't enter the loop and I don't know why.
the program needs to print:
Number: 9, Left: 8 + Right: 1 = 9
Number: 10, Left: 10 + Right: 0 = 10
Number: 45, Left: 20 + Right: 25 = 45
Number: 55, Left: 30 + Right: 25 = 55
Number: 99, Left: 98 + Right: 1 = 99
I will appreciate some insights :)
for loop was fine, you had some logic issue, which you haven't handled, like when n==1 and when len(sqr)==1.
def kaprekar_num(num):
count = 0
n=1
while count <= num:
sqr = n ** 2
digits = str(sqr)
length = len(digits)
if sqr==1:
print("Number: " + str(n) + " = " + str(n))
count+=1
n+=1
elif length>1:
for x in range(1,length):
left = int("".join(digits[:x]))
right = int("".join(digits[x:]))
if (left + right) == n:
print("Number: " + str(n) + ", Left: " + str(left) + " + " + " Right: " + str(right) + " = " + str(n))
n += 1
count += 1
else:
n += 1
else:
n+=1
kaprekar_num(5)
How you're managing the n value is incorrect. It should be set before the loop starts, then after each try, regardless of the outcome, it should increment.
def kaprekar_num(num):
count = 0
# Start n at one, and don't reset it on each loop
n = 1
while count <= num:
sqr = n ** 2
digits = str(sqr)
length = len(digits)
for x in range(1, length):
left = int("".join(digits[:x]))
right = int("".join(digits[x:]))
if (left + right) == n:
print("Number: " + str(n) + ", Left: " + str(left) + " + " + " Right: " + str(right) + " = " + str(n))
count += 1
# This number is a Kaprekar number, so break out of the loop
break
# Regardless of the status of this number, try the next one
n += 1
kaprekar_num(5)
And as a recommendation: I'd highly recommend you look into stepping through the code with a debugger in the future. If you had done so, you'd have seen that n is not changing fairly quickly.
you've set the loop to repeat once i think, if you meant to put n instead of 1, i think thats the problem.
Try to set the loop to this instead
for x in range(n, length):
So I have been working on a quizzing application for some time now (about 4 days). I managed to make all the logical part of the code (the quiz taking, the quiz question handling, score outputting, etc.) I know that this code is neither the best nor the most efficient as it can be but I'm just a beginner. Anyways, the get() function for the entry function for tkinter does not return anything. I am aware that there is a way to fix it however I'm not sure how to implement the solution with an external loop. Please help me. Here is my code:
import random
from time import sleep
import tkinter as tk
from tkinter import *
import threading
class App(threading.Thread):
def __init__(self):
threading.Thread.__init__(self)
self.start()
def callback(self):
self.root.quit()
def run(self):
self.root = tk.Tk()
self.root.protocol("WM_DELETE_WINDOW", self.callback)
#label = tk.Label(self.root, text="Hello World")
#label.pack()
#Button(self.root, text = "Choose", command=btnPressed).pack()
tk.Label(self.root, text="Answer: ").grid(row=0,column=0)
#answerField_get = StringVar()
answerField = tk.Entry(self.root)
answerField.grid(row=0, column=1)
#Button(self.root, text='Show').grid(row=3, column=1, sticky=tk.W, pady=4)
print(str(answerField.get()))
Button(self.root, text='Show', command = lambda arg1=answerField.get():btnPressed("<"+str(arg1)+">")).grid(row=3, column=1, sticky=tk.W, pady=4)
self.root.mainloop()
def sendTMP(self, sendStr):
btnPressed(sendStr)
SCORE_SET = []
qasTmp = {}
qas = {}
qasSequenced = {}
incorrectResponses = []
incorrectResponses_replies = []
quiztaker_name = ""
attachAnsCode = "%% Fun fact: rgb computer parts lovers are somewhat weird hehe %%********^^&&^^&&^^&&"
qasQsSequenced = False
qasQsL = 0
qasQsL_divisionFactor = 2
qasINDEX = 0
err_noCode = "<!>NO_CODE<!>"
codes_answerCorrect = "A_C"
codes_answerIncorrect = "A_I"
answerCode = err_noCode
score = 0
randQs = False
# File
# the metadata will corrupt the reading from the file, a separate file, created in the targeted system, must be used to properly read the data.
# comment out the file name that is not being used.
filename_windows = "qas-windows"
filename_rpi = "qas-rpi"
filename = filename_windows
fileformat = "txt"
file_name_format = filename + "." + fileformat
spaceIndicator = "|"
char_commentLine_qasFile = "*"
char_newline = "`"
print("Information about modes: ")
print(" *Easy: No point deductions for an incorrect response")
print(" *Hard: One point deducted for every incorrect response")
modes_err = "0"
modes_ez = "1"
modes_hard = "2"
gameOn = False
selectedMode = modes_err
askReplay = True
data_prev = []
with open("SCORES.txt", 'r') as scores_prev:
data_prev = scores_prev.readlines()
scores_prev.close()
for i in range(0, len(data_prev)):
SCORE_SET.append(data_prev[i])
def btnPressInform():
print("A button has been pressed!")
def importAndClean():
# import questions from qas-windows.txt
with open(file_name_format, 'r') as document:
for line in document:
if line.strip():
key, value = line.split(None, 1)
if key[0] != char_commentLine_qasFile: # Custom comments for the txt file
qasTmp[key] = value.split()
# Clean up dictionary input from the txt file
for i in range(0, len(qasTmp)): # FIVE FOR LOOPS!!!! (FOUR IN THIS ONE)
for ii in qasTmp:
output = ""
output_ans = ""
for iii in range(0, len(ii)):
if ii[iii] != spaceIndicator:
output += ii[iii]
else:
output += " "
for iiii in range(0, len(qasTmp[ii])):
TEMP = str(qasTmp[ii])
for iiiii in range(2, len(TEMP) - 2): # IGNORE [' and ']
# print(TEMP[iiiii])
if TEMP[iiiii] != spaceIndicator:
output_ans += TEMP[iiiii]
else:
output_ans += " "
# print(output + " : " + output_ans) #Output question: answer
qas[output] = output_ans
importAndClean()
def getL():
qasQsL = len(qas) / qasQsL_divisionFactor # only ask 1/qasQsL_divisionFactor the questions
qasQsL = int(qasQsL) # round to an integer as odd numbers will end in .5 after division
if qasQsL < 1:
qasQsL = 1 # Have atleast ONE question
return qasQsL
def debug1(keys, vals, index, i):
print(str(index) + "/" + str((len(keys) - 1)))
print(keys)
print(vals)
print()
print(keys[index] + " : " + vals[index] + "\n")
print("Sorting original index " + str(i) + " at random index " + str(index))
def debug2(keys, vals, index):
print(keys)
print(vals)
print("\n")
def debugFinal():
print("Temp (OG reading): ")
print(qasTmp)
print("\nQAS (Non-sequenced, cleaned): ")
print(qas)
print("\nQAS Sequenced (Randomly sequenced, cleaned): ")
print(qasSequenced)
def randomize(qasQsL_tmp):
qas_keys = list(qas.keys())
qas_vals = list(qas.values())
if randQs == False:
qasQsL_tmp = len(qas_keys) # all questions
print("You will be asked all " + str(qasQsL_tmp) + " questions")
else:
qasQsL_tmp = getL() # random question
print("You will be asked " + str(qasQsL_tmp) + " questions out of " + str(len(qas)) + " possible questions!")
print("\n\nRandomly sequencing questions...")
for i in range(0, qasQsL_tmp):
INDEX = random.randint(0, qasQsL_tmp - 1)
# debug1(qas_keys, qas_vals, INDEX, i)
qasSequenced[qas_keys[INDEX]] = qas_vals[INDEX]
qas_keys.pop(INDEX)
qas_vals.pop(INDEX)
qasQsL_tmp -= 1
# debug2(qas_keys, qas_vals, INDEX)
sleep(0.05)
# debugFinal()
print("Done sequencing! Starting quiz now! \n\n")
return "0"
def quizController(index):
qas_keys = list(qasSequenced.keys())
qas_vals = list(qasSequenced.values())
# print(qas_keys)
# print(qas_vals)
lines = []
lines_index = 0
tmp = ""
# Splitter
for i in range(0, len(qas_keys[index])):
if lines_index < len(qas_keys[index]) - 1:
if qas_keys[index][i] != char_newline:
tmp += qas_keys[index][i]
else:
lines.append(tmp)
tmp = ""
lines.append(tmp)
# Multiple choice
mChoiceQ = False
mChoice_startBrackets = 0
mChoice_endBrackets = 0
mChoice_options = []
mChoice_numOptions = 0
mChoice_seperatorsAt = []
for i in range(0, len(qas_keys[index])):
if qas_keys[index][i] == "[":
mChoice_startBrackets = i
mChoiceQ = True
elif qas_keys[index][i] == "]":
mChoice_endBrackets = i
elif qas_keys[index][i] == "/":
mChoice_seperatorsAt.append(i)
if mChoiceQ == True:
TEMP = ""
for i in range(mChoice_startBrackets, mChoice_endBrackets + 1):
if qas_keys[index][i] != "[":
if qas_keys[index][i] != "/" and qas_keys[index][i] != "]":
TEMP += qas_keys[index][i]
else:
mChoice_options.append(TEMP)
TEMP = ""
mChoice_numOptions = len(mChoice_seperatorsAt) + 1
# Default options (yes, no) full names
for i in range(0, len(mChoice_options)):
if mChoice_options[i].lower() == "y":
mChoice_options.append("yes")
elif mChoice_options[i].lower() == "n":
mChoice_options.append("no")
# if mChoiceQ == True:
# print("It is a multiple choice question! There are " + str(mChoice_numOptions) + " options. They are: ")
# print(mChoice_options)
print("\nQuestion " + str(index + 1) + "/" + str(qasQsL) + ":")
for i in range(0, len(lines)):
print(lines[i])
# answer = ""
answer = input(">")
# answer = input(qas_keys[index]+ ": ")
if mChoiceQ == False:
if len(answer) > 0:
if answer.lower() == str(qas_vals[index]).lower():
return codes_answerCorrect
else:
incorrectResponses.append(qas_keys[index])
incorrectResponses_replies.append(answer)
# print("DEBUG: Incorrect response! Expected '" + str(qas_vals[index]).lower() + "', received " + answer.lower())
return codes_answerIncorrect
else:
print("Please insert an answer!")
else:
allowedResponse = False
for i in range(0, len(mChoice_options)):
if answer.lower() == mChoice_options[i].lower():
allowedResponse = True
if allowedResponse == True:
ans = qas_vals[index].lower()
yn = False
ans_yesno = ""
if ans.lower() == "y" or ans.lower() == "n":
yn = True
else:
yn = False
if yn == True:
if ans == "y":
ans_yesno = "yes"
elif ans == "n":
ans_yesno = "no"
if len(answer) > 0:
if yn == True:
if answer.lower() == ans.lower() or answer.lower() == ans_yesno.lower():
return codes_answerCorrect
else:
return codes_answerIncorrect
incorrectResponses.append(qas_keys[index])
incorrectResponses_replies.append(answer)
else:
if answer.lower() == ans.lower():
return codes_answerCorrect
else:
return codes_answerIncorrect
incorrectResponses.append(qas_keys[index])
incorrectResponses_replies.append(answer)
else:
print("Please insert an answer!")
else:
print("Invalid response! You may only enter the following: " + str(mChoice_options))
def saveScore():
# Clear file!
score_file_CLEAR = open("SCORES.txt", "wt")
score_file_CLEAR.close()
# Save contents
score_file = open("SCORES.txt", "wt")
for i in range(0, len(SCORE_SET)):
score_file.write(SCORE_SET[i])
print("Done saving!")
def btnPressed(tmp):
print(tmp)
app = App()
while True:
qasQsL = len(qasSequenced)
if gameOn == True and selectedMode != modes_err:
if qasQsSequenced == True:
if qasINDEX < qasQsL:
answerCode = quizController(qasINDEX)
else:
output = randomize(qasQsL)
if output == "0":
qasQsSequenced = True
if qasINDEX < qasQsL:
if answerCode == codes_answerCorrect:
score += 1
qasINDEX += 1
# print("DEBUG: Correct! Score set to: " + str(score))
elif answerCode == codes_answerIncorrect:
if selectedMode == modes_hard:
score -= 1
qasINDEX += 1
# print("Score set to: " + str(score))
else:
print("")
if qasQsL != 0:
score_per = score / qasQsL
if score_per < 0:
score_per = 0
if score < 0:
score = 0
print("You score was lower than 0, therefore it was set to 0")
# print("Your score: " + str(score) + "/" + str(len(qasSequenced)) + " (" + str(int(score_per*100)) + "%)")
# if score != qasQsL:
# print("You responded to the following questions incorrectly:")
# print(incorrectResponses)
if score / qasQsL == 1:
SCORE_SET.append(quiztaker_name + " scored " + str(score) + " out of " + str(qasQsL) + "(" + str(
int(score / qasQsL) * 100) + "%). PART OF Qs: " + str(
int(randQs)) + " at division factor 1/" + str(qasQsL_divisionFactor) + ", MODE: " + str(
int(selectedMode)) + "\n")
if score / qasQsL != 1:
SCORE_SET.append(quiztaker_name + " scored " + str(score) + " out of " + str(qasQsL) + " (" + str(
int(score / qasQsL) * 100) + "%). PART OF Qs: " + str(
int(randQs)) + " at division factor 1/" + str(qasQsL_divisionFactor) + ", MODE: " + str(
int(selectedMode)) + " They got the following questions wrong: \n")
for i in range(0, len(incorrectResponses)):
SCORE_SET.append(" " + str(i + 1) + ") " + incorrectResponses[i] + " --RESPONSE-- " +
incorrectResponses_replies[i] + "\n")
SCORE_SET.append("\n")
saveScore()
qasQsSequenced = False
gameOn = False
print("\nGame over!")
askReplay = True
else:
continue
elif askReplay == False:
TEMP = input("What mode would you like? (E = Easy, H = Hard): ")
if len(str(TEMP)) > 0:
if str(TEMP).lower() == "e":
selectedMode = modes_ez
gameOn = True
print("Set mode to: NO POINT DEDUCTIONS")
elif str(TEMP).lower() == "h":
selectedMode = modes_hard
gameOn = True
print("Set mode to: POINT DEDUCTIONS ALLOWED")
else:
print("Error: Undefined response. Please try again!")
elif askReplay == True:
TEMP = input("Would you like to (re)do the quiz? (Y/N): ")
if len(str(TEMP)) > 0:
if str(TEMP).lower() == "y":
askReplay = False
qasQsSequenced = False
qasQsL = 0
qas.clear()
qasSequenced.clear()
qasTmp.clear()
qasINDEX = 0
incorrectResponses.clear()
answerCode = err_noCode
score = 0
selectedMode = modes_err
importAndClean()
randQs = False
USER_TEMP = input("Please enter your name >")
if len(USER_TEMP) > 0:
quiztaker_name = str(USER_TEMP)
print("Welcome " + quiztaker_name + "!")
USER_TEMP = input("Would you like all questions (a) or a part of the questions(p)? (A/P) > ")
if len(USER_TEMP) > 0:
if USER_TEMP.lower() == "a":
print("Set to all questions!")
randQs = False
elif USER_TEMP.lower() == "p":
print("Set to 1/" + str(qasQsL_divisionFactor) + " questions (pre-set variable)")
randQs = True
else:
print("Undefined response! Setting to default value (ALL)")
randQs = False
gameOn = False
askReplay = False
elif str(TEMP).lower() == "n":
selectedMode = modes_hard
gameOn = False
print("Exiting now!")
saveScore()
sleep(2)
exit(0)
else:
print("Error: Undefined response. Please try again!")
Entry() doesn't work like input(). It doesn't wait for your data but it only informs tkitner that you want to display Entry widget (and mainloop() will display it) and Python goes to next lines of code and it runs print(str(answerField.get())) before it even displays window - so you try to get from empty Entry.
You should get it in function assigned to Button which you will press after you put some text in Entry.
The same problem is with
lambda arg1=self.answerField.get():print(arg1)
it assigns to args value from Entry only once when lambda is defined at start - so it get empty string. You should use it inside function
command=lambda:print(self.answerField.get())
or create normal function and assign to button.
Minimal working code
import tkinter as tk
import threading
class App(threading.Thread):
def run(self):
self.root = tk.Tk()
#self.root.protocol("WM_DELETE_WINDOW", self.on_close)
self.answerField = tk.Entry(self.root)
self.answerField.grid(row=0, column=1)
#b = tk.Button(self.root, text='Show', command=lambda:print(self.answerField.get()))
b = tk.Button(self.root, text='Show', command=self.on_click)
b.grid(row=1, column=1)
self.root.mainloop()
def on_click(self):
print(self.answerField.get())
#def on_close(self):
# self.root.destroy()
App().start()
#App().run()
Everything works besides values between 100 and 999, except values divisible by 100 work.
The game is as follows:
Four is magic. Write a Python program (called q3.py) that given an integer from 0 to 1000 does the “4 is magic” transformation. The steps are as follows:
Convert the integer n into English and count the number of letters (i.e. 21 is “twenty one” and consists of 9 letters, 102 is “one hundred two” and consists of 13 letters, 1000 is “one thousand” and consists of 11 letters).
Let nlen be the length of the English word equivalent for the integer n.
a. If nlen is 4, output “four is magic.” Then, terminate the transformation process.
b. Otherwise output “ is nlen.” Repeat
step (a), where the integer n is set to nlen.
Suppose the user inputs the integer 26. Then, the transformation proceeds as follows.
26 is 9. , where twenty six is the 9-letter English word equivalent of 26.
9 is 4. , where nine is the 4-letter English word equivalent of 9.
4 is magic.
def convert(number_str):
# Enter your code here.
count = 0
index = 0
x = ['zero','one','two','three','four','five','six','seven','eight','nine','ten','eleven','twelve','thirteen','fourteen','fifteen','sixteen','seventeen','eighteen','nineteen']
y = ['zero','ten','twenty','thirty','forty','fifty','sixty','seventy','eighty','ninety']
while (number_str != '4'):
if 0 <= int(number_str) <= 19:
a = len(x[int(number_str)])
print(x[int(number_str)],'is',a)
number_str = str(a)
elif 20 <= int(number_str) <= 99:
if number_str[1] == "0":
a = len(y[int(number_str[0])])
print(y[int(number_str[0])],'is',a)
number_str = str(a)
else:
a = len(y[int(number_str[0])]) + len(x[int(number_str[1])])
print(y[int(number_str[0])] + ' ' + x[int(number_str[1])],'is',a)
number_str = a
elif 100 <= int(number_str) <= 999:
rem = int(number_str) % 100
div = int(number_str) // 100
if rem == 0:
a = len(x[div]) + 7
print(x[div] + ' hundred is',a)
number_str = str(a)
else:
if (number_str[1] == '0'):
a = len(x[div]) + 7 + len(convert(str(rem)))
print(x[div] + ' hundred ' + convert(str(rem)) + ' is '+ str(a))
number_str = str(a)
elif (number_str[1] != '0'):
a = len(x[div]) + 6 + len(convert(str(rem)))
print(x[div] + ' hundred ' + convert(str(rem)) + ' is '+ str(a))
number_str = str(a)
elif number_str == '1000':
a = 11
print('one thousand is '+ str(a))
number_str = str(a)
return 'four is magic'
def main():
''' The program driver. '''
user_input = input('> ')
while user_input != 'quit':
print(convert(user_input))
user_input = input('> ')
main()
My question is what is wrong with this area:
else:
if (number_str[1] == '0'):
a = len(x[div]) + 7 + len(convert(str(rem)))
print(x[div] + ' hundred ' + convert(str(rem)) + ' is '+ str(a))
number_str = str(a)
elif (number_str[1] != '0'):
a = len(x[div]) + 6 + len(convert(str(rem)))
print(x[div] + ' hundred ' + convert(str(rem)) + ' is '+ str(a))
number_str = str(a)
convert always returns "four is magic" It looks like you want it to return some value based on its input.
def convert(number_str):
# Enter your code here.
count = 0
index = 0
x = ['zero','one','two','three','four','five','six','seven','eight','nine','ten','eleven','twelve','thirteen','fourteen','fifteen','sixteen','seventeen','eighteen','nineteen']
y = ['zero','ten','twenty','thirty','forty','fifty','sixty','seventy','eighty','ninety']
while (number_str != '4'):
if 0 <= int(number_str) <= 19:
a = len(x[int(number_str)])
print(x[int(number_str)],'is',a)
number_str = str(a)
elif 20 <= int(number_str) <= 99:
if number_str[1] == "0":
a = len(y[int(number_str[0])])
print(y[int(number_str[0])],'is',a)
number_str = str(a)
else:
a = len(y[int(number_str[0])]) + len(x[int(number_str[1])])
print(y[int(number_str[0])] + ' ' + x[int(number_str[1])],'is',a)
number_str = a
elif 100 <= int(number_str) <= 999:
rem = int(number_str) % 100
div = int(number_str) // 100
print(div)
if rem == 0:
a = len(x[div]) + 7
print(x[div] + ' hundred is',a)
number_str = str(a)
else:
if (number_str[1] == '0'):
a = len(x[div]) + 7 + len(str(x[rem]))
print(x[div] + ' hundred ' + str(x[rem]) + ' is '+ str(a)) # error was here
number_str = str(a)
elif (number_str[1] != '0'):
a = len(x[div]) + 6 + len(str(x[rem]))
print(x[div] + ' hundred ' + str(x[rem]) + ' is '+ str(a)) # error was here
number_str = str(a)
elif number_str == '1000':
a = 11
print('one thousand is '+ str(a))
number_str = str(a)
return 'four is magic'
def main():
''' The program driver. '''
user_input = input('> ')
while user_input != 'quit':
print(convert(user_input))
user_input = input('> ')
main()
Where I commented #error you were doing recursion which was not what you wanted ( I think). But fixed it and it should work now. When you call recursive functions (calling the same function) it execute the newest call on the stack, returning the value it came back with, which isn't how your program worked.
Also I noticed you weren't calling x[rem] like you were suppose to for a look up on the spelling, fixed that too.
Next time please include desired output instead of making us fish for information.