版权声明:本文为博主原创,若转载请附上博文链接 https://blog.csdn.net/liudong124521/article/details/89638197
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))