基础篇(一)
一、中文编码
在python的print()函数中,想要输出中文时,必须添加# -- coding: utf-8 -- 或者#coding=utf-8 在开头,不然无法正确输出中文如:print(“你好!世界”)
二、编码排版
- 在python当中,使用冒号(:)代替c/c++以及java中的{}来区分语句,当然,还要加上缩进。
如:
N=30
for n in range(0,N+1): #语句后面用冒号:代替{}
print(n)
if n%2==0:
print("is even number") # 如此处般缩进
elif n%3==0:
print("is a multiple of 3!")
print("end")*
2.使用分号(;)可以一行放多个语句,如:
print("end");print("finished")
而如果觉得语句过长,可以使用斜杠(\)进行分割,如:
item_1,item_2,item_3=1,2,3
total=item_1 +\
item_2 +\
item_3
print(total) #输出为6 *
- python 中的引号,有单引号,双引号,三个单引号或三个双引号:
word='word'
sentence="this is a sentence"
paragraph1='''这是一个段落1
包含了多个语句'''
paragraph2="""这是一个段落2
包含了多个语句"""
PS.此外,三个单引号或者双引号还可以用于注释多行。如:
'''xxx
xxx
'''
"""
yyy
yyy
"""
三、输入输出
-
input()用于等待用户输入。
input("enter键退出,其他任意键显示...\n")
-
print()输出默认是换行的,但是如过在变量末尾加上逗号,可以实现不换行,如:
x="my name is" y="sakura" print(x,y) 输出为: my name is sakura
-
python的字符串输出
s="abcdefghijk" print(s[0:3]) #输出为abc,最后一位s[3]不输出 print(s[-4:-1]) #从左到右下标为0,1,2,3~n,从右到左是-1,-2,-3.......输出为:hij. 格式是s[-4:-1],不能是s[-1:-4]. print(s[-1:]) # 空的参数表示到尾(头)为止 print (s*2) #星号(*)表示重复操作,这里把s输出两次 print(s+"add string") #加号(+)表示字符串连接运算符号 print(s[0:5:2]) #输出为:ace。三个参数时候,第三位的2表示步长
四、python的列表list[]、元组tuple()、字典dict{}、集合set{}
1.类型对比图:
类型 | 特性 | 例子 |
---|---|---|
list[] | mutable and ordered | list=[‘num’,‘char’,‘str’,‘list’] |
tuple() | immutable and ordered | tuple1=(‘s’,‘p’) ; tuple=(‘num’,‘char’,‘str’,tuple1,list) |
dict{} | mutable and unordered | dict={‘first’:‘1st’,‘second’:‘2nd’,‘third’:‘3rd’} |
set{} | mutable and unordered | set={‘first’,‘second’,‘third’} |
ps.
1.数据可进行嵌套,如list[]和tuple()除了支持字符,数字,字符串,还可以包含list列表/tuple元组(即嵌套)
2.set 无关键字,dict有关键字。且:
print(dict.keys()) #keys()取出全部字典内容,输出为:dict_keys(['first', 'second', 'third'])
print(dict.get('second')) #get()取出指定关键字对应内容,输出为:2nd
—over,第一天的学习到此为止–