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

python3 入门 (一) 基础语法

2015-09-22 18:38 861 查看
1.编码问题

默认情况下,Python 3源码文件以 UTF-8 编码,所有字符串都是 unicode 字符串。 也可以为源码文件指定不同的编码,在文件头部加上:

# coding=gbk

2.关键字

保留字即关键字,Python的标准库提供了一个keyword module,可以输出当前版本的所有关键字:

>>> import keyword
>>> keyword.kwlist

['False', 'None', 'True', 'and', 'as', 'assert', 'break', 'class', 'continue', 'def', 'del', 'elif', 'else', 'except', 'finally', 'for', 'from', 'global', 'if', 'import', 'in', 'is', 'lambda', 'nonlocal', 'not', 'or', 'pass', 'raise', 'return', 'try', 'while', 'with', 'yield']


3.注释

Python中单行注释以#开头,多行注释用三个单引号(''')或者三个双引号(""")将注释括起来。

4.变量

Python中的变量不需要声明。每个变量在使用前都必须赋值,变量赋值以后该变量才会被创建

Python 3支持int、float、bool、complex(复数)。

数值运算:

Python可以同时为多个变量赋值,如a, b = 1, 2。

一个变量可以通过赋值指向不同类型的对象。

数值的除法(/)总是返回一个浮点数,要获取整数使用//操作符。

在混合计算时,Python会把整型转换成为浮点数。

字符串:

python中的字符串str用单引号(' ')或双引号(" ")括起来,同时使用反斜杠(\)转义特殊字符

字符串可以使用 + 运算符串连接在一起,或者用 * 运算符重复

text = 'ice'+' cream'
print(text)

text = 'ice cream '*3
print(text)


使用三引号('''...'''或"""...""")可以指定一个多行字符串

text = '''啦啦啦
喔呵呵呵呵
呵呵你妹'''
print(text)
text = 'ice\
cream'
print(text)


如果不想让反斜杠发生转义,可以在字符串前面添加一个 r 或 R ,表示原始字符串。

如 r"this is a line with \n" 则\n会显示,并不是换行

text1 = r'E:\notice'
text2 = "let's go!"
text3 = r'this is a line with \n'
print(text1)  # E:\notice
print(text2)  # let's go!
print(text3)  # this is a line with \n


字符串有两种索引方式,第一种是从左往右,从0开始依次增加;第二种是从右往左,从-1开始依次减少。

python中没有单独的字符类型,一个字符就是长度为1的字符串

text = 'ice cream'
print(len(text))

print(text[0])  # i
print(text[-9])  # i

print(text[8])  # m
print(text[-1])  # m


python字符串不能被改变。向一个索引位置赋值会导致错误

text = 'ice cream'
text[0] = 't'  # 报错
print(text)


还可以对字符串进行切片,获取一段子串。用冒号分隔两个索引,形式为变量[头下标:尾下标]。

截取的范围是前闭后开的,并且两个索引都可以省略:

text = 'ice cream'
print(text[:3])  # ice
print(text[4:9])  # cream
print(text[4:])  # cream


5.三目运算符

x = 100
y = 200
z = x if x > y else y
print(z)  # 200


6.分支

if-else 语句与其他语言类似,不再赘述

if-elif-else 语句,相当于c或java语言中的if-else if-else :

while True:
score = int(input("Please input your score : "))
if 90 <= score <= 100:
print('A')
elif score >= 80:
print('B')
elif score >= 70:
print('C')
elif score >= 60:
print('D')
else:
print('Your score is too low')


7.循环

while循环语句一般形式:

while 判断条件:

   statements

import random

print("hello world!\n")
number = random.randint(1, 10)
temp = input("Please input a number : ")
i = int(temp)

while i != number:
print("wrong...")
if i < number:
print("required a bigger number")
else:
print("required a smaller number")
temp = input("Please input a number : ")
i = int(temp)

print("yes...")


for循环的一般格式如下:

for <variable> in <sequence>:

  <statements>

else:

  <statements>

languaegs = ['C','c++','java','python']
for language in languaegs:
print(language, len(language))


循环语句可以有else子句

它在穷尽列表(以for循环)或条件变为假(以while循环)循环终止时被执行

但循环被break终止时不执行.如下查寻质数的循环例子

for num in range(2, 10):
for x in range(2, num):
if num%x == 0:
print(num, 'equals', x, '*', num//x)
break
else:
# 循环中没有找到元素
print(num, 'is a prime number')


如果需要遍历数字序列,可以使用内置range()函数:

# range()函数,含头不含尾
# 0~4
for i in range(5):
print(i)

# 2~7
for i in range(2, 8):
print(i)

# 1~9 步长为3
for i in range(1, 10, 3):
print(i)


range()函数与for循环结合:

languaegs = ['c','c++','java','python']
for i in range(len(languaegs)):
print(i, ':', languaegs[i])
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: