gpt4 book ai didi

python - Python 2 中的嵌套 while 循环

转载 作者:行者123 更新时间:2023-12-01 05:33:37 25 4
gpt4 key购买 nike

这来自《Python 计算和编程简介》中的手指练习 3.1。

Write a program that asks the user to input an integer and prints two integers, root and pwr, such that 0 < pwr < 6 and root**pwr is equal to the integer entered by the entered. If no such pair of integers exists, it should print a message to that effect.

我已经非常接近了,部分归功于 Stack Overflow 中的一些建议。但没有人完全做到这一点,部分原因是练习的重点是使用嵌套的 While 循环,而不是 For 循环或任何其他比这更复杂的循环。这是一个详尽的枚举练习。

我真的很接近。这是我到目前为止所拥有的:

num = int(raw_input('Enter a positive integer: '))
power = 0
root = 0
while power < 6:
if root ** power == num:
break
power += 1
root= 0
while root ** power < num:
root += 1

if root**power == num:
print('Root = ' + str(root) + ' and power = ' + str(power))
else:
print('No pair of integers exist such that one has an exponent that is between 1 and 6')

这里只有两个问题:我必须运行检查来查看 root 和 power 是否等于用户输入,这感觉没有必要。想知道如何使其更清洁。

当用户输入 1 时也是如此对于输入,程序输出 Root 0 and Power 0这超出了练习的参数范围。

最佳答案

Was wondering how to make that cleaner.

简单。您可以将其折叠到一行,然后转动

while power < 6:
if root ** power == num:
break

进入

while (power < 6) and (root ** power != num):

(括号是不必要的,但我发现它有助于可读性。)

关于python - Python 2 中的嵌套 while 循环,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19624130/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com