Python基础实例 (2)

#! /usr/bin/python
# -*- coding: utf8 -*- 

s=input("输入你的中文名,按回车继续");
print ("你的名字是  : " +s)

l=len(s)
print ("你中文名字的长度是:"+str(l))


知识点:

类似Java,在python3里所有字符串都是unicode,所以长度一致.

6 条件和循环语


#! /usr/bin/python
#条件和循环语句

x=int(input("Please enter an integer:"))
if x<0:
    x=0
    print ("Negative changed to zero")

elif x==0:
    print ("Zero")

else:
    print ("More")


# Loops List
a = [\'cat\', \'window\', \'defenestrate\']
for x in a:
    print (x, len(x))

#知识点:

#    * 条件和循环语句
#    * 如何得到控制台输入

7

#! /usr/bin/python
# -*- coding: utf8 -*- 

def sum(a,b):
    return a+b


func = sum
r = func(5,6)
print (r)

# 提供默认值
def add(a,b=2):
    return a+b
r=add(1)
print (r)
r=add(1,5)
print (r)


一个好用的函数

#! /usr/bin/python
# -*- coding: utf8 -*- 

# The range() function
a =range (1,10)
for i in a:
    print (i)
    
a = range(-2,-11,-3) # The 3rd parameter stands for step
for i in a:
    print (i)


知识点:

Python 不用{}来控制程序结构,他强迫你用缩进来写程序,使代码清晰.

定义函数方便简单 

方便好用的range函数

8 异常处

#! /usr/bin/python
s=input("Input your age:")
if s =="":
    raise Exception("Input must no be empty.")

try:
    i=int(s)
except Exception as err:
    print(err)
finally: # Clean up action
    print("Goodbye!")

9 文件处

对比Java,python的文本处理再次让人感动

#! /usr/bin/python

spath="D:/download/baa.txt"
f=open(spath,"w") # Opens file for writing.Creates this file doesn\'t exist.
f.write("First line 1.\n")
f.writelines("First line 2.")

f.close()

f=open(spath,"r") # Opens file for reading

for line in f:
    print("每一行的数据是:%s"%line)

f.close()


知识点:

open的参数:r表示读,w写数据,在写之前先清空文件内容,a打开并附加内容.

打开文件之后记得关闭

10 类和继

class Base:
    def __init__(self):
        self.data = []
    def add(self, x):
        self.data.append(x)
    def addtwice(self, x):
        self.add(x)
        self.add(x)

# Child extends Base
class Child(Base):
    def plus(self,a,b):
        return a+b

oChild =Child()
oChild.add("str1")
print (oChild.data)
print (oChild.plus(2,3))

\'\'\'
知识点:

    * self:类似Java的this参数
    
\'\'\'

11 包机

每一个.py文件称为一个module,module之间可以互相导入.请参看以下例子:

# a.py
def add_func(a,b):
    return a+b

# b.py
from a import add_func # Also can be : import a

print ("Import add_func from module a")
print ("Result of 1 plus 2 is: ")
print (add_func(1,2))    # If using "import a" , then here should be "a.add_func"

内容版权声明:除非注明,否则皆为本站原创文章。

转载注明出处:https://www.heiqu.com/zzwdgs.html