建议在学习python前,一定要先学习python语法,python语法相对简单,有编程基础的同学将很容易入门!
推荐Python菜鸟教程
这里举几个常用的例子:
打印日志:
print('hello world!')
定义变量:
a = 1
b = 'hello'
c = True
list = [1, 2, 3]
list.append(4)
for循环:
for item in list:
print(item)
for index in range(10):
print(index)
while循环:
i = 0
while i > 10:
i += 1
print(i)
定义方法:
def testFun(x):
print(x)
条件判断:
def printX(x):
if x == 1:
print(1)
elif x == 2:
print(2)
else:
print("unknown")
异常捕获:
try:
result = 1 / 0
print(result)
except Exception as e:
print("错误:" + str(e))
创建对象:
class Person:
def __init__(self, name, age):
self.name = name
self.age = age
def showPersonInfo(self):
print(self.name, self.age)
调用:
person = Person("ahah", 20)
person.showPersonInfo()
class House:
def __init__(self):
self.cover = ""
self.title = ""
self.roomCount = ""
self.area = ""
self.address = ""
self.source = ""
self.url = ""
house = House()
house.title = "百度"
house.url = "https://www.baidu.com"
注释用 # 号:
print("注释")
当然,还有其它的如运算符,字典,函数,File(文件处理)等等,与java,c,js等语言都大同小异,这里就不做过多讲解了…
需要注意的是,Python代码语句之间没有结尾符,但却有严格的缩进机制,依靠缩进来判断代码属于哪个条件下,一般的,在编辑器中,在你写完一句代码并按Enter时,会自动进行缩进,当缩进不符合预期时,可以自行调整!
|