当前位置: 移动技术网 > IT编程>脚本编程>Python > python简单实例一

python简单实例一

2019年04月30日  | 移动技术网IT编程  | 我要评论
python简单实例一。 1.自定义函数 #coding=utf-8 #自定义函数,传入参数,没有传入参数 def sayhello(): print (

python简单实例一。

1.自定义函数

#coding=utf-8
#自定义函数,传入参数,没有传入参数

def sayhello():
    print ("hello word")

def maxed(a,b):
    if(a>b):
        print(a)
    else:
        print(b)

sayhello()
print(maxed(2,3))

2.判断语句

 1 #coding=utf-8
 2 #判断
 3 score = 90
 4 
 5 if score >= 80:
 6     print("很好") 
 7 elif score >= 60:
 8     print ("及格")
 9 elif score >= 30:
10     print("不及格")
11 else:
12     print("很差")

3.循环语句

1 #coding=utf-8
2 #循环
3 #拼接字字符串
4 
5 for i in range(0,100):
6     print("itme ,{0}{1}{2}".format(i,"hello","python"))

4.面向对象(类)

 1 #coding=utf-8
 2 #类,构造函数,类的继承
 3 
 4 class hello:
 5     def __init__(self,name):
 6         self._name=name
 7     def sayhello(self):
 8         print("hello,{0}".format(self._name))   
 9 
10 class hi(hello):
11     def __init__(self, name):
12         hello.__init__(self, name)
13     def hi(self):
14         print("hi,{0}".format(self._name))
15 
16 h=hello("张三")
17 h.sayhello()
18 h1=hi("李四")
19 h1.hi()

 

5.导入库

  建立文件mylib.py,代码如下:

1 class hello():
2     def sayhello(self):
3         print("hello!")

  建立文件loadlib.py,代码如下,两种引用方式。

1 #coding=utf-8
2 #引入外部库的两种方式
3 
4 #import mylib
5 #h1=mylib.hello()
6 #h1.sayhello()
7 from mylib import hello
8 h=hello()
9 h.sayhello()

 

6.python版本下载

  3.x有更多的新特性,2.x运行速度更快
  学习开发使勇2.7.8最好

7.开发环境

  pycharm集成开发环境,本文使用eclipse,python2.7

8.错误:

file "f:\python\jike_leaon\src\flow.py", line 1
syntaxerror: non-ascii character '\xc5' in file f:\python\jike_leaon\src\flow.py on line 1, but no encoding declared;

seehttps://www.python.org/peps/pep-0263.htmlfor details
原因:不支持中文字符串。
修改:文件开头注释加上 #coding=utf-8

9.错误:

typeerror: this constructor takes no arguments

修改:构造函数,是两个下划线,不是一个!


如您对本文有疑问或者有任何想说的,请点击进行留言回复,万千网友为您解惑!

相关文章:

验证码:
移动技术网