可以在Python的“ print”语句中放入“ if”语句吗?

时间:2019-05-01 22:08:09

标签: python if-statement printing

因此,如果条件为真,我希望字体为红色,否则以绿色字体打印。查看下面的代码作为示例。

#if Money is greater than or equal to 0, then the font color will be green. Otherwise, the font color will be red.

from colorama import Fore
Cash = int(input("Enter random number here (This is how much money a player has)"))
print("Money: ", if (Cash) >= 0: Fore.GREEN + (Cash), else: Fore.RED + (Cash))

#this does not work on python, is there a way you can fix this?
#If I input a positive number, I get a green font.
#If I input a negative number, I get a red font.
#The output only says "SyntaxError: invalid syntax"

1 个答案:

答案 0 :(得分:0)

您只需要重新排列您的声明即可。

将其想象为“在这种情况下,打印此...,在其他情况下打印”。

print("Money: ", Fore.GREEN + str(Cash) if Cash >= 0 else Fore.RED + str(Cash))