Skip to main content
 首页 » 编程设计

python之开始 Python : For Loop- what do to afterwards

2024年10月17日7powertoolsteam

在网上的教科书上找到了这个练习,我正在努力通过它。我相信他们打算用 while 循环来回答它,但我使用的是 for 循环,这可能是我的问题。

“编写一个程序,提示用户输入一个整数并返回两个整数pwr和root,使得0 < pwr < 6 和root**pwr 相等到用户输入的整数。如果不存在这样的整数对,它应该打印“不存在这样的整数。”

我如何测试以查看是否有任何 # 符合条件,如果没有,请说出来?

u_i = int(input("input a #:")) 
root = u_i**.5 
 
for pwr in range(1,6): 
    ans = root**pwr 
 
    if ans == u_i: 
        print(pwr) 
        print(int(root)) 
#here is where the problem comes in as it will do this every time and I'm\ failing to discover what I should do instead. 
if ans!= u_i: 
    print("No such integer exists") 

完全披露:自从我上一节数学课以来已经有很长一段时间了,所以我不相信我的“解决方案”对于问题的要求是否正确。然而,我更感兴趣的是解决我面临的困境,因为我正在尝试正确使用循环。

请您参考如下方法:

你想检查是否有一个整数 root 使得 root ** pwr == user_input。通过一些数学运算,我们可以将上面的语句重写为 root = user_input ** (1./pwr)。您只有很少的 pwr 值可供选择,因此您可以简单地遍历这些值(看起来您已经弄清楚了那部分)。您需要做的最后一件事是(对于每个 pwr)检查 root 是否是一个整数,您可以使用 root % 1 == 0 或 int(root) == root。

如果你想看起来“花哨”,你可以使用 python 的 for ... else 语法。 for 循环中的 else block 只有在循环没有中断的情况下才会执行。例如:

def has_dogs(pets): 
    # This functions check to see if "dog" is one of the pets 
    for p in pets: 
        if p == "dog": 
            print "found a dog!" 
            break 
    else: 
        # This block only gets run if the loop finishes  
        # without hitting "break" 
        print "did not find any dogs :(" 

for ... else 语法基本上是一种奇特的方式来做到这一点:

def has_dogs(pets): 
    # This functions check to see if "dog" is one of the pets 
    dog_found = False 
    for p in pets: 
        if p == "dog": 
            print "found a dog!" 
            dog_found = True 
            break 
    if not dog_found: 
        print "did not find any dogs :("