Python基础习题练习及解析(1)

91 阅读2分钟

**input**  
 使用变量接收一个人名 然后print输出 welcome 人名



name = input() print(f" welcome{name}!")


**字符串 :输入 ‘abcd1234’ 输出 ‘bd24’**



string = "abcd1234" print(string[1::2])


**if**  
 1.从控制台输入要出的拳 —石头(1)/剪刀(2)/布(3)  
 2.电脑随即出拳 (随机数字 import random random.randint())  
 3.比较胜负  
 石头 胜 剪刀  
 剪刀 胜 布  
 布 胜 石头



user_choose = int(input("请输入要出的拳———石头(1)/剪刀(2)/布(3):"))
computer_choose = random.randint(1, 3)
if (user_choose == computer_choose):
    print(computer_choose)
    print("双方平局!")
elif (user_choose != 3) and (user_choose - computer_choose == -1):
    print(computer_choose)
    print("玩家胜利!")
elif (user_choose == 3) and (user_choose - computer_choose == 2):
    print(computer_choose)
    print("玩家胜利!")
else:
    print(computer_choose)
    print("电脑胜利!")

**判断闰年**  
 用户输入年份year, 判断是否为闰年?  
 (year能被4整除但是不能被100整除 或者 year能被400整除, 那么就是闰年)



year = int(input("请输入年份:"))
if ((year % 4 == 0) and (year % 100 != 0)) or (year % 400 == 0):
    print(f"{year}年是闰年")
else:
    print(f"{year}年不是闰年")

**使用while循环将字符串 abcdefghijklmnopqrstuvwxyz 倒序**



num_str = "abcdefghijklmnopqrstuvwxyz" num_len = len(num_str) n = 0 num_list = [] while n < len(num_str): num_list.append(num_str[num_len - n - 1]) n += 1 print(num_list)


**创建一个字典 ,包含基础数据类型和列表、元祖、字典各种数据类型 并遍历打印所有的值 如{‘a’:(1,2),‘b’:(3,4),“c”:{5:6,7:8}} 打印 1 2 3 4 6 8**



dict_num = {'a': [1, 2], 'b': (3, 4), "c": {5: 6, 7: 8}} for k, v in dict_num.items(): if type(v) == tuple: num_tuple = v len_v = len(v) for i in num_tuple: print(i) if type(v) == list: num_list = v len_v = len(v) for i in num_list: print(i) if type(v) == dict: num_dict = v len_v = len(v) for i, j in num_dict.items(): print(j)

**杨辉三角**



import copy num_list_01 = [1] num_list_02 = [1] num_list_05 = [] print(num_list_01) for i in range(10): num_list_01.append(0) num_list_03 = copy.deepcopy(num_list_01) num_list_02.insert(0, 0) num_list_04 = copy.deepcopy(num_list_02) n = len(num_list_02) num_list_05.clear() for j in range(n): num_list_05.append(num_list_03[j] + num_list_04[j]) num_list_01 = copy.deepcopy(num_list_05) num_list_02 = copy.deepcopy(num_list_05) print(num_list_05)


**使用循环去除列表中的重复值**



letter_list = ['a', 'b', 'c', 'd', 'a'] letter_list_len = len(letter_list) list_new = [] # if i not in list_new for i in range(letter_list_len): for j in range(i + 1, letter_list_len): if letter_list[i] == letter_list[j]: break else: list_new.append(letter_list[i]) print(list_new)


**有字符串"k:1|k1:2|k2:3|k3:4" 处理成字典 {‘k’:1,‘k1’:2…}**



str_a = "k:1|k1:2|k2:3|k3:4" str_b = str_a.split('|') list_c = [] list_k = [] list_v = [] for i in str_b: kv = i.split(':') list_c = list_c + kv for i in range(8): if i % 2 == 0: list_k.append(list_c[i]) else: list_v.append(int(list_c[i])) dict_new = zip(list_k, list_v) print(dict(dict_new))