2014-01-27 106 views
-3

我使用了一本书所以这段代码是从书 我需要它,从蟒蛇2.5〜3.3我如何转换这个Python代码?

my_name = 'Zed A. Shaw' 

my_age = 35 

my_height = 75 

my_weight = 180 

my_eyes = 'Blue' 

my_teeth = 'White' 

my_hair = 'Brown' 



print "Let ' s talk about %s." % my_name 

print "He ' s %d inches tall." % my_height 

print "He ' s %d pounds heavy." % my_weight 

print "He 's got %s eyes and %s hair." % (my_eyes, my_hair) 

print "His teeth are usually %s depending on the coffe." % my_teeth 
+2

这个问题似乎是脱离主题,因为它是关于基本的Python语法。 – iCodez

回答

1

您需要使用print作为一个内置功能:

print("Let ' s talk about %s." % my_name) # Note the parenthesis 

另外,如果你是移动到Python 3.x的,你应该养成使用str.format代替%的习惯:

print("Let ' s talk about {}.".format(my_name)) 

虽然%仍然有效,str.format是现代/首选的字符串格式化方式。


总而言之,你的代码应该是这样的:

my_name = 'Zed A. Shaw' 

my_age = 35 

my_height = 75 

my_weight = 180 

my_eyes = 'Blue' 

my_teeth = 'White' 

my_hair = 'Brown' 



print("Let ' s talk about {}.".format(my_name)) 

print("He ' s {} inches tall.".format(my_height)) 

print("He ' s {} pounds heavy.".format(my_weight)) 

print("He 's got {} eyes and {} hair.".format(my_eyes, my_hair)) 

print("His teeth are usually {} depending on the coffee.".format(my_teeth)) 
+0

这应该在2.x和3.x上运行,顺便说一句。 – dstromberg

0

打开print "foo"print("foo")

1

2to3可以处理基本语法转换,如这一点,并会产生正确的结果你的脚本的情况。我强烈建议你使用它。

假设你的文件名是“foo.py”,那么你就可以运行这个命令来产生正确的Python 3语法:

2to3 -w foo.py 

值得一提的是,格式化是遗留在Python 3,但它仍然有效;我建议您尽早将它转换为more widely accepted form