初学者Python程序流程某处出错

问题描述 投票:0回答:1
import random
bored = input('Are you bored? Please answer with a \'yes\' or \'no\'')
activities = ['Read a book', 'Watch a movie', 'Do some physical activities you enjoy', 'Play a card game', 'Bake something', 'Finish something you never fnished.']

if bored == 'no' or 'No':
    print('Then what are you doing here?')
else:
    if bored == 'yes' or 'Yes':
        print(random.choice(activities))

这个代码不做它应该做的。

谁能帮帮我?

python workflow flow
1个回答
0
投票

尝试一下。

import random 

bored = input("Are you bored? Please answer with a 'yes' or 'no': ") 

activities = ['Read a book', 'Watch a movie', 'Do some physical activities you enjoy', 'Play a card game', 'Bake something', 'Finish something you never fnished.']

if bored == 'no' or bored == 'No': 
  print('Then what are you doing here?') 
else: 
  print(random.choice(activities))

问题

  1. 条件不正确

这些条件不会产生你所期望的结果(即总是作为True)。

if bored == 'no' or 'No':

if bored == 'yes' or 'Yes':

使用这三个选项中的一个。

if bored == 'no' or bored == 'No':

if bored.lower() == 'no':

if bored in ('No', 'no'):
  1. 在booleans上不需要检查两个值(即 "否 "和 "是")。

简化这个。

if bored == 'no' or 'No':                  # incorrect conditional
  print('Then what are you doing here?') 
else:                                     
    if bored == 'yes' or 'Yes':            # no need to check for 'yes'
        print(random.choice(activities))

要:

if bored == 'no' or bored == 'No': 
    print('Then what are you doing here?') 
else:
    print(random.choice(activities))
© www.soinside.com 2019 - 2024. All rights reserved.