简体   繁体   English

为什么我的代码(Python 加减法)不起作用?

[英]Why my code (Python adding and subtracting) does not work?

Here is what I need coded:这是我需要编码的内容:

  • Detect user input for the words: "add" and "sub" aka subtraction.检测用户输入的单词:“add”和“sub”,也就是减法。
  • If the wrong answer is given, it should re-ask the question.如果给出错误的答案,它应该重新提问。
  • If the user chooses either, it should generate two numbers from 1-9, number 1 >= number 2, and the user should be asked the answer.如果用户选择其中之一,它应该从 1-9 生成两个数字,数字 1 >= 数字 2,并且应该询问用户答案。
  • If the answer is correct, it should move to the next round (our teacher said there must be 5 rounds, at each end of the round the code should ask the user to type "add" or "sub" again.如果答案是正确的,它应该进入下一轮(我们的老师说必须有5轮,在每一轮结束时,代码应该要求用户再次输入“add”或“sub”。
  • If the user gives the wrong answer, it should re-ask the question.如果用户给出了错误的答案,它应该重新提问。
  • The code ends when all 5 rounds are done, or if the user types "end" at any time with a message saying "Goodbye".代码在所有 5 轮完成后结束,或者如果用户在任何时候键入“end”并显示“Goodbye”消息。

My code is:我的代码是:

import random

i = 1
while i < 6:
    answer1 = input("Hello, please type \"add\" for adding, or \"sub\" for subtracting")

    first_number = random.randrange(1, 9)
    second_number = random.randrange(1, first_number)
    one = str(first_number)
    two = str(second_number)

    if answer1 == "add":
        the_answer = first_number + second_number
        the_answer_actual = str(the_answer)
        user_answer = int(input(one + " + " + two + " = "))
        if the_answer == user_answer:
            print("The answer is correct!")
            i += 1
        elif the_answer != user_answer:
            print("Wrong answer. The correct answer was " + the_answer_actual)
            i += 1
        else:
            continue

    elif answer1 == "sub":
        the_answer = first_number - second_number
        the_answer_actual = str(the_answer)
        user_answer = int(input(one + " - " + two + " = "))
        if the_answer == user_answer:
            print("The answer is correct!")
            i += 1
        elif the_answer != user_answer:
            print("Wrong answer. The correct answer was " + the_answer_actual)
            i += 1
        else:
            continue

    elif answer1 == "end" or i < 6:
        print("Goodbye.")
        break

    else:
        pass

======================================================================== Problem: This error code appears when the 5th round is over: ==================================================== ====================== 问题:第5轮结束时出现此错误代码:

  • Traceback (most recent call last): -File "C:\Users\kingh\PycharmProjects\pythonProject\main.py", line 8, in Traceback(最近一次调用最后):-File "C:\Users\kingh\PycharmProjects\pythonProject\main.py",第 8 行,在
    • second_number = random.randrange(1, first_number) second_number = random.randrange(1, first_number)
    • File "C:\Users\kingh\AppData\Local\Programs\Python\Python39\lib\random.py", line 316, in randrange文件“C:\Users\kingh\AppData\Local\Programs\Python\Python39\lib\random.py”,第 316 行,位于 randrange
      • raise ValueError("empty range for randrange() (%d, %d, %d)" % (istart, istop, width)) ValueError: empty range for randrange() (1, 1, 0) raise ValueError("empty range for randrange() (%d, %d, %d)" % (istart, istop, width)) ValueError: empty range for randrange() (1, 1, 0)

You just need to convert the answer to an integer before comparing it:您只需在比较之前将答案转换为 integer :

if answer2 == int(user_answer):

and then it works perfectly (naturally you must do it for subtraction as well)然后它完美地工作(当然你也必须做减法)

EDIT: and you need to add a break after the correct answer编辑:你需要在正确答案后添加一个休息

print("The answer is correct!")
break

You need to do this in both add and sub as it doesn't work in either:您需要在 add 和 sub 中执行此操作,因为它在任何一个中都不起作用:

if str(answer2) == useranswer:

or或者

useranswer = int(input("..."))

as else you will be comparing a string with an int which will never work.否则,您会将字符串与永远不会工作的 int 进行比较。 the first solution converts the number you calculated to a string, the second solution converts the input you get from the user to an int.第一个解决方案将您计算的数字转换为字符串,第二个解决方案将您从用户获得的输入转换为 int。 Both work, but you cannot compare a String with an int.两者都有效,但您不能将 String 与 int 进行比较。

If you want to do more comparisons with the userinput (like checking if the result was bigger/lower than what you entered) i would reccomend the first solution, as you will alwats have the userinput as an int until you compare it.如果您想与用户输入进行更多比较(例如检查结果是否大于/小于您输入的内容),我会推荐第一个解决方案,因为您将始终将用户输入作为 int 进行比较,直到您进行比较。

You might need to use if ans2 == user_answer: instead of if answer2 == user_answer: since it is a string comparison.您可能需要使用if ans2 == user_answer:而不是if answer2 == user_answer:因为它是字符串比较。

EDIT: You might also want to use i += 1 instead to make sure it stops after the specified number of iterations.编辑:您可能还想使用i += 1来确保它在指定的迭代次数后停止。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM