编写一个简单的循环程序

时间:2016-09-27 15:23:03

标签: python

我想用这种逻辑编写一个程序。

A value is presented of the user.
Commence a loop
    Wait for user input
    If the user enters the displayed value less 13 then
       Display the value entered by the user and go to top of loop.
    Otherwise exit the loop

3 个答案:

答案 0 :(得分:0)

您只需要两个while循环。一个让主程序永远持续下去,另一个在答案错误时打破并重置a的值。

while True:
    a = 2363
    not_wrong = True

    while not_wrong:
        their_response = int(raw_input("What is the value of {} - 13?".format(a)))
        if their_response == (a - 13):
            a = a -13
        else:
            not_wrong = False

答案 1 :(得分:0)

虽然您应该展示您尝试编写解决方案并在遇到问题时发布,但您可以执行以下操作:

a = 2363
b = 13
while True:
    try:
        c = int(input('Subtract {0} from {1}: '.format(b, a))
    except ValueError:
        print('Please enter an integer.')
        continue

    if a-b == c:
        a = a-b
    else:
        print('Incorrect. Restarting...')
        a = 2363
        # break

(如果您使用的是Python2,请使用raw_input代替input

这会创建一个无限循环,尝试将输入转换为整数(或打印声明请求正确的输入类型),然后使用逻辑来检查是否a-b == c。如果是,我们会将a的值设置为此新值a-b。否则,我们重启循环。如果您不想要无限循环,可以取消注释break命令。

答案 2 :(得分:0)

您的逻辑是正确的,可能需要查看while loopinput。虽然循环一直持续到满足条件:

while (condition):
    # will keep doing something here until condition is met

while循环的示例:

x = 10
while x >= 0:
    x -= 1
    print(x)

这将打印x直到它达到0,因此在控制台的新行中输出将为9 8 7 6 5 4 3 2 1 0。

input允许用户从控制台输入内容:

x = input("Enter your answer: ")

这将提示用户输入你的答案:"并存储用户输入变量x的值。 (变量意味着像容器或盒子)

将所有内容放在一起,你会得到类似的东西:

a = 2363              #change to what you want to start with
b = 13                #change to minus from a

while a-b > 0:        #keeps going until if a-b is a negative number
    print("%d - %d = ?" %(a, b))                      #asks the question
    user_input = int(input("Enter your answer: "))    #gets a user input and change it from string type to int type so we can compare it
    if (a-b) == user_input:         #compares the answer to our answer
        print("Correct answer!") 
        a -= b                      #changes a to be new value
    else:
        print("Wrong answer") 

print("All done!")

现在这个程序在a = 7停止,因为我不知道你是否想继续使用负数。如果你刚刚编辑了while循环的条件。我相信你能做到的。

相关问题