繁体   English   中英

语法错误python,不知道怎么写代码

[英]Syntax error python, not sure how to write the code

我正在尝试编写一个代码来测试一个单词,看看它是否是一个回文。 它正在工作,但在给出正确答案之前它会循环打印 NO。 我希望它只打印一次正确的答案。

我真的什么都没做,只是在网上查了一些答案

x = str(input("enter the word:"))

w = "" 

for i in x: 
    w = i + w 
    if x == w: 
        print("YES") 
    else:
        print("NO")

它应该打印 YES 或 NO 一次,现在在给出正确答案之前它会打印很多次。

缩进 w= i + w 行

x = str(input("enter the word:"))

w = "" 

for i in x: 

  w = i + w 

if (x==w): 
    print("YES") 
else:
    print("NO")

请更正您的缩进,以便排除故障。

乍一看,您的“if”语句似乎嵌套在您的“for”循环旁边,因此在添加每个字母后检查回文。

如果你把 if else 放在循环中,它必然会多次打印结果。 将它放在循环之外,它只会打印一次。

欢迎来到社区!

一种更短的方法可以是:`

x = str(input("enter the word:"))
if (x==x[::-1]): 
    print("YES") 
else:
    print("NO")

您可能想研究 python 中的字符串切片 :)

Mark B 已经解决了你的问题,但这里有一个额外的方法。

word = input("Enter word")

reverse = word[::-1]

if word == reverse:
    print("Yes, plaindrome")
else:
    print("No, not palindrome")

使用 for 循环创建一个新字符串(字符串 x 的反向)。 在 for 循环之外使用条件。 此外,检查大写条目。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM