如何在这个循环中得到一个双倍的伪码?

2024-09-30 00:30:49 发布

您现在位置:Python中文网/ 问答频道 /正文

pseudocode

numtodouble=int
result=int
print("")

print("Enter a number you would like to double and press Enter.")
input (numtodouble)
<class 'int'>2
'2'
while numtodouble>0:
    result=numtodouble*2
    print("2 X", numtodouble, "=", result)
    print("")
    print("Enter a number you would like to double and press Enter.")
    input(numtodouble)
    break
print("OK, you entered a value <=0, ending execution.")

有人知道我的代码哪里出错了吗?我已经挣扎了好几个小时了。在


Tags: andtoyounumberinputresultlikeint
1条回答
网友
1楼 · 发布于 2024-09-30 00:30:49
try:
    # input is stored as num_to_double. the input is cast to an int, and the string in input is the prompt
    num_to_double = int(input("Enter a number you would like to double and press Enter."))
    while num_to_double>0:
        result=num_to_double*2
        # Format puts the arguments into the curly braces in the order given
        print("2 X {} = {}\n".format(num_to_double, result))
        # input is cast to int and stored in num_to_double. The text in the input command is the prompt
        num_to_double =int(input("Enter a number you would like to double and press Enter."))
    # This is otuside the while loop, so this runs when the while loop breaks. The previous break command was making 
    # the code act not as intended
    print("OK, you entered a value <=0, ending execution.")
# This catches if someone inputs a value that is not able to be cast to a string. It's the second half of the Try: 
# Except block.
except ValueError as _:
    print("A not-a-number was supplied")

这段代码要简单得多,可以完成您要做的事情。我假设您正在学习python,因此其中有些东西并不是最简单的方法,比如format函数,但是它们非常有用。在

^{pr2}$

如果我能做的是最接近伪代码的。在这里使用变量之前声明变量是不必要的,而且很麻烦。就像伪代码不是要变成python一样。与打印空白行相同,这些空白行应包装到上一个或下一个打印行。在

相关问题 更多 >

    热门问题