牛客网Python入门【06条件语句】

一、判断布尔值

要求输入0 或者 1,输出"Hello World!"或者"Erros!"。

print("Hello World!"if input()==True else "Erros!")

这是最简洁的解决方法。

或者使用bool()函数:当bool()函数没有参数时,它返回False;bool()函数有一个参数时,它返回该参数的布尔值。对于数字类型,非零值被视为True,而0(零)被视为False;对于字符串,非空字符串被视为True,而空字符串''被视为False

def judge(x):
    if x==True:
        print("Hello World!")
    if x==False:
        print("Erros!")

judge(bool(int(input())))

因此,一定要用int(inout())才能正确输出,因为input()函数默认类型为字符型str,所以在进行bool()时,只要有输入就会返回True。

二、判断列表是否为空

要求创建一个空列表my_list,如果列表为空,请使用print()语句一行输出字符串'my_list is empty!',否则使用print()语句一行输出字符串'my_list is not empty!'。

我用了bool()函数,因为对于列表、元组、字典等容器类型,在bool()函数中:非空容器被视为True,而空容器被视为False。

def judge(a):
    if bool(a)==True:
        print("my_list is not empty!")
    if bool(a)==False:
        print("my_list is empty!")

my_list=[]
judge(my_list)

 两种解法

# 创建一个空列表my_list
my_list = []
# 法1
if len(my_list)==0:
    print('my_list is empty!')
else:
    print('my_list is not empty!')
     
# 法2
 if not my_list:
     print('my_list is empty!')
 else:
     print('my_list is not empty!')

或者

my_list = [] 
if my_list: print("my_list is not empty!") 
else: print("my_list is empty!")

总之可以根据列表长度或者 if (not) my_list判断列表是否为空。

三、禁止重复注册

要求创建一个依次包含字符串'Niuniu'、'Niumei'、'GURR'和'LOLO'的列表current_users,

再创建一个依次包含字符串'GurR'、'Niu Ke Le'、'LoLo'和'Tuo Rui Chi'的列表new_users,

使用for循环遍历new_users,如果遍历到的新用户名在current_users中,

则使用print()语句一行输出类似字符串'The user name GurR has already been registered! Please change it and try again!'的语句,

否则使用print()语句一行输出类似字符串'Congratulations, the user name Niu Ke Le is available!'的语句。(注:用户名的比较不区分大小写)

current_users=['Niuniu','Niumei','GURR','LOLO']
new_users=['GurR','Niu Ke Le','LoLo','Tuo Rui Chi']

for x in new_users:
    num = 0
    for y in current_users:
        if x.lower()==y.lower():
            num=1
            print("The user name %s has already been registered! Please change it and try again!"%x)
    if num == 0:
        print("Congratulations, the user name %s is available!"%x)

本来想通过一行代码print("Congratulations, the user name %s is available!" % x if num == 0 else "")输出非重复注册的情况,但if num == 0 else ""判断语句的else的情况必须加上,否则错误,但添加之后会输出空行,不符合输出要求。

或者(注意else的位置即可)

for i in new_users:
    for j in current_users:
        if i.lower() == j.lower():
            print(f'The user name {i} has already been registered! Please change it and try again!')
            break
    else:
        print(f'Congratulations, the user name {i} is available!')

更好的方法(不用嵌套循环) 

current_users = ['Niuniu','Niumei','GURR','LOLO']
new_users = ['GurR','Niu Ke Le','LoLo','Tuo Rui Chi']
current_users_L = [i.lower() for i in current_users]   #再来一个列表存储变小写后的字符串

for i in new_users:
    if i.lower() in current_users_L:  #直接判断新表中小写后的字符串是否在列表中
        print('The user name {} has already been registered! Please change it and try again!'.format(i))
    else:
        print('Congratulations, the user name {} is available!'.format(i))

 四、计算菜品价格

要求输入一个字符串表示菜品。输出该菜品的价格。

def computeprice(x):
    if x=="pizza":
        print(10)
    elif x=="rice":
        print(2)
    elif x=="yogurt":
        print(5)
    else:
        print(8)
computeprice(input())

还可以使用字典实现

dict={"pizza":10,"rice":2,"apple":8}
print(dict[input()])

不过本题设置的条件是为了练习条件语句,因此有“剩余的价格为8”这种描述,而用字典实现这种比较困难。 (事后发现不困难,只是掌握的知识不足)

dict = {'pizza': 10, 'rice': 2, 'yogurt': 5} 
print(dict.get(input(), 8))
# 如果input()是dict的键,那么根据input()去找值,如果temp不是dict的键,那么返回8

用一个get()函数就能解决。 

  • 字典名.get(k,value)
  • 如果key值存在,那么返回对应字典的value,不会用到自己设置的value;
  • 如果key值不存在.返回None,但是不会把新设置的key和value保存在字典中;
  • 如果key值不存在,但设置了value,则返回设置的value;

五、计算绩点

要求需要根据他的成绩计算他的平均绩点,假如绩点与等级的对应关系如下表所示。请根据输入的等级和学分数,计算牛牛的均绩(每门课学分乘上单门课绩点,求和后对学分求均值)。

num = []
num_1 = []
num_2 = []
num_3 = []
dict = {"A": 4.0, "B": 3.0, "C": 2.0, "D": 1.0, "F": 0}
while True:
    grade = input()
    num.append(grade)
    if grade == 'False':
        num.remove(grade)
        break
        
for i in range(len(num)):
    if i % 2 == 0:
        num_1.append(num[i])
        num_3.append(dict[num[i]])
    else:
        num_2.append(int(num[i]))
count = 0

for j in range(len(num_2)):
    count += num_2[j] * num_3[j]
print("{:.2f}".format(count / sum(num_2)))

破题目毁我青春,谁家算平均绩点不除科目数,除学分和是谁想出来的好办法。

评论区简洁一些的办法,输入时不用通过一个大列表做临时存储再分表,而是输入即存到对应列表。

# 吐槽一下这个狗屁题目描述,不清不楚,还考语文阅读理解? “求和后对学分求均值” 很难理解成“绩点的和” 除以 “学分的和”
# 实际上也就是一个字典取值,求和,做个除法,很简单的逻辑;出题人语文水平可以适当提升一下
# 很多题目都是参考菜鸟教程的例子改编来的,换汤不换药,确实省事

dict1 = {"A": 4.0, "B": 3.0, "C": 2.0, "D": 1.0, "F": 0}
list1 = []
list2 = []
while True:
    grade = input()
    if grade == "False":
        break
    else:
        score = int(input())
        list1.append(dict1[grade] * score)
        list2.append(score)
print('{:.2f}'.format(sum(list1) / sum(list2)))

 六、验证登录名与密码

要求使用if-else语句,根据输入的用户名ID和密码,判断该用户等否登录。

name=input()
code=input()

if name=='admis' and code=='Nowcoder666':
    print("Welcome!")
else:
    print("user id or password is not correct!")

 

 

  • 15
    点赞
  • 16
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值