您的位置:首页 > 编程语言 > Python开发

Python基础语法

2017-06-01 17:35 197 查看
#coding:utf-8

print 'HelloWorld'

i = 5
print i
i = i + 1
print i
#python 中字符串有单引号、双引号及三引号,单引号与双引号没有区别
s = '''This is a multi-line string.
This is the second line.'''
print s

#标识符命名:区分大小写、能包含字母、数字、下划线,只允许字母与下滑线开头
#使用变量时只需要给它们赋一个值。不需要声明或定义数据类型。
'''运算符:
1. 'la' * 3得到'lalala';
2. 3 ** 4得到81(即3 * 3 * 3 * 3)
3. 逻辑非使用not, x = True; not y返回False。注意:True与False均大写
'''
#python使用缩进区分程序块,同一层次的语句必须有相同的缩进。每一组这样的语句称为一个块。
#在Python中没有switch语句。你可以使用if..elif..else语句来完成同样的工作(在某些场合,使用字典会更加快捷。)
#while与if语句
number = 23
running = True
while running:
guess = int(raw_input('Enter an integer : '))
if guess == number:
print 'Congratulations, you guessed it.' # New block starts here
print "(but you do not win any prizes!)" # New block ends here
running = False
elif guess < number:
print 'No, it is a little higher than that' # Another block
# You can do whatever you want in a block ...
else:
print 'No, it is a little lower than that'
# you must have guess > number to reach here
else:
print 'The while loop is over.'
print 'Done'
# This last statement is always executed, after the if statement is executed

#for语句
for i in range(1, 5):   #[1,5),默认步长为1
print i
else:
print 'The for loop is over'

#函数的定义
def func():
global x        #global语句:函数内定义的变量为局部变量,使用全局变量要用global申明
print 'x is', x
x = 2
print 'Changed local x to', x

x = 50
func()
print 'Value of x is', x

#文档字符串,docstrings
#文档字符串的惯例是一个多行字符串,它的首行以大写字母开始,句号结尾。第二行是空行,从第三行开始是详细的描述。
def printMax(x, y):
'''Prints the maximum of two numbers.

The two values must be integers.'''
x = int(x) # convert to integers, if possible
y = int(y)
if x > y:
print x, 'is maximum'
else:
print y, 'is maximum'

printMax(3, 5)
print printMax.__doc__


import与from .. import

# Filename: mymodule.py
def sayhi():
print 'Hi, this is mymodule speaking.'
version = '0.1'
# End of mymodule.py


使用import调用

# Filename: mymodule_demo.py
import mymodule
mymodule.sayhi()
print 'Version', mymodule.version


使用from .. import

# Filename: mymodule_demo2.py
from mymodule import sayhi, version
# Alternative:
# from mymodule import *
sayhi()
print 'Version', version


一般说来,应该避免使用from..import而使用import语句,因为这样可以使你的程序更加易读,也可以避免名称的冲突。

Python列表

# This is my shopping list
shoplist = ['apple', 'mango', 'carrot', 'banana']
print 'I have', len(shoplist),'items to purchase.'
print 'These items are:', # Notice the comma at end of the line
for item in shoplist:
print item,         #使用一个 逗号 来消除每个print语句自动打印的换行符
print '\nI also have to buy rice.'
shoplist.append('rice')
print 'My shopping list is now', shoplist
print 'I will sort my list now'
shoplist.sort()
print 'Sorted shopping list is', shoplist
print 'The first item I will buy is', shoplist[0]
olditem = shoplist[0]   #Python从0开始计数
del shoplist[0]         #列表是可变的,而字符串是不可变的 。
print 'I bought the', olditem
print 'My shopping list is now', shoplist


Python元组

元组和列表十分类似,只不过元组和字符串一样是 不可变的 即你不能修改元组。元组通过圆括号中用逗号分割的项目定义。元组通常用在使语句或用户定义的函数能够安全地采用一组值的时候,即被使用的元组的值不会改变。

zoo = ('wolf', 'elephant', 'penguin')
print 'Number of animals in the zoo is', len(zoo)
new_zoo = ('monkey', 'dolphin', zoo)
print 'Number of animals in the new zoo is', len(new_zoo)
print 'All animals in new zoo are', new_zoo
print 'Animals brought from old zoo are', new_zoo[2]
print 'Last animal brought from old zoo is', new_zoo[2][2]

age = 22
name = 'Swaroop'
print '%s is %d years old' % (name, age)
print 'Why is %s playing with that python?' % name  #单项才能省略括号


一个空的元组由一对空的圆括号组成,如myempty = ()。然而,含有单个元素的元组就不那么简单了。你必须在第一个(唯一一个)项目后跟一个逗号,这样Python才能区分元组和表达式中一个带圆括号的对象。即如果你想要的是一个包含项目2的元组的时候,你应该指明singleton = (2 , )。

# 'ab' is short for 'a'ddress'b'ook
ab = { 'Swaroop' : 'swaroopch@byteofpython.info',
'Larry' : 'larry@wall.org',
'Matsumoto' : 'matz@ruby-lang.org',
'Spammer' : 'spammer@hotmail.com'
}
print "Swaroop's address is %s" % ab['Swaroop']
# Adding a key/value pair
ab['Guido'] = 'guido@python.org'
# Deleting a key/value pair
del ab['Spammer']
print '\nThere are %d contacts in the address-book\n' % len(ab)
for name, address in ab.items():
print 'Contact %s at %s' % (name, address)
if 'Guido' in ab: # OR ab.has_key('Guido')
print "\nGuido's address is %s" % ab['Guido']
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  python