打印

Python的基本语法说明

[复制链接]
492|0
手机看帖
扫描二维码
随时随地手机跟帖
跳转到指定楼层
楼主
gaoyang9992006|  楼主 | 2019-1-24 23:14 | 只看该作者 回帖奖励 |倒序浏览 |阅读模式
本帖最后由 gaoyang9992006 于 2019-1-24 23:16 编辑

Here are some samples to help get a better idea of Python's syntax:

Hello World (the traditional first program)


print 'Hello world!'  # Python 2 syntax

# or

print('Hello world!')  # Python 3 syntax

String formatting


name = 'Monty'
print('Hello, %s' % name)  # string interpolation
print('Hello, {}'.format(name))  # string formatting



Defining a function


def add_one(x):
    return x + 1



Testing variable equality


x = 1
y = 2
print 'x is equal to y: %s' % (x == y)
z = 1
print 'x is equal to z: %s' % (x == z)
names = ['Donald', 'Jake', 'Phil']
words = ['Random', 'Words', 'Dogs']
if names == words:
    print 'Names list is equal to words'
else:
    print "Names list isn't equal to words"
new_names = ['Donald', 'Jake', 'Phil']
print 'New names list is equal to names: %s' % (new_names == names)



Defining a class with two methods


class Talker(object):
    def greet(self, name):
        print 'Hello, %s!' % name
    def farewell(self, name):
        print 'Farewell, %s!' % name



Defining a list


dynamic_languages = ['Python', 'Ruby', 'Groovy']
dynamic_languages.append('Lisp')



Defining a dictionary


numbered_words = dict()
numbered_words[2] = 'world'
numbered_words[1] = 'Hello'
numbered_words[3] = '!'



Defining a while loop


while True:
    if value == wanted_value:
        break
    else:
        pass



Defining multiline strings


string = '''This is a string with embedded newlines.
Also known as a tripled-quoted string.
    Whitespace at the beginning of lines is included,
so the above line is indented but the others are not.
'''


Splitting a long string over several lines of source code


string = ('This is a single long, long string'
          ' written over many lines for convenience'
          ' using implicit concatenation to join each'
          ' piece into a single string without extra'
          ' newlines (unless you add them yourself).')



Defining a for loop


for x in xrange(1, 4):
    print ('Hello, new Python user!'
           'This is time number %d') % x



List comprehension


l = [x**2 for x in range(4)]
print(l)
# [0, 1, 4, 9]



Set comprehension with condition


squares = {x**2 for x in [0,2,4] if x < 4}
print(squares)
# {0, 4}


相关帖子

发新帖 我要提问
您需要登录后才可以回帖 登录 | 注册

本版积分规则

认证:西安公路研究院南京院
简介:主要工作从事监控网络与通信网络设计,以及从事基于嵌入式的通信与控制设备研发。擅长单片机嵌入式系统物联网设备开发,音频功放电路开发。

1966

主题

15954

帖子

208

粉丝