Python练习小程序合集

1.Pig Latin翻译器

把输入单词的第一位移到末位,然后加上“ay”,代码如下:

def piglatin():
    word = input('请输入一个单词')
    if len(word)>0 and word.isalpha():
        str_word =str(word);
        str_word_1 = str_word[0].lower();
        new_str_word = str_word[1:];
        print(new_str_word+str_word_1+'ay');
    else:
        print('只能输入有效单词,请重新输入')
        piglatin()
piglatin()

2.

打印1到100自然数,当这个数字是3的倍数时,将其替换为Fizz,当这个数字是5的倍数时,将其替换为Buzz,当这个数既是3的倍数也是5的倍数时,将其替换为FizzBuzz,打印完成后,统计其中Fizz的数量,代码如下:

n = []
m = range(1,101)
for i in m:
    n.append(i) #append()方法用于在列表末尾添加新的对象
    if i%3 == 0 and i%5 != 0:
        n[i-1] = 'Fizz'; #可以写成n[i-1]也可以写成n[n.index(i)]
    elif i%5 == 0 and i%3 != 0:
        n[n.index(i)] = 'Buzz';
    elif i%5 == 0 and i%3 == 0:
        n[n.index(i)] = 'FizzBuzz';
print(n)

def Fizz_count(list):
    a = 0
    for t in list:
        if t == 'Fizz':
            a += 1
    return a
print('Fizz有{}个'.format(Fizz_count(n)))

3.水果店

定义一个字典prices,包含水果名称和价格,一个字典stock,包含水果名称和剩余数量,一个字典food_2,包含要购买的水果名称和数量,写一个方法来计算购买food_2中的水果共需要多少钱和购买后的水果剩余量,要求:购买前水果剩余数量大于0才可进行购买,当购买量大于剩余量时,则购买数量为剩余数量,代码如下:

prices = {'banana':4,'apple':2,'orange':1.5,'pear':3}
stock = {'banana':6,'apple':0,'orange':32,'pear':15}
food_2 = {'banana':8,'apple':3,'orange':2}

def compute_bill_3(food_2,prices,stock):
    money_1 = 0
    money_2 = 0
    for fruit in food_2.keys():
        if stock[fruit]>0 and food_2[fruit]<=stock[fruit]:
            money_1 += prices[fruit]*food_2[fruit]
            print(fruit + '剩余数量为{}'.format(stock[fruit]-food_2[fruit]))
        elif stock[fruit]>0 and food_2[fruit]>stock[fruit]:
            print(fruit + '剩余数量为0')
            money_2 += prices[fruit]*stock[fruit]
    print('共需花费{}元'.format(money_1+money_2))

4.算成绩

#task1
#定义三个字典代表三个学生的成绩单
lilei={"name":"Lilei","homework":[],"quizzes":[],"tests":[]}
hanmeimei={"name":"Hanmeimei","homework":[],"quizzes":[],"tests":[]}
jim={"name":"Jim","homework":[],"quizzes":[],"tests":[]}

#task2
#三个学生的成绩
lilei['homework'] = [90,97,75,92]
lilei['quizzes'] = [88,40,94]
lilei['tests'] = [75,90]
hanmeimei['homework'] = [100,92,98,100]
hanmeimei['quizzes'] = [82,83,91]
hanmeimei['tests'] = [89,97]
jim['homework'] = [0,87,75,22]
jim['quizzes'] = [0,75,78]
jim['tests'] = [100,100]

#task3
#定义一个列表,列表里的三个元素为task1中创建的包含学生成绩的字典
student = [lilei,hanmeimei,jim]

#task4
#遍历列表student,print每个学生的name,homework,quizzes,tests
for name_dictionary in student:
    print(name_dictionary.get('name'))
for name_dictionary in student:
    print(name_dictionary.get('homework'))
for name_dictionary in student:
    print(name_dictionary.get('quizzes'))
for name_dictionary in student:
    print(name_dictionary.get('tests'))

#task5
#定义一个函数,入参为列表,计算列表内元素的平均值
def average(number):
    return sum(number)/len(number)

#task6
#定义一个函数,入参为代表一个学生成绩单的字典,返回学生的加权平均分
#homework占10%
#quizzes占30%
#tests占60%
def get_average(student):
    avg_homework = average(student['homework'])
    avg_quizzes = average(student['quizzes'])
    avg_tests = average(student['tests'])
    return avg_homework*0.1+avg_quizzes*0.3+avg_tests*0.6

#task7
#定义一个函数,入参为一个数字,按以下规则给分数划分等级
#大于等于90,返回A
#大于等于80,返回B
#大于等于70,返回C
#大于等于60,返回D
#其它,返回F
def get_letter_grade(score):
    if score >= 90:
        return 'A'
    elif score >= 80 and score < 90:
        return 'B'
    elif score >= 70 and score < 80:
        return 'C'
    elif score >= 60 and score < 70:
        return 'D'
    else:
        return 'D'
#print(get_letter_grade(get_average(jim)))

#task8
#定义一个函数计算班级平均分,以一个列表为参数
#这个列表里包含定义三位学生成绩的字典
def get_class_average(class_list):
    result = []
    for student_name in class_list:
        result.append(get_average(student_name))
    return average(result)

5.战船小游戏

from random import randint

board = []
for i in range(5):
    board.append(['O']*5)

def print_board(board_in):
    for row in board_in:
        print('  '.join(row))
print_board(board)

def random_row(board_in):
    return randint(1,len(board_in))
def random_col(board_in):
    return randint(1,len(board_in))

ship_row = random_row(board)
ship_col = random_col(board)
#print('行数是'+str(ship_row))
#print('列数是'+str(ship_col))

for turn in range(4):
    guess_row = int(input('猜猜船在第几行:'))
    guess_col = int(input('猜猜船在第几列:'))

    if guess_row == ship_row and guess_col == ship_col:
        print('恭喜你!击沉了我的战船')
        break
    else:
        if guess_row not in range(1, 6) or \
            guess_col not in range(1, 6):
            print('超出了范围')
        elif board[guess_row-1][guess_col-1] == 'X':
            print('这个地方已经选择过啦!')
        else:
            print('你没有击中我的战船!')
            board[guess_row-1][guess_col-1] = 'X'
    if 3-turn != 0:
        print('还剩{}次机会'.format(3-turn))
    else:
        print('没有机会啦,你输了')
    print_board(board)


6.数字求和

写一个方法,接受一个正整数为入参,返回这个数字各个位数上的数字之和

#方法一
def digit_sum(num):
    result = []
    while num:
        result.append(num% 10)
        num= num// 10
    result.reverse()
    return sum(result)

#方法二
def digit_sum_2(num):
    return sum(list(map(int, str(num))))

#方法三
def digit_sum_3(num):
    result = []
    while num:
        num, i = divmod(num, 10)
        result.append(i)
    result.reverse()
    return sum(result)

7.

#task1
#求一个数字的阶乘
def factorial(num):
    result = 1
    for i in range(1,num+1):
        result *= i
    return int(result)

#task2
#判断一个数字是否为质数
def is_prime(num):
    for n in range(2,num):
        if num%n == 0:
            return False
        else:
            return True

8.倒序输出字符串

#方法一
def reverse(text):
    list = []
    list_2 = []
    for i in str(text):
        list.append(i)
    for t in range(len(list)):
        list_2.append(list[len(list)-1-t])
    new_text = ''.join(list_2)
    return new_text

#方法二
def reverse(text):
    list = []
    for i in str(text):
        list.append(i)
    new_list =  list[::-1]
    new_text = ''.join(new_list)
    return new_text

#方法三
def reverse(text):
    list = []
    for i in str(text):
        list.append(i)
    list.reverse()
    new_text = ''.join(list)
    return new_text

#方法四
def reverse(text):
    new_text = ''
    for i in text:
        new_text = i + new_text
    return new_text

9.

#task1
#接受一个字符串为入参,去掉其中的元音字母
def anti_vowel(word):
    list = []
    for items in word:
        list.append(items)
    for i in list:
        if i in ['a','e','i','o','u']:
            list.remove(i)
            new_word = ''.join(list)
        else:
            new_word = ''.join(list)
    return new_word

你可能感兴趣的:(Python)