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.")
有谁知道我的代码出错了?我已经挣扎了几个小时。
答案 0 :(得分:1)
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,所以这些东西中的一些并不是最简单的方法,比如格式化函数,但是学习起来非常有用。
num_to_double = 0
result = 0
print("")
num_to_double = int(input("Enter number would you like to double and press enter."))
while num_to_double > 0:
result = num_to_double * 2
print("2 X {} = {}".format(num_to_double, result))
print("")
num_to_double = int(input("Enter number would you like to double and press enter."))
print("OK< you entered a value <=0, ending execution.")
这段代码是我能对所提供的伪代码做的最接近的代码。在这里使用变量之前声明变量是不必要的并且是混乱的。这就像伪代码并不意味着成为python。与打印空白行相同,应将它们包裹在上一行或下一行打印行中。