在Python中运行else/if语句时遇到问题

2024-04-23 19:51:12 发布

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

我对Python还很陌生,我正试图利用各种在线资源教会自己一些东西。在WIkipedia关于算法的文章中,有一个BASIC程序示例;我决定尝试使用Python编写相同的程序,但是我在if/else语句的语法方面遇到了问题。我很确定这是一个基本的格式化问题,但我没有足够的编码经验来理解我做错了什么。以下代码块:

# Euclid's algorithm for greatest common divisor

print "Euclid's algorithm for greatest common divisor"

print "Type two integers greater than 0"
("\n")
("\a")

# Gather input from user in the form of a string. 

("\n")
a = raw_input("Integer 1? ")
("\n")
b = raw_input("Integer 2? ")
("\n")

# Calculate equalities.

if b = 0:
    print a

elif a > b:
a = a - b
print a

b = b - a

if b = 0:
print a

返回错误:

^{pr2}$

我意识到整个模块是不完整的,但我想在继续下一部分之前,先弄清楚我在这一部分做得有什么不对。在


Tags: 程序利用forinputrawifintegercommon
3条回答

两个问题:

if b = 0: # this is assignment; you want == which is comparison
    print a

elif a > b:
a = a - b # this needs to be indented just like the print under the if clause

您正在使用赋值来测试是否相等。使用两个符号:

if b == 0:

b = 0是赋值语句,不能在其他语句内使用语句;b == 0测试b是否等于0。在

  1. =是赋值(如x=4,意思是set x=4)。==是相等性检查。你想要==。在
  2. python需要缩进。在

因此

if True:
print 'happy'`

是语法错误,而

^{pr2}$

没事的。在

  1. 严格地说,这不是语法错误,但是代码中的("\n")语句是为了什么?现在他们什么都不做。在

相关问题 更多 >