Python,如何修复if和else语句

时间:2019-07-16 18:51:38

标签: python-3.x

我要问的问题是:如果变量youngfamous都为True,则写一个打印“您必须富有!” 的表达式

使用输入'True' 'True'You must be rich!

进行采样输出

以下代码有什么问题?输出为'There is always the lottery...',而不是'You must be rich!'

young = (input() == 'True')
famous = (input() == 'True')

if (young == 'True') and (famous == 'True'):
    print('You must be rich!')
else:
    print('There is always the lottery...')

4 个答案:

答案 0 :(得分:2)

您的代码正在执行的操作是检查young是否等于字符串'True',以及famous是否等于字符串'True'。您要

if (young and famous):

或者如果您想写出来

if (young == True and famous == True):

答案 1 :(得分:2)

实际上,您需要根据字符串“ True”检查值,而实际上需要根据布尔值True对其进行检查。只需删除引号。

if (young == True) and (famous == True): 
    print('You must be rich!') 
else: 
    print('There is always the lottery...')

答案 2 :(得分:0)

第一和第二行实际上是布尔值。

输入函数求值后,将根据您键入的内容为您提供TrueFalse

因此if语句正在评估

if ({True or False} == 'True') and ({True or False} == 'True'):

由于布尔值和字符串表示形式永远都不等效,因此它将始终为false。

更改为此

if input('Are you young?')=='True' and input('Are you famous?')=='True':
  print('you must me rich!')
else:
  print('there is always the lottery')

答案 3 :(得分:0)

您的赋值运算符:

young = (input() == 'True')
famous = (input() == 'True')

将这两个变量设置为布尔值。但是,您的if语句会将它们与字符串进行比较:

if (young == 'True') and (famous == 'True'): 

在上述每个实例中,将单引号放在True周围,它将起作用,因为然后比较是针对布尔值True而不是字符串'True'。

请注意,您可以使用type关键字进行检查以显示其类型。即:

print(type(young))
print(type('True'))
相关问题