Python基础
Posted hongrun
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Python基础相关的知识,希望对你有一定的参考价值。
if语句
#if..else基本格式
if 条件: pass else: pass
猜年龄
age_of_princal = 56 guess_age = int( input(">>:")) if age_of_princal == guess_age : print("Yes,you got it..") else: print("No,you are wrong")
#if..elif..else基本格式
if 条件: pass elif 条件: pass else: pass
#猜年龄
age_of_princal = 56 guess_age = int( input(">>:")) if age_of_princal == guess_age: print("Good!") elif guess_age > age_of_princal print("偏大") else: print("偏小")
#判断分数级别
core = int(input("请输入你的分数:")) if core >= 90: print("A") elif core >= 80: print("B") elif core >= 70: print("C") elif core >= 60: print("D") else: print("滚")
#用户登录(不介意采用这种方法)
i = 1 name = "alex" password = 12345 name1 = input("plese,Input you are name:") password1 = input("please,input you are password:") if i == 1: if name == str(name1): if password == int(password1): print("恭喜您成功登陆") else: print("您密码与之不符!您还有两次机会") name1 = input("plese,Input you are name:") password1 = input("please,input you are password:") if name == str(name1): if password == int(password1): print("恭喜您成功登陆") else: print("您密码与之不符!您还有一次机会") name1 = input("plese,Input you are name:") password1 = input("please,input you are password:") if name == str(name1): if password == int(password1): print("恭喜您成功登陆") else: print("您密码与之不符!您没有机会了") i = 0 exit(0) else: print("您用户名与之不符!您没有机会了") i = 0 exit(0) else: print("您用户名与之不符!您还有一次机会") name1 = input("plese,Input you are name:") password1 = input("please,input you are password:") if name == str(name1): if password == int(password1): print("恭喜您成功登陆") else: print("您密码与之不符!您没有机会了") i = 0 exit(0) else: print("您用户名与之不符!您没有机会了") i = 0 exit(0) else: print("您用户名与之不符!您还有两次机会") name1 = input("plese,Input you are name:") password1 = input("please,input you are password:") if name == str(name1): if password == int(password1): print("恭喜您成功登陆") else: print("您密码与之不符!您还有一次机会") name1 = input("plese,Input you are name:") password1 = input("please,input you are password:") if name == str(name1): if password == int(password1): print("恭喜您成功登陆") else: print("您密码与之不符!您没有机会了") i = 0 exit(0) else: print("您用户名与之不符!您没有机会了") i = 0 exit(0) else: print("您用户名与之不符!您还有一次机会") name1 = input("plese,Input you are name:") password1 = input("please,input you are password:") if name == str(name1): if password == int(password1): print("恭喜您成功登陆") else: print("您密码与之不符!您没有机会了") i = 0 exit(0) else: print("您用户名与之不符!您没有机会了") i = 0 exit(0) else: exit(0)
#用户登录(结合while循环&if..else)
name = "alex" password = "123456" i = 1 while i <= 3: user_name = input("Input you name:") user_password = input("Input you password:") if user_name == name: if user_password == password: print("Welcome!") break else: print("Input you password error") i += 1 else: print("Input you name error") i += 1
#判断最大与最小值
num1 = input("num1:") num2 = input("num2:") num3 = input("num3:") if num1 > num2 > num3: print("最大值为:",num1,"最小值为:",num3) elif num1 > num3 > num2: print("最大值为:", num1, "最小值为:", num2) elif num2 > num1 > num3: print("最大值为:", num2, "最小值为:", num3) elif num2 > num3 > num1: print("最大值为:", num2, "最小值为:", num1) elif num3 > num1 > num2: print("最大值为:", num3, "最小值为:", num2) else: print("最大值为:", num3, "最小值为:", num1)
#判断最大值
num1 = input("num1:") num2 = input("num2:") num3 = input("num3:") if num1 > num2: max_num = num1 if max_num > num3: print("Max NUM is",max_num) else: print("Max NUM is",num3) else: max_num = num2 if max_num > num3: print("Max NUM is",max_num) else: print("Max NUM is",num3)
while循环
#while基本格式
while 条件: pass
#输出1到10
num = 1 while num <= 10: print(num) num += 1;
#输出1到100的偶数(while循环&if..else嵌套)
num = 1 while num <= 100: if num % 2 == 0: print(num) num += 1 else: num += 1
#3次机会猜年龄(while循环&if..elif..else嵌套)
age = 50 guess_sum = 1 print("You can guess 3") while guess_sum <= 3: user_input_age = int(input("Age is:")) if user_input_age == age: print("Yes") guess_sum = 4 elif user_input_age > age: print("Is bigger") guess_sum += 1 else: print("Is smaller") guess_sum += 1 print("End")
#一直猜年龄直到猜正确
age = 50 while True: user_input_age = int(input("Age is")) if user_input_age == age: print("Yes") break elif user_input_age > age: print("Is bigger") else: print("Is smaller") print("End") #直到正确结束退出while循环执行
#while..else基本用法
while 条件: pass else:#除了break其他情况都会出现 pass
while循环中的else语句比较特殊,这里的else语句,只有在循环正常结束的时候才会执行,
什么意思呢?意思就是说如果我们的while循环在执行过程中中断了,也就是说执行了
break语句,这里的else语句就不会被执行。我们看一下下面的代码:
# 循环没有被中断 num = 0 while num<10: num = num + 1 if num%2 ==0: continue print(num) else: print("else-----") 结果: 1 3 5 7 9 else-----
---------------------------------------------------------------------------------------------------
# 循环被中断 num = 0 while num<10: num = num + 1 if num%2 ==0: break print(num) else: print("else-----") 结果: 1
#continue与else的使用
num = 1 while num <= 10: num += 1 if num == 3: continue print(num) else:#除了break其他情况都会出现 print("This is else statement")
运行结果:
2 4 5 6 7 8 9 10 11
end=""的使用
#end=""输出到同一行
print("hello world.",end="") print("hello world.",end="") print("hello world.",end="")
运行结果:
hello world.hello world.hello world.
#根据用户输入值去输出矩形图
height = int(input("Height:")) width = int(input("width:")) num_height = 1 while num_height <= height: num_width = 1 while num_width <= width: print("#",end = "") num_width += 1 print() num_height += 1
#输出#组成的直角三角形
num_height = 1 while num_height <= 4: num_width = 4 while num_width - 3 <= num_height: print("#",end = "") num_width += 1 print() #换行 num_height += 1
#第一种方式输出*号倒立直角三角形
user_width = int(input("please width:")) user_height = int(input("please height:")) i = 1 while i <= user_height: j = user_width while j - i>= 0: print("*",end="") j -= 1 print() i += 1
#第二种方式输出*号倒立直角三角形
line = 5 while line > 0: tmp = line while tmp > 0: print("*",end="") tmp = tmp - 1 print() line -= 1
#九九乘法表倒立
first = 9 while first > 0: sec = 1 while sec <= first: print(str(sec) + "*" + str(first) + "=" +str(sec * first), end = "\\t") #\\t是制表符,*空格 sec += 1 print() first -= 1
#输出九九乘法表
first = 1 while first <= 9: sec = 1 while sec <= first: print(str(sec) + "*" + str(first) + "=" +str((sec) * first), end = "\\t") sec += 1 print() first += 1
#字符格式化输出
name = input("name:") age = input("age:") job = input("job:") salary = input("salary:") if salary.isdigit(): #长得像不像数字,比如200d,‘200‘ salary = int(salary) else: #print("must input digit") exit("must input digit") #退出程序 msg = ‘‘‘ ---------info of %s---------- Name : %s Age : %s Job : %s Salary : %s ------------end-------------- ‘‘‘ % (name,name,age,job,salary) print(msg)
for循环
#1-100所有的奇数
for i in range(1,101): if i % 2 != 0: print(i)
#第二种方法:1-100所有的奇数
for i in range(1,101,2): #2是步长 print(i)
#循环100次,从50到70之间不打印
for i in range(100): if i >= 50 and i <= 70: continue else: print(i)
#第二种方式:循环100次,从50到70之间不打印
for i in range(100): if i < 50 or i >70: print(i)
#第一种方式:判断用户输入用户名和密码是否错误
_name = "alex" _password = "123" for i in range(3): user_name = input("You name:") user_password = input("You password:") if _name == user_name and _password == user_password: print("%s success login" %(user_name)) break else: if i == 2: print("You have entered too many times.") print("You input name or password error!")
#第二种方式:判断用户输入用户名和密码是否错误
_name = "alex" _password = "123" for i in range(3): user_name = input("You name:") user_password = input("You password:") if _name == user_name and _password == user_password: print("%s success login" %(user_name)) break #跳出,中断。break 过后,就不会执行最后面的else语句 else: print("You input name or password error!") else: #只要上面的for循环正常执行完毕,中间没被打断,就会执行else语句 print("You have entered too many times.")
#让用户输入一个值number,窗口输出1-number
number = int(input("从一到:")) for i in range(1,number + 1): print(i)
#输错三次后可以给用户选择是否继续
_name = "alex" _password = "123" counter = 0 while counter < 3: name = input("You name:") password = input("You password:") if name == _name and password == _password: print("Welcome %s login..." %_name) break else: print("invalid you name or password") counter += 1 if counter == 3: keep_going_choice = input("还想玩么?[y/n]") if keep_going_choice == "y": counter = 0 else: print("error ")
#continue&break注意要点
exit_flag = False for i in range(10): if i < 5: #continue print(i) print(end ="\\t") for j in range(10): if j < 5: #exit_flag = True # break #这个break能跳出 j这个循环 continue print(j) if exit_flag: break #这个break能跳出 i 这个循环
列表
#索引切片
a = [‘wuchao‘,‘jinxing‘,‘xiaohu‘,‘sanpang‘,‘ligang‘] print(a[1])#取到索引1的值 print(a[1:2])#取不到右边那个 print(a[1:])#取从索引1到最后 print(a[1:-1])#取从索引1到最后的前面一个 print(a[1:-1:1])#取从左到右一个一个去取 print(a[3::-2]) #从后面往前面步长为2
#添加append insert
a.append(‘xuepeng‘) #默认查到最后一个位置 print(a) a.insert(1,‘xuepeng‘) #将数据插入到索引为1的位置 print(a)
#修改
a = [‘wuchao‘,‘jinxing‘,‘xiaohu‘,‘sanpang‘,‘ligang‘] a[0] = ‘hongrun‘ print(a) a[1:3] = [‘qingxia‘,‘jiaxin‘] #改索引为1,2的值 print(a)
#删除 remove pop del
a.remove(‘wuchao‘)#remove只能删除值,不能做切片 print(a) b = a.pop(1) #pop根据索引取到值,还可以取到删除值 print(b) del a[0] #del既可以删除一个值也可以删除整个对象del a print(a)
#count计算某元素出现次数
a = [‘to‘,‘be‘,‘or‘,‘not‘,‘to‘,‘be‘].count(‘to‘) #计算a列表里有几个to print(a)
#extend将列表添加到另一个列表里
a = [1,2,3] b = [4,5,6] a.extend(b) print(a) print(b)
运行结果:
[1, 2, 3, 4, 5, 6]
[4, 5, 6]
#index取出某个字符串的索引值
a = [‘wuchao‘,‘jinxing‘,‘xiaohu‘,‘sanpang‘,‘ligang‘] t = a.index(‘jinxing‘) print(t)
#index取出第二个ligang的索引值
a = [‘wuchao‘,‘jinxing‘,‘ligang‘,‘xiaohu‘,‘sanpang‘,‘ligang‘] first_lg_index = a.index(‘ligang‘) #get the first ligang little_list = a[first_lg_index + 1:] #切片第二个取小列表 second_lg_index = little_list.index("ligang")#取第二个ligang在小列表里的位置 print("second_lg_index",second_lg_index) second_lg_index_in_big_list = first_lg_index + second_lg_index + 1 #通过第一个ligang和第二个ligang来计算出第二个ligang在大列表里的位置 print(second_lg_index_in_big_list) print(a[first_lg_index + 1:])
#reverse将全部字符倒过来
a = [‘wuchao‘,‘jinxing‘,‘ligang‘,‘xiaohu‘,‘sanpang‘,‘ligang‘] b = [‘luhongrun‘,‘luqingxia‘,‘lujiaxin‘] c = a + b #a,b都不改变,得到一个全新的值 print(c) a.reverse() #将a里列表的值顺序给倒过来了 print(a)
#sort默认数字由小到大与字母ASCII按顺序排序
x = [4,6,2,1,7,9] x.sort() print(x) x.sort(reverse = True)#通过设置reverse的值为True,即可将数字由大到小排列与字母ASCII按从后到前排列 print(x) b = sorted(x) print(b)
#判断里面是否有haidilaoge
a = [‘wuchao‘,‘jinxing‘,‘ligang‘,‘xiaohu‘,‘sanpang‘,‘ligang‘] print(a.count("haidilaoge")) print("haidilaoge" in a)#in表示在不在a里面
运行结果:
0
False
#嵌套
a = [[1,2,3],‘alex‘,4,(2,3,4)] b = a[0] #b = [1,2,3] b[1] == 2 print(a[0][1])
运行结果:2
#第一种购物车(较麻烦)
user_salary = int(input("Please,Input you salary:")) goods_list = [5800,9000,32,80,1500] goods_name = ["iphone6s","mac-book","coffee","python-book","bicyle"] goods_money = [] shopping_ = [] user_money_ye = [] i = 0 user_input = True modle = ‘quit‘ user_money_ye.append(int(user_salary)) print("----------欢迎光临本店----------") shopping_list = ‘‘‘1. iphone6s 5800, 2. mac book 9000, 3. coffee 32, 4. python book 80, 5. bicyle 1500‘‘‘ print(shopping_list) print("--------------------------------") while user_input: user_input_goods = input(">>>:") if user_input_goods != modle: if user_money_ye[i] >= goods_list[int(user_input_goods) - 1]: user_money = user_money_ye[i] - goods_list[int(user_input_goods) - 1] shopping_.append(goods_name[int(user_input_goods) - 1]) goods_money.append(goods_list[int(user_input_goods) - 1]) user_money_ye.append(user_money) i += 1 print("以加入%s到您的购物车,当前余额%s" % (goods_name[int(user_input_goods) - 1], user_money_ye[i])) else: print("您余额不足,还剩%s" %user_money_ye[i]) print("请重新选择") elif user_input_goods == modle: print("您已购买商品如下") #print(shopping_) g = 0 for n in range(i): print(shopping_[g],end=‘\\t\\t\\t\\t‘) print(goods_money[g]) g += 1 print("您的余额为:%s" %user_money_ye[i]) print("欢迎下次光临") user_input = False else: print("You input error!")
#第二种购物车
product_list = [(‘Mac‘,9000), (‘kindle‘,800), (‘tesla‘,900000), (‘python book‘,105), (‘bike‘,2000),] shopping_car =[] saving = input(‘please input your saving:‘) if saving.isdigit(): saving = int(saving) while True: for i,v in enumerate(product_list,1):#enumerate是加编号用的 print(i,‘>>>>‘,v) choice = input(‘选择购买商品编号[退出:quit]:‘) if choice.isdigit(): choice = int(choice) if choice > 0 and choice <= len(product_list): p_item = product_list[choice - 1] if p_item[1] < saving: saving -= p_item[1] shopping_car.append(p_item) else: print(‘余额不足,还剩%s‘%saving) else: print(‘编码不存在‘) elif choice == ‘quit‘: print(‘--------------您已经购买如下商品----------------‘) for i in shopping_car: print(i) print(‘您还剩%s元钱‘%saving) break else: print(‘invalid input‘) for i in product_list: print(product_list.index(i),i)
序列
我们去银行办理业务都是需要排队的,排队前都是拿一个号,然后去排序,窗口叫到哪个号,哪个号就去窗口办理业务。
我们把排队的人想象成一个排列好的队伍,队伍按照号码来排序,他们是一个有序的队列。每个人排队的人都有名字,这些名字按照顺序排列起来也叫序列。同样,我们把人名替换成数字或字母,那他们也叫序列。
序列就是按照一定的顺序排列起来的一系列元素,每个元素不是在其他元素之前,就是在其他元素之后。
这里需要大家了解一条语句——range()。
range()语句用来生成一组数字,在Pyhton2.x里可以很明显的看出来,Python3.x则看不出来(后面会解释原因)
>>> range(10) [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] # 就像队伍一样,还是有按照顺序来排列的,每个元素不是在其他元素之前就是在其之后 >>> range(1,10) # Range()生成的数字默认从0开始,也可以是指定起始值。取不到右边的10 [1, 2, 3, 4, 5, 6, 7, 8, 9] >>> range(1,10,2) # 还可以指定步长,这步长为2 [1, 3, 5, 7, 9] # rang()的用法: range(stop) #stop为结束位置,列出从0到stop之前的所有整数 range(start, stop[, step]) #start表示起始数字,stop表示结束数字,stop表示每两个相邻数字之间的差,也叫步长 #列出从start开始,到stop之前所有的数字
参考:
http://www.cnblogs.com/resn/p/5776403.html
以上是关于Python基础的主要内容,如果未能解决你的问题,请参考以下文章