【问题标题】:Can't break a Palindrome loop in Python无法打破 Python 中的回文循环
【发布时间】:2023-03-03 23:25:01
【问题描述】:

我只是一个使用 Python 的初学者,并且已经创建了代码来打印 1-1000 范围内的所有回文数。然而,在我的 print 语句之后,代码只是不断地循环和打印从 1 到 99 的数字。我试过使用 break;在 print(i) 语句之后,但它会导致控制台在循环中打印 1 和 *Palindromes 而不是回文数。有什么打破循环的建议吗?`

    pi = 3.14159
area = 0

def areaSquare(squareWidth):
    return squareWidth * squareWidth

def areaCircle(radius):
    return pi *(radius * radius)

   
def menu():     #Creat the menu for user to see
    print("\nCalculations")
    print("1. Calculate area of a square\n2. Calculate the area of a circle\n3. Display palindromes up to 1,000\n4. Exit programme.")


menu()  # call the menu
option = int(input("Enter an option: "))

while option != 4:   #create a loop
    if option == 1:
            print("***Area of a square***") 
            squareWidth = float(input("Enter width of square(cm): "))
            print("The area of the square of width ",squareWidth, "cm = ", areaSquare(squareWidth), "cm squared")
            menu()
            option = int(input("Enter an option: "))
    elif option == 2:
            print("***Area of a circle***");
            radius = float(input("Enter radius of circle(cm): "))
            print("The area of a circle of " , radius , "cm = ", areaCircle(radius), " round")
            menu()
            option = int(input("Enter an option: "))
    elif option == 3:
           for i in range(1, 1000): 
              if str(i) == str(i)[::-1]:
                  print(i,)
    else:   
        print("Invlid entry, please select a number between 1 and 4.")

        menu()
        option = int(input("Enter an option: "))     

print("Goodbye!")  

【问题讨论】:

  • 如果您只是从for i in range(1, 1000): 行中删除缩进,它就可以正常工作。请分享您获得的输出的屏幕截图。
  • 对我来说,它也适用于适当的缩进。我建议将最后两行中的str(i) 和i 分别替换为n。

标签: python for-loop palindrome


【解决方案1】:

Python 3

print("**Palindromes***");
for i in range(1, 1000): 
    if str(i) == str(i)[::-1]:
        print(i,)

Try it online!

这应该可以解决问题。我认为您有一个导致代码缩进的外部循环,这就是您的循环没有中断的原因。

【讨论】:

  • 啊,是的,可能是外部while循环?这是完整的代码
  • @CherylO'Hagan 如果我的回答解决了您的问题,您能否接受并关闭此问题?谢谢:)
【解决方案2】:

谢谢大家。我将 while 循环更改为 if 语句,并且能够让循环中断!

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-03-28
    • 2014-02-06
    • 2013-03-08
    • 1970-01-01
    • 2022-10-24
    • 1970-01-01
    • 1970-01-01
    • 2021-08-29
    相关资源
    最近更新 更多