Python编程:基础学习一

来源:互联网 发布:最容易学的编程语言 编辑:程序博客网 时间:2024/05/10 09:17
#---第二章:变量和简单数据类型---#name="ada lovelace";print(name.title());# title()以首字母大写的方式显示每个单词,即将每个单词的首字母都改为大写name="Ada Lovelace";print(name.upper());# upper()将字符串中所有字母转换成大写print(name.lower());# lower()将字符串中所有字母转换成小写first_name = "ada";last_name = "lovelace";full_name = first_name + " " + last_name;# Python使用加号( + )来合并字符串print(full_name);print("\tpython");# 字符串中添加制表符,可使用字符组合 \tprint("Languages:\nPython\nC\nJavaScript");# 要在字符串中添加换行符,可使用字符组合 \nfavorite_language = ' python ';print("cc"+favorite_language.rstrip()+"dd");# 剔除字符串结尾的空白print("cc"+favorite_language.lstrip()+"dd");# 剔除字符串开头的空白print("cc"+favorite_language.strip()+"dd");# 剔除字符串两端的空白age = 18;# 使用函数 str() 避免类型错误。可调用函数 str() ,它让Python将非字符串值表示为字符串message = "Happy "+str(age)+"rd Birthday!";print(message);#整数除法的结果只包含整数部分,小数部分被删除。#请注意,计算整数结果时,采取的方式不是四舍五入,而是将小数部分直接删除。#在Python 2中,若要避免这种情况,务必确保至少有一个操作数为浮点数,这样结果也将为浮点数print(3/2);print(3.0/2);#---第三章:列表简介---##列表(索引从0而不是1开始)bicycles = ['trek','cannondale','redline','specialized'];print(bicycles); # ['trek', 'cannondale', 'redline', 'specialized']print(bicycles[0]); # trekprint(bicycles[0].title()); # Trekprint(bicycles[2]); # redlineprint(bicycles[-1]); # specialized 访问最后一个元素,也就是倒数第一个元素print(bicycles[-2]); # redline  访问倒数第二个元素....以此类推....#列表的修改、添加和删除元素motorcycles = ['honda','yamaha','suzuki'];print(motorcycles);motorcycles[0] = "ducati";# 修改列表元素print(motorcycles);motorcycles.append("ducati");#在列表末尾添加元素print(motorcycles);motorcycles = ['honda','yamaha','suzuki'];# 使用方法 insert() 可在列表的任何位置添加新元素。为此,你需要指定新元素的索引和值motorcycles.insert(0,"ducati");# 方法 insert() 在索引 0 处添加空间,并将值 'ducati' 存储到这个地方。这种操作将列表中既有的每个元素都右移一个位置print(motorcycles);motorcycles = ['honda','yamaha','suzuki'];print(motorcycles);del motorcycles[0];# 使用 del 可删除任何位置处的列表元素,条件是知道其索引print(motorcycles);motorcycles = ['honda','yamaha','suzuki'];print(motorcycles);# 方法 pop() 可删除列表末尾的元素,并让你能够接着使用它。# 术语弹出(pop)源自这样的类比:列表就像一个栈,而删除列表末尾的元素相当于弹出栈顶元素。popped_motorcycle = motorcycles.pop();print(motorcycles);print(popped_motorcycle);motorcycles = ['honda','yamaha','suzuki'];#可以使用 pop() 来删除列表中任何位置的元素,只需在括号中指定要删除的元素的索引即可first_owned = motorcycles.pop(0);print("The first motorcycle I owned was a "+first_owned.title()+".");motorcycles = ['honda','yamaha','suzuki','ducati'];print(motorcycles);# 根据值删除元素motorcycles.remove('ducati');print(motorcycles);#组织列表#使用方法 sort() 对列表进行永久性排序cars = ['bmw','audi','toyota','subaru'];cars.sort();print(cars);#你还可以按与字母顺序相反的顺序排列列表元素,为此,只需向 sort() 方法传递参数 reverse=Truecars.sort(reverse=True);print(cars);#要保留列表元素原来的排列顺序,同时以特定的顺序呈现它们,可使用函数 sorted() 。#函数sorted() 让你能够按特定顺序显示列表元素,同时不影响它们在列表中的原始排列顺序。cars = ['bmw','audi','toyota','subaru'];print("Here is the original list:");print(cars);print("\nHere is the sorted list:");print(sorted(cars));print("\nHere is the original list again:");print(cars);#如果你要按与字母顺序相反的顺序显示列表,也可向函数 sorted() 传递参数 reverse=True print(sorted(cars,reverse=True));print(cars);cars = ['bmw','audi','toyota','subaru'];print(cars);#要反转列表元素的排列顺序,可使用方法 reverse()# reverse() 不是指按与字母顺序相反的顺序排列列表元素,而只是反转列表元素的排列顺序cars.reverse();print(cars);#使用函数 len() 可快速获悉列表的长度print(len(cars));#---第四章:操作列表---## for循环magicians = ['alice','david','carolina'];for magician in magicians :print(magician);#在 for 循环中,想包含多少行代码都可以。在代码行 for magician in magicians 后面,#每个缩进的代码行都是循环的一部分,且将针对列表中的每个值都执行一次。因此,可对列表中的每个值执行任意次数的操作。for magician in magicians :print(magician.title()+", that was a great trick!");print("I can't wait to see your next trick, "+magician.title()+".");# 在 for 循环结束后执行一些操作# 在 for 循环后面,没有缩进的代码都只执行一次,而不会重复执行magicians = ['alice','david','carolina'];for magician in magicians :print(magician.title()+", that was a great trick!");print("I can't wait to see your next trick, "+magician.title()+".\n");print("Thank you, everyone. That was a great magic show!")# 创建数值列表# Python函数 range() 让你能够轻松地生成一系列的数字。左闭右开for value in range(1,5):print(value);# 使用函数 range() 时,还可指定步长。例如,下面的代码打印1~10内的偶数:even_numbers = list(range(2,11,2));print(even_numbers);#使用函数 range() 几乎能够创建任何需要的数字集,例如,如何创建一个列表,#其中包含前10个整数(即1~10)的平方呢?在Python中,两个星号( ** )表示乘方运算squares = [];for value in range(1,11):square = value ** 2;squares.append(square);print(squares);squares = [];for value in range(1,11):squares.append(value ** 2);print(squares);# 对数字列表执行简单的统计计算digits = [1,2,3,4,5,6,7,8,9,0];# 最小值print(min(digits));# 最大值print(max(digits));# 求和print(sum(digits));# 列表解析:将 for 循环和创建新元素的代码合并成一行,并自动附加新元素# 要使用这种语法,首先指定一个描述性的列表名,如 squares ;然后,指定一个左方括号,# 并定义一个表达式,用于生成你要存储到列表中的值。在这个示例中,表达式为 value**2 ,它计# 算平方值。接下来,编写一个 for 循环,用于给表达式提供值,再加上右方括号。在这个示例中,# for 循环为 for value in range(1,11) ,它将值1~10提供给表达式 value**2 。# 请注意,这里的 for语句末尾没有冒号squares = [value ** 2 for value in range(1,11)];print(squares);#切片# 要创建切片,可指定要使用的第一个元素和最后一个元素的索引。# 与函数 range() 一样,Python在到达你指定的第二个索引前面的元素后停止。# 要输出列表中的前三个元素,需要指定索引0~3,这将输出分别为 0 、 1 和 2 的元素。players = ['charles', 'martina', 'michael', 'florence', 'eli'];print(players[0:3]);print(players[1:4]);# 如果你没有指定第一个索引,Python将自动从列表开头开始print(players[:4]);# 要让切片终止于列表末尾,也可使用类似的语法。# 例如,如果要提取从第3个元素到列表末尾的所有元素,可将起始索引指定为 2 ,并省略终止索引print(players[2:]);# 负数索引返回离列表末尾相应距离的元素,因此你可以输出列表末尾的任何切片print(players[-3:]);# 遍历切片players = ['charles', 'martina', 'michael', 'florence', 'eli'];print("Here are the first three players on my team:");for player in players[:3]:print(player);# 复制列表my_foods = ['pizza','falafel','carrot cake'];# 要复制列表,可创建一个包含整个列表的切片,方法是同时省略起始索引和终止索引( [:] )。# 这让Python创建一个始于第一个元素,终止于最后一个元素的切片,即复制整个列表friend_foods = my_foods[:];# friend_foods = my_foods #这行行不通#这里将 my_foods 赋给 friend_foods ,而不是将 my_foods 的副本存储到 friend_foods。#这种语法实际上是让Python将新变量 friend_foods 关联到包含在 my_foods 中的列表,#因此这两个变量都指向同一个列表print("My favorite foods are:");print(my_foods);print("\nMy friend's favorite foods are:");print(friend_foods);# 例子:my_foods = ['pizza','falafel','carrot cake'];friend_foods = my_foods[:];my_foods.append('cannoli');friend_foods.append('ice cream');print("My favorite foods are:");print(my_foods);print("\nMy friend's favorite foods are:");print(friend_foods);# 元组:Python将不能修改的值称为不可变的,而不可变的列表被称为元组.# 元组看起来犹如列表,但使用圆括号而不是方括号来标识。# 定义元组后,就可以使用索引来访问其元素,就像访问列表元素一样dimensions = (200,50);print(dimensions);print(dimensions[0]);print(dimensions[1]);# TypeError: 'tuple' object does not support item assignment# 类型错误:元组对象不支持元素值重新分配,也就是不能尝试去修改元组中的任一个元素的值# dimensions[0] = 250;print(dimensions);# 遍历元组中的元素for dimension in dimensions:print(dimension);# 修改元组变量# 虽然不能修改元组的元素,但可以给存储元组的变量赋值.# 相比于列表,元组是更简单的数据结构。# 如果需要存储的一组值在程序的整个生命周期内都不变,可使用元组。dimensions = (300,50);print("Original dimensions:");for dimension in dimensions:print(dimension);dimensions = (400,500);print("\nModified dimensions:");for dimension in dimensions:print(dimension);# 第五章:if语句#每条 if 语句的核心都是一个值为 True 或 False 的表达式,这种表达式被称为条件测试。#Python根据条件测试的值为 True 还是 False 来决定是否执行 if 语句中的代码。#如果条件测试的值为 True ,Python就执行紧跟在 if 语句后面的代码;#如果为 False , Python 就忽略这些代码。car = 'bmw';print(car == 'bmw');# Truecar = 'audi';print(car == 'bmw');# False#例子cars = ['bmw','audi','toyota','subaru'];for car in cars:if car == 'bmw':print(car.upper());else:print(car.title());car = 'bmw';print(car == 'bmw');# 检查是否不相等request_topping = 'mushrooms';if request_topping != 'anchovies':print("Hello the anchovies!")age = 18;if age < 17:print("too small");else:print("sure");# 使用and 、 or age_0 = 22;age_1 = 18;print(age_0 >= 21 and age_1 >= 21);age_1 = 22;print(age_0 >= 21 and age_1 >= 21);age_0 = 22;age_1 = 18;print(age_0 >= 21 or age_1 >= 21);age_0 = 18;print(age_0 >= 21 or age_1 >= 21);# 要判断特定的值是否已包含在列表中,可使用关键字 inrequest_topping = ['mushrooms','onions','pineapple'];print('mushrooms' in request_topping);print('pepperoni' in request_topping);# 确定特定的值未包含在列表中很重要;在这种情况下,可使用关键字 not in banned_users = ['andrew','carolina','david'];user = 'marie';if user not in banned_users:print(user.title()+",you can post a response if you wish.");# 布尔表达式game_active = Truecan_edit = False# 在跟踪程序状态或程序中重要的条件方面,布尔值提供了一种高效的方式。# 在 if 语句中,缩进的作用与 for 循环中相同。如果测试通过了,# 将执行 if 语句后面所有缩进的代码行,否则将忽略它们。age = 19;if age >= 18:print("You are old enough to vote!");print("Have you registered to vote yet?");# if-else语句age = 17;if age >= 18:print("You are old enough to vote!");print("Have you registered to vote yet?");else:print("Sorry,you are too young to vote.");print("Please register to vote as soon as you turn 18!");# if-elif-else结构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;else:price = 10;print("Your admission cost is $"+str(price)+".");# 使用多个elif代码块age = 12;if age < 4:price = 0;elif age < 18:price = 5;elif age < 65:price = 10;else:price = 5;print("Your admission cost is $"+str(price)+".");# 省略else代码块# Python并不要求 if-elif 结构后面必须有 else 代码块。在有些情况下, else 代码块很有用;# 而在其他一些情况下,使用一条 elif 语句来处理特定的情形更清晰# 提醒:# else 是一条包罗万象的语句,只要不满足任何 if 或 elif 中的条件测试,其中的代码就会执行,# 这可能会引入无效甚至恶意的数据。如果知道最终要测试的条件,应考虑使用一个 elif 代码块来# 代替 else 代码块。这样,你就可以肯定,仅当满足相应的条件时,你的代码才会执行。age = 12if age < 4:price = 0elif age < 18:price = 5elif age < 65:price = 10elif age >= 65:price = 5print("Your admission cost is $" + str(price) + ".");# 测试多个条件# if-elif-else 结构功能强大,但仅适合用于只有一个条件满足的情况:遇到通过了的测试后,# Python就跳过余下的测试。这种行为很好,效率很高,让你能够测试一个特定的条件。# 然而,有时候必须检查你关心的所有条件。在这种情况下,应使用一系列不包含 elif 和 else# 代码块的简单 if 语句。在可能有多个条件为 True ,且你需要在每个条件为 True 时都采取相应措施# 时,适合使用这种方法。request_toppings = ['mushrooms','extra cheese'];if 'mushrooms' in request_toppings:print("Adding mushrooms");if 'pepperoni' in request_toppings:print("Adding pepperoni.");if 'extra cheese' in request_toppings:print("Adding extra cheese");print("\nFinished making your pizza");request_toppings = ['mushrooms','extra cheese'];if 'mushrooms' in request_toppings:print("Adding mushrooms");elif 'pepperoni' in request_toppings:print("Adding pepperoni.");elif 'extra cheese' in request_toppings:print("Adding extra cheese");print("\nFinished making your pizza");# 总之,如果你只想执行一个代码块,就使用 if-elif-else 结构;# 如果要运行多个代码块,就使用一系列独立的 if 语句。# 检查特殊元素(for循环中嵌套if-else语句)request_toppings = ['mushrooms','green peppers','extra cheese'];for request_topping in request_toppings:if request_topping == 'green peppers':print('Sorry,we are out of green peppers right now.');else:print("Adding "+request_topping+".");print("\nFinished making your pizza!");# 确定列表不是空的request_toppings = [];# 在 if 语句中将列表名用在条件表达式中时,Python将在列表# 至少包含一个元素时返回 True ,并在列表为空时返回 Falseif request_toppings:for request_topping in request_toppings:print("Adding "+request_topping);print("\nFinish making your pizza!");else:print("Are you sure you want a plain pizza?");# 使用多个列表avaliable_toppings = ['mushrooms','olives','green peppers',                      'pepperoni','pineapple','extra cheese'];request_toppings = ['mushrooms','french fries','extra cheese'];for request_topping in request_toppings:if request_topping in avaliable_toppings:print("Adding "+request_topping+".");else:print("Sorry,we don't have "+request_topping+".");print("\nFinished making your pizza!");

0 0
原创粉丝点击