我的while循环执行,但输出不是预期的。为什么?

2024-09-30 22:19:32 发布

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

我是python初学者,我编写了以下代码:

print("This is a program to print squares, cubes, etc. table.")
num = int(input("Enter a number to square, cube, etc. : "))

i = 0

while i<10:
    numpow = 1
    c = num^ numpow
    print(f"{num} to the power of {numpow} is {c}")
    numpow = 1 + numpow
    i += 1

输出为:

This is a program to print squares, cubes, etc. table.
Enter a number to square, cube, etc. : 3
3 to the power of 1 is 2
3 to the power of 1 is 2
3 to the power of 1 is 2
3 to the power of 1 is 2
3 to the power of 1 is 2
3 to the power of 1 is 2
3 to the power of 1 is 2
3 to the power of 1 is 2
3 to the power of 1 is 2
3 to the power of 1 is 2

但这不是预期的产出。我希望输出如下所示:

This is a program to print squares, cubes, etc. table.
Enter a number to square, cube, etc. : 3
3 to the power of 1 is 3
3 to the power of 2 is 9
3 to the power of 3 is 27
3 to the power of 4 is 81
3 to the power of 5 is 243
3 to the power of 6 is 729
3 to the power of 7 is 2187
3 to the power of 8 is 6561
3 to the power of 9 is 19683
3 to the power of 10 is 59049

为什么?

因为你知道我是一个初学者,所以我花了1/2个小时来研究它,但没有找到解决方案。我厌倦了


Tags: ofthetoistableetcthisprogram
3条回答

只是为了好玩,也来看看这个:

print("This is a program to print squares, cubes, etc. table.")
num = int(input("Enter a number to square, cube, etc. : "))

for numpow in range(1,11):
    c = num**numpow
    print(f"{num} to the power of {numpow} is {c}")
while i<10:
    numpow = 1

对于每个迭代,将numpow指定给1。 要修复错误,请将其更改为:

numpow = 1
while i<10:
    

似乎您还需要使用**而不是^

您的代码中有两个错误,您会在下面的代码中注意到:

i = 0

while i<10:
    numpow = i
    c = num** numpow
    print(f"{num} to the power of {numpow} is {c}")
    i += 1

相关问题 更多 >