Python基础知识练习

Python基础知识练习 扫二维码继续学习

初学Python者必须进行练习,才能掌握Python基础知识
(3人)

99.98元

#!/usr/bin/env python
#coding:utf-8

def move(list1, step):
	for i in range(step):
		a = list1.pop(0)
		list1.append(a)
	return list1

if __name__ == "__main__":
	list1 = [23,45,678,9,32,2,56,7,34,]
	step = 3
	move(list1, step)
	print(list1)
#!/usr/bin/env python
#coding:utf-8

import random

def oushu(number):
	if number % 2 == 0:
		return number
def jishu(number):
	if number % 2 != 0:
		return number


if __name__ == "__main__":
	list1 = []
	list_new = []
	list_new2 = []
	for i in range(10):
		list1.append(random.randint(0,100))
	for i in list1:
		if oushu(i):
			list_new.append(i)
		if jishu(i):
			list_new2.append(i)
	for i in list_new2:
		list_new.append(i)
	print(list_new)

 

[展开全文]
DAHUI · 22小时前 · 函数练习-2 0

1,谷歌得到答案。

explicit

implicit

2,

5,format 方法是什么意思

divmod 是什么意思

6,保留2位小数

7,

8,为什么有了\就可以呢

9,

12,

13,

14,[::2]

[展开全文]

16、自己定义一个列表,要求该列表中的元素至少要包括字符串、整数、浮点数。要求:编

写一段程序,列表中不是字符串的元素全部删除。

#coding=utf-8

lst = ["wanglaoshi", "adam", 12, 26, 3.14, [3,6,9]]

print(lst)

new_lst = []

for i in lst:

    if isinstance(i, str):

        new_lst.append(i)

print(new_list)

17、写一段程序,能够实现如下功能:

  • 输入英文的姓名
  • 按照字典顺序将所有姓名排序
  • 输入完毕,将排序结果打印出来

#!/usr/bin/env python

#coding=utf-8

= {"java":"python","ruby":"cc","go":"aa"}

def fun(s):

    = sorted(s.iteritems(),key=lambda t:t[1],reverse=True)

    return d    

= fun(s)

print d

 

18、已知道两个列表:citys=["suzhou","shanghai","hangzhou","nanjing"],

codes = ["0512","021","0571","025"]

创建一个字典,以citys中的元素为key,以codes中的元素为value

#!/usr/bin/env python

#coding=utf-8

citys_codes = {"suzhou":"0512","shanghai":"021","hangzhou":"0571","nanjing":"025"}

def fun(s):

d = sorted(s.iteritems(),key=lambda i:i[1],reverse=False)

return d

d = fun(citys_codes)

print d

#!/usr/bin/env python
# coding:utf-8
'''19、在得到的字典{'suzhou': '0512', 'hangzhou': '0571', 'shanghai': '021', 'nanjing': '025'}中,选出value不是三个数字的健值对组成一个新的字典
。比如"shanghai":"021"就不该在新字典中出现.
'''

dct = {'suzhou': '0512', 'hangzhou': '0571', 'shanghai': '021', 'nanjing': '025'}

new_dct = {}
for k, v in dct.items():
    if len(v) != 3:
        new_dct.update([(k,v),])
print(new_dct)

#!/usr/bin/env python
# coding:utf-8
'''21、写一个程序,将公元1900年到2016年之间所有的闰年年份选出来'''

import calendar

years = range(1896,2016)

leap_years = []

for year in years:
    if calendar.isleap(year):
        leap_years.append(year)

print(leap_years)

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

[展开全文]
 b = []
>>> a = [1,'string',10.11]
>>> type(a)
<class 'list'>
>>> a
[1, 'string', 10.11]
>>> for i in a:
	if type(i) == type("aaa"):
		b.append(i)
		print(b)

		
['string']
b = []

while True:
    a = input()
    if a == "q":
        break
    b.append(a)
b.sort()
print(b)
>>> citys=["suzhou","shanghai","hangzhou","nanjing"]
>>> codes=["0512","021","0571","025"]
>>> a=zip(citys,codes)
>>> a
<zip object at 0x0000027ED4360888>
>>> type(a)
<class 'zip'>
>>> print(a)
<zip object at 0x0000027ED4360888>
>>> dict(a)
{'hangzhou': '0571', 'shanghai': '021', 'nanjing': '025', 'suzhou': '0512'}
def splitNum(number):
          a = []
          number_str = str(number)
          b = len(number_str)
          c = [10**i for i in range(b)]
          c = sorted(c,reverse=True)
          for i in c:
                    x=number//i
                    y=number%i
                    a.append(x)
                    number = y
          print(a)
                    
if __name__ == "__main__":
          number = int(input())
          splitNum(number)
name_list = ['tianming','lufei','tom','yourou']

while True:
          name_input = input()
          if name_input in name_list:
                    print("bingo")
                    break
          else:
                    print("try again")

 

[展开全文]
#/usr/bin/env python
#coding=utf-8


def add_F(x,y):
          return x+y
def sub_F(x,y):
          return x-y
def mul_F(x,y):
          return x*y
def div_F(x,y):
          return x/y


if __name__ =="__main__":
          while True:
                    num_first = int(input("请输入第一个数字:"))
                    num_last  = int(input("请输入第二个数字:"))
                    value = input("请输入要执行的计算:")
                    if value == "q":
                              break
                    elif "+" in value:
                              result = add_F(num_first,num_last)
                              print("结果是{}".format(result))
                    elif "-" in value:
                              result = sub_F(num_first,num_last)
                              print("结果是{}".format(result))
                    elif "*" in value:
                              result = mul_F(num_first,num_last)
                              print("结果是{}".format(result))
                    elif "/" in value:
                              result = div_F(num_first,num_last)
                              print("结果是{}".format(result))
                    else:
                              print("输入有误")
          

d = {}
score_list = []
while True:
          name = input()
          

          if name == "q" :
                    break
          else:
                    score = int(input())
                    d[name] = score
                    score_list.append(score)
                          
print(d)
print(score_list)
max_score = max(score_list)
for k in d:
          if d[k] == max_score:
                    max_name = k
avg_score = sum(score_list)/len(score_list)
print("{0}:{1}".format(max_name,max_score))
#!/usr/bin/env python
# coding=utf-8

def salary(work_day,normal_day,money):
      days = int(work_day) - int(normal_day)
      if  days < 0:
                days = abs(days)
                
                if days<=2:
                          money = int(money)
                          return(money)                                        
                elif days<=7 and days>=2:                                                  
                          money = int(money)*(1-0.1)  
                          return(money)    
                elif days>7 and days<=14:
                          money = int(money)*(1-0.5)
                          return(money)
                else:
                          money=0
                          return(money)
      elif days == 0:
           money = int(money)*(1+0.2)
           return(money)              
      else:
          print(money)
          money = int(money) + days*(int(money)/int(normal_day))
          return(money)              
     

if __name__ =="__main__":
      while True:
                normal_day = input("请输入应工作天数:")
                try:
                          
                          if normal_day == "q":
                              
                                    break
                          else:
                                    work_day = input("请输入实际工作天数:")
                                    money = input("请输入工资:")
                                    print("=========")
                                    money = salary(work_day,normal_day,money)
                                    print("工资为{}".format(money))
                except:
                          print("输入有误")
                else:
                          print("===========")
q
#/usr/bin/python
#coding:utf-8

def dv_17(number):
	if number % 17 == 0:
		return number

if __name__ == "__main__":
	list_number = []
	count = 0
	for i in range(100,1000):
		if dv_17(i):
			list_number.append(i)
			count +=1
#
	print(list_number)
	print(count)

 

[展开全文]
DAHUI · 2016-11-30 · 函数练习-1 0

25、已知:字典:{“name”: “python”, “book”: “python”, “lang”:”english”}
要求:将该字典的键和值对换。(注意,字典中有键的值是重复的)


''
'' >>> a = {"name": "python", "book": "python", "lang":"english"}
'' >>> from collections import defaultdict
'' >>> dd = defaultdict(list)
'' >>> for k,v in a.items():
'' ...     dd[v].append(k)
'' ...
'' >>> dict(dd)
'' {'english': ['lang'], 'python': ['name', 'book']}
'' >>> a
'' {'name': 'python', 'book': 'python', 'lang': 'english'}
'' >>> b = {v:k for k,v in a.items()}
'' >>> b
'' {'english': 'lang', 'python': 'book'}

 

[展开全文]
kokk · 2016-11-22 · 函数练习-1 0



>>>  import keyword
>>>  keyword.kwlist
['False', 'None', 'True', 'and', 'as', 'assert', 'break', 'class', 'continue', 'def', 'del', 'elif', 'else', 'except', 'finally', 'for', 'from', 'global', 'if', 'import', 'in', 'is', 'lambda', 'nonlocal', 'not', 'or', 'pass', 'raise', 'return', 'try', 'while', 'with', 'yield']

[展开全文]

1.import this

2.import kyword

 keyword.kwlist

5.divmod(100,3)取,商和余数

 round(100/3,3)取三位小数,四舍五入

7,decimal模块,fractions模块

9,print(r"c:\news")

[展开全文]