print("-------------输出语句-------------");message="Hello Python world";print(message);print("-------------首字母大写-------------");name="ada lovelace";print(name.title());print("-------------大小写-------------");print(name.upper());print(name.lower());print("-------------拼接字符串-------------");first_name = "ada"last_name = "lovelace"full_name = first_name + " " + last_nameprint(full_name);print("-------------添加空白-------------");print("\tPython");print("Languages:\nPython\nC\nJavaScript");print("-------------删除空白-------------");print("Hello ".rstrip());print("-------------运算-------------");print(2+3);print(3-2);print(2*3);print(3/2);print(3**2);print(3**3);print(10**6);print(0.1+0.1);print(0.2+0.2);print("------------注释-------------");# 测试注释-------------输出语句-------------Hello Python world-------------首字母大写-------------Ada Lovelace-------------大小写-------------ADA LOVELACEada lovelace-------------拼接字符串-------------ada lovelace-------------添加空白------------- PythonLanguages:PythonCJavaScript-------------删除空白-------------Hello-------------运算-------------5161.592710000000.20.4------------注释-------------Process finished with exit code 0print("-------------列表-------------");bicycles = ['trek', 'cannondale', 'redline', 'specialized'];print(bicycles);print("-------------访问列表元素-------------");print(bicycles[0]);print("-------------修改列表元素-------------");bicycles[0]='ducati';print(bicycles);print("-------------添加列表元素-------------");bicycles.append('test');print(bicycles);print("-------------插入列表元素-------------");bicycles.insert(0,'test2');print(bicycles);print("-------------删除列表元素-------------");del bicycles[0];print(bicycles);print(bicycles.pop());print(bicycles);print("-------------排序列表元素-------------");bicycles.sort();print(bicycles);print("-------------倒叙打印列表元素-------------");print(bicycles.reverse());print("-------------列表长度-------------");print(len(bicycles));print("-------------数值列表------------");numbers=list(range(1,6));print(numbers);-------------列表-------------['trek', 'cannondale', 'redline', 'specialized']-------------访问列表元素-------------trek-------------修改列表元素-------------['ducati', 'cannondale', 'redline', 'specialized']-------------添加列表元素-------------['ducati', 'cannondale', 'redline', 'specialized', 'test']-------------插入列表元素-------------['test2', 'ducati', 'cannondale', 'redline', 'specialized', 'test']-------------删除列表元素-------------['ducati', 'cannondale', 'redline', 'specialized', 'test']test['ducati', 'cannondale', 'redline', 'specialized']Process finished with exit code 0print("-------------检查是否相等-------------");car='bmw';print(car=='bmw');print(car=='audi');print(car=='BMW');print(car.upper()=='BMW');age=18;print(age==18);print(age>=18);print(age<=18);print(age>18);print(age<18);age_0 = 22;age_1 = 18;print(age_0 >= 21 and age_1 >= 21);print(age_0 >= 21 or age_1 >= 21);print("-------------if语句-------------");age = 19if age >= 18: print("You are old enough to vote!"); age=17 if age>=18: print("You are old enough to vote!"); else: print("Sorry you are too young"); age = 12 if age < 4: print("Your admission cost is $0.") elif age < 18: print("Your admission cost is $5.") else: print("Your admission cost is $10.") age = 12 if age < 4: price = 0 elif age < 18: price = 5 elif age < 65: price = 10 elif age >= 65: price = 5print("Your admission cost is $" + str(price) + ".")-------------检查是否相等-------------TrueFalseFalseTrueTrueTrueTrueFalseFalseFalseTrue-------------if语句-------------You are old enough to vote!Sorry you are too youngYour admission cost is $5.Your admission cost is $5.Process finished with exit code 0print("-------------一个简单的字典-------------");alien_0 = {'color': 'green', 'points': 5}print(alien_0['color'])print(alien_0['points'])print("-------------访问字典中的值------------");alien_0={'color':'green'};print(alien_0['color']);print("-------------先创建一个空字典------------");alien_0 = {}alien_0['color'] = 'green'alien_0['points'] = 5print(alien_0)print("-------------修改字典中的值------------");alien_0={'color':'green'}print("The alien is " + alien_0['color'] + ".")alien_0['color'] = 'yellow'print("The alien is now " + alien_0['color'] + ".")print("-------------删除键值对------------");alien_0 = {'color': 'green', 'points': 5}print(alien_0);del alien_0['points']print(alien_0);print("-------------遍历字典------------");user_0 = { 'username': 'efermi', 'first': 'enrico', 'last': 'fermi',}for key,value in user_0.items(): print("\nKey:"+key) print("Value:"+value)-------------一个简单的字典-------------green5-------------访问字典中的值------------green-------------先创建一个空字典------------{'color': 'green', 'points': 5}-------------修改字典中的值------------The alien is green.The alien is now yellow.-------------删除键值对------------{'color': 'green', 'points': 5}{'color': 'green'}-------------遍历字典------------Key:usernameValue:efermiKey:firstValue:enricoKey:lastValue:fermiProcess finished with exit code 0print("-------------函数input()的工作原理-------------");message = input("Tell me something, and I will repeat it back to you: ")print(message)print("-------------编写清晰的程序-------------");name=input("Please enter your name:");print("Hello,"+name+"!");print("-------------求模运算符-------------");print(4%3);print("-------------while循环-------------");current_number = 1while current_number <= 5: print(current_number) current_number += 1print("-------------让用户选择何时退出-------------");prompt = "\nTell me something, and I will repeat it back to you:"prompt += "\nEnter 'quit' to end the program. "message = ""while message != 'quit': message = input(prompt) print(message)print("-------------break语句-------------");prompt = "\nPlease enter the name of a city you have visited:"prompt += "\n(Enter 'quit' when you are finished.) "while True: city = input(prompt) if city == 'quit': break else: print("I'd love to go to " + city.title() + "!")-------------函数input()的工作原理-------------Tell me something, and I will repeat it back to you: Hello WorldHello World-------------编写清晰的程序-------------Please enter your name:AliceHello,Alice!-------------求模运算符-------------1-------------while循环-------------12345-------------让用户选择何时退出-------------Tell me something, and I will repeat it back to you:Enter 'quit' to end the program. Hello WorldHello WorldTell me something, and I will repeat it back to you:Enter 'quit' to end the program. quitquit-------------break语句-------------Please enter the name of a city you have visited:(Enter 'quit' when you are finished.) ShangHaiI'd love to go to Shanghai!Please enter the name of a city you have visited:(Enter 'quit' when you are finished.) quitProcess finished with exit code 0print("-------------函数-------------");def greet_user(): print("Hello World")print("-------------区分线-------------");greet_user();print("-------------调用函数-------------");def tpl_sum( T ): #定义函数tpl_sum() result = 0 #定义result的初始值为0 for i in T: #遍历T中的每一个元素i result += i #计算各个元素i的和 return result #函数tpl_sum()最终返回计算的和print("(1,2,3,4)元组中元素的和为:",tpl_sum((1,2, 3,4))) #使用函数tpl_sum()计算元组内元素的和print("[3,4,5,6]列表中元素的和为:",tpl_sum([3,4, 5,6])) #使用函数tpl_sum()计算列表内元素的和print("[2.7,2,5.8]列表中元素的和为:",tpl_sum([2.7, 2,5.8])) #使用函数tpl_sum()计算列表内元素的和print("[1,2,2.4]列表中元素的和为:",tpl_sum([1,2,2.4]))#使用函数tpl_sum()计算列表内元素的和-------------函数--------------------------区分线-------------Hello World-------------调用函数-------------(1,2,3,4)元组中元素的和为: 10[3,4,5,6]列表中元素的和为: 18[2.7,2,5.8]列表中元素的和为: 10.5[1,2,2.4]列表中元素的和为: 5.4Process finished with exit code 0def<函数名>(参数列表): <函数语句> return<返回值>在上述格式中,参数列表和返回值不是必需的,return 后也可以不跟返回值,甚至连 return 也没有。如果 return 后没有返回值,并且没有 return 语句,这样的函数都会返回 None 值。有些函数可能既不需要传递参数,也没有返回值。
注意:当函数没有参数时,包含参数的圆括号也必须写上,圆括号后也必须有“:”。
在 Python 程序中,完整的函数是由函数名、参数以及函数实现语句(函数体)组成的。在函数声明中,也要使用缩进以表示语句属于函数体。如果函数有返回值,那么需要在函数中使用 return 语句返回计算结果。
根据前面的学习,可以总结出定义 Python 函数的语法规则,具体说明如下所示。
print("-------------类-------------");class MyClass: #定义类MyClass "这是一个类."myclass = MyClass() #实例化类MyClassprint('输出类的说明:') #显示文本信息print(myclass.__doc__) #显示属性值print('显示类帮助信息:')help(myclass)print("-------------类对象-------------");class MyClass: #定义类MyClass """一个简单的类实例""" i = 12345 #设置变量i的初始值 def f(self): #定义类方法f() return 'hello world' #显示文本x = MyClass() #实例化类#下面两行代码分别访问类的属性和方法print("类MyClass中的属性i为:", x.i)print("类MyClass中的方法f输出为:", x.f())print("-------------构造方法-------------");class Dog(): """小狗狗""" def __init__(self, name, age): """初始化属性name和age.""" self.name = name self.age = age def wang(self): """模拟狗狗汪汪叫.""" print(self.name.title() + " 汪汪") def shen(self): """模拟狗狗伸舌头.""" print(self.name.title() + " 伸舌头")print("-------------调用方法-------------");def diao(x,y): return (abs(x),abs(y))class Ant: def __init__(self,x=0,y=0): self.x = x self.y = y self.d_point() def yi(self,x,y): x,y = diao(x,y) self.e_point(x,y) self.d_point() def e_point(self,x,y): self.x += x self.y += y def d_point(self): print("亲,当前的位置是:(%d,%d)" % (self.x,self.y))ant_a = Ant()ant_a.yi(2,7)ant_a.yi(-5,6)-------------类-------------输出类的说明:这是一个类.显示类帮助信息:Help on MyClass in module __main__ object:class MyClass(builtins.object)| 这是一个类.| | Data descriptors defined here:| | __dict__| dictionary for instance variables (if defined)| | __weakref__| list of weak references to the object (if defined)-------------类对象-------------类MyClass中的属性i为: 12345类MyClass中的方法f输出为: hello world-------------构造方法--------------------------调用方法-------------亲,当前的位置是:(0,0)亲,当前的位置是:(2,7)亲,当前的位置是:(7,13)Process finished with exit code 0