Python2.7 基本语法,,1.关键字Pytho
Python2.7 基本语法,,1.关键字Pytho
1.关键字
Python标准库提供了keyword module,可以输出当前版本的所有关键字:
>>> import keyword>>> keyword.kwlist[‘and‘, ‘as‘, ‘assert‘, ‘break‘, ‘class‘, ‘continue‘, ‘def‘, ‘del‘, ‘elif‘, ‘else‘, ‘except‘, ‘exec‘, ‘finally‘, ‘for‘, ‘from‘, ‘global‘, ‘if‘, ‘import‘, ‘in‘, ‘is‘, ‘lambda‘, ‘not‘, ‘or‘, ‘pass‘, ‘print‘, ‘raise‘, ‘return‘, ‘try‘, ‘while‘, ‘with‘, ‘yield‘]>>>
2.注释:
单行注释用#,多行注释用‘‘‘或者"""
3.变量:
Python中的变量不需要声明。每个变量在使用前都必须赋值,变量赋值以后该变量才会被创建
Python可以同时为多个变量赋值,如a, b = 1, 2。数值的除法(/)总是返回一个浮点数,要获取整数使用//操作符。一个变量可以通过赋值指向不同类型的对象。在混合计算时,Python会把整型转换成为浮点数4.字符串:
python中的字符串str用单引号(‘ ‘)或双引号(" ")括起来,
使用反斜杠(\)转义特殊字符
字符串可以使用 + 运算符串连接在一起,或者用 * 运算符重复
>>> text=‘ice‘+‘ cream‘>>> print(text)ice cream>>> text=‘ice cream‘*3>>> print(text)ice creamice creamice cream>>>
使用三引号(‘‘‘...‘‘‘或"""...""")可以指定一个多行字符串
>>> text = ‘‘‘aaabbbccc‘‘‘>>> print(text)aaabbbccc>>>
>>> text=‘iccecream‘>>> print(text)iccecream>>>
如果不想让反斜杠发生转义,可以在字符串前面添加一个 r 或 R,表示原始字符串。
>>> text1 = r‘E:\notice‘>>> print text1E:\notice
python字符串不能被改变。向一个索引位置赋值会导致错误
>>> text=‘ice cream‘>>> text[0]=‘t‘Traceback (most recent call last): File "<pyshell#117>", line 1, in <module> text[0]=‘t‘TypeError: ‘str‘ object does not support item assignment
5:三目运算符
>>> x=100>>> y=200>>> z=x if x>y else y>>> print(z)200>>>
6.分支
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.循环
for循环的一般格式如下:
for<variable>in<sequence>:
<statements>
else:
<statements>
>>> languaegs = [‘C‘,‘c++‘,‘java‘,‘python‘]>>> for language in languaegs: print(language, len(language)) (‘C‘, 1)(‘c++‘, 3)(‘java‘, 4)(‘python‘, 6)>>>
循环语句可以有else子句
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‘)
待续...
Python2.7 基本语法
相关内容
- 暂无相关文章
评论关闭