python入门
一、简介
1、Python
Python是一种高级的、简单的、解释性的、通用的和动态的编程语言,它支持面向对象的编程方法。与其他语言(如C、C++或Java )相比,它易于学习,其优雅的语法允许程序员用更少的代码行表达概念。
Python是一种独立于平台的语言,用它编写的程序可以在任何操作系统上运行。
Python是解释性的编程语言,这意味着代码可以逐行执行。
Python是动态类型的,不需要声明变量的数据类型。
2、PyCharm
PyCharm是一种Python IDE,是一个面向Python程序员的集成开发环境。
3、Hello World
print("Hello World")
name = input("please enter your name:")
print("Hello", name)
输出:
Hello World
please enter your name:albert
Hello albert
二、语法
1、数据类型
python中有五种数据类型:数字、字典、布尔、集合、序列类型,可以使用type()
函数来检查变量的数据类型:
a = False
b = 5
c = 2.3
d = 'Hello Python'
e = ['a', 2, True]
f = ('Hello', 'World', 0)
g = {'name': 'Jim', 'sex': 'male'}
h = set()
print(type(a))
print(type(b))
print(type(c))
print(type(d))
print(type(e))
print(type(f))
print(type(g))
print(type(h))
输出:
<class 'bool'>
<class 'int'>
<class 'float'>
<class 'str'>
<class 'list'>
<class 'tuple'>
<class 'dict'>
<class 'set'>
2、条件语句
- if
n = int(input("Enter the number:"))
if n % 2== 0:
print("The number is even")
else:
print("The number is odd")
输出:
Enter the number:5
The number is odd
- elif
time = int(input("Enter the time: "))
if time >= 6 and time <= 12:
print("Good Morning")
elif time > 12 and time <= 18:
print("Good Afternoon")
elif time > 18 and time <= 24:
print("Good Evening")
else:
print("Hello!")
输出:
Enter the time: 20
Good Evening
3、循环语句
- for
list = ['a', 'b', 'c', 'd']
for x in list:
print(x)
输出:
a
b
c
d
for i in range(5, 10):
print(i, i*2)
输出:
5 10
6 12
7 14
8 16
9 18
- while
i = 0
while i < 5:
print(i)
i += 1
输出:
0
1
2
3
4
num = 1
while num <= 3:
print(num)
num = num + 1
else:
print("finished")
输出:
1
2
3
finished
4、字符串
name = 'python'
print(name[0], name[1], name[2], name[3], name[4], name[5])
print(name[-1], name[-2], name[-3], name[-4], name[-5], name[-6])
print(name[0:])
print(name[:6])
print(name[1:2])
print('th' in name)
print('java' not in name)
print('Hello %s' % name)
输出:
p y t h o n
n o h t y p
python
python
y
True
True
Hello python
5、正则表达式
import re
sentence = 'Python is a very popular programming language. Python has easy syntax.'
print(re.findall('Python', sentence))
x = re.search('\s', sentence)
print('The first white-space character is placed in position:', x.start())
matches = re.search('(popular)', sentence)
print(matches.span())
print(matches.group(1))
print(matches.string)
ret = re.split('\s', sentence)
print(ret)
# substitution
ret = re.sub('\s', '-', sentence)
print(ret)
输出:
['Python', 'Python']
The first white-space character is placed in position: 6
(17, 24)
popular
Python is a very popular programming language. Python has easy syntax.
['Python', 'is', 'a', 'very', 'popular', 'programming', 'language.', 'Python', 'has', 'easy', 'syntax.']
Python-is-a-very-popular-programming-language.-Python-has-easy-syntax.
6、列表
list = ['a', 'b', 'c', 'd', 'e', 'f']
print(list[:3])
print(list[3:])
print(list[1:-1])
print('c' in list)
#step:2
print(list[::2])
print(list[3:6:2])
#repetition
print(list*2)
#concatenation
list1 = [1, 2, 3]
list2 = [4, 5, 6]
print(list1 + list2)
print()
for i in list1:
print(i)
输出:
['a', 'b', 'c']
['d', 'e', 'f']
['b', 'c', 'd', 'e']
True
['a', 'c', 'e']
['d', 'f']
['a', 'b', 'c', 'd', 'e', 'f', 'a', 'b', 'c', 'd', 'e', 'f']
[1, 2, 3, 4, 5, 6]
1
2
3
7、元组
tupleVal = (3, 1, 2, 3, 2, 6, 5, 4, 4, 5, 3, 7, 3)
print("tuple: ", tupleVal)
occureneces = tupleVal.count(3)
print("The item '3' occured ", occureneces, " times")
index = tupleVal.index(5)
print("The index value of '5' is ", index)
输出:
tuple: (3, 1, 2, 3, 2, 6, 5, 4, 4, 5, 3, 7, 3)
The item '3' occured 4 times
The index value of '5' is 6
8、集合
# empty set
A = set()
# initializing the set B
B = {"a", "c", "d", "f"}
A.add("apple")
A.add("banana")
print(A)
B.add("x")
B.add("y")
print(B)
A.clear()
print(A)
set1 = {'a', 'p', 'b', 'd', 'e'}
set2 = {'a', 'b'}
print('set1 is a superset for set2: ', set1.issuperset(set2))
print('set2 is a subset for set1: ', set2.issubset(set1))
set3 = {'a', 'x', 'w', 'p'}
print('intersection between set1 and set3: ', set1.intersection(set3))
print('the union of set1 and set3: ', set1.union(set3))
# remove方法在移除时如果元素不存在,则会发生错误
set3.discard('p')
print(set3)
x = set3.pop()
print(x)
print(set3)
输出:
{'apple', 'banana'}
{'c', 'y', 'f', 'd', 'a', 'x'}
set()
set1 is a superset for set2: True
set2 is a subset for set1: True
intersection between set1 and set3: {'a', 'p'}
the union of set1 and set3: {'b', 'w', 'd', 'a', 'e', 'x', 'p'}
{'a', 'w', 'x'}
a
{'w', 'x'}
9、字典
emptyDict = dict()
emptyDict = {}
student = {'name': 'Tom', 'age': 22, 'sex': 'male'}
print(type(student))
print(len(student))
print(student['name'], student['sex'], student.get('age'))
del student['sex']
print(student)
print(len(student))
student.clear()
print(student)
输出:
<class 'dict'>
3
Tom male 22
{'name': 'Tom', 'age': 22}
2
{}
10、函数
def hello(name):
print("hello", name)
hello('albert')
def sum(a, b):
return a + b
s = sum(1, 2)
print('1 + 2 = ', s)
输出:
hello albert
1 + 2 = 3
11、类
class People:
def __init__(self, name, age, sex):
self.name = name
self.age = age
self.sex = sex
def speak(self):
print("I'm %s, I am %s years old." % (self.name, self.age))
p = People('Lucy', 28, 'female')
p.speak()
# 继承
class Student(People):
def __init__(self, name, age, sex, school):
People.__init__(self, name, age, sex)
self.school = school
def speak(self):
People.speak(self)
print("I am studying in %s school" % self.school)
s = Student('Jack', 33, 'male', 'Boston University')
s.speak()
输出:
I'm Lucy, I am 28 years old.
I'm Jack, I am 33 years old.
I am studying in Boston University school
三、其他
1、注释
单行注释是在行首使用#
,例如:
#This is a single-line comment
多行注释是用三重引号,例如:
'''
This is the example of
multiline comment
'''
2、运算符
列举少数几个特殊的运算符:
**
幂运算符:
print(2**3)
输出:8
//
整数除法:
print(5/2)
print(5//2)
输出:
2.5
2
- 逻辑运算符
and
、or
、not
- 成员(Membership)运算符
in
、not in
:
print(1 in [1,2,3])
print(1 not in [1,2,3])
输出:
True
False
- 身份(Identity)运算符
a = 1
b = 1
print(a is b)
a = [1,2]
b = [1,2]
print(a is not b)
输出:
True
True
3、设置源文件编码
# -*- coding: UTF-8 -*-