Python 编写一个简单的循环程序
我想用这个逻辑写一个程序Python 编写一个简单的循环程序,python,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 您只需要两个whil
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
您只需要两个
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
虽然您应该在遇到问题时展示您在编码解决方案和发布方面的尝试,但您可以执行以下操作:
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\u input
而不是input
)
这将创建一个无限循环,该循环将尝试将输入转换为整数(或打印请求正确输入类型的语句),然后使用逻辑检查
a-b==c
。如果是这样,我们将a
的值设置为这个新值a-b
。否则,我们将重新启动循环。如果不需要无限循环,可以取消对break
命令的注释。您的逻辑正确,可能需要查看while loop
,以及input
。而循环将继续运行,直到满足条件:
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循环的条件。我相信你能做到 那么您想要一个程序,让用户回答2363或
a
减去b
的值,这总是13?如果回答错误,它会不断询问用户,直到回答正确为止。如果正确,它会将a更新为a-13
?所以2363-13=2350
然后下一个循环询问2350-13
是什么?