简体   繁体   English

条件表达式无法正常运行(Python)

[英]Conditional Expression not functioning properly (Python)

I am supposed to write a few lines of code to create a conditional expression (ternary operation) that evaluates to string "negative" if user_val is less than 0 and "non-negative" if 0 or greater than 0. 我应该写几行代码来创建条件表达式(三元操作),如果user_val小于0,则条件表达式为字符串“负”,如果0或大于0,则条件表达式为“非负”。

The code I currently have prints "negative" when the number is less than zero but when a number 0 or greater is assigned to user_val it doesn't print "non-negative." 当数字小于零时,我当前拥有的代码将显示“负数”,但是将0或更大的数字分配给user_val时,它不会显示“非负数”。

user_val = -9

cond_str = 'negative' 
cond_str if (user_val < 0) else
cond_str == 'non-negative'

print(user_val, 'is', cond_str)

I tried defining cond_str as an empty string and I also tried swapping around the statements so that cond_str=='non-negative' would go first. 我尝试将cond_str定义为空字符串,并且还尝试在语句周围进行交换,以便首先使用cond_str =='non-negative'。 I also tried removing the second line of the code all together but it's still not working. 我还尝试一起删除了代码的第二行,但仍然无法正常工作。 Thanks for your help with this. 感谢您的帮助。 Any advice or suggestions would be very much appreciated! 任何意见或建议将不胜感激!

I think you mean to use: 我认为您的意思是使用:

cond_str = 'negative' if (user_val < 0) else 'non-negative'

The ternary operator must be on a single line, since Python is white-space sensitive. 由于Python对空格敏感,因此三元运算符必须在一行上。

I don't understand why you test an equality in the last statement. 我不明白为什么您要在上一条语句中测试相等性。

For me the easiest is the following: 对我来说,最简单的方法如下:

cond_str = 'negative' if user_val < 0 else 'non-negative'

You can chain an if statement with an assignation in Python to test which value you want to assign. 您可以将if语句与Python中的赋值链接起来,以测试要分配的值。 This is called « ternary operator ». 这称为“三元运算符”。

Youll want to build a conditional statement to do this in one line. 您将希望构建一个条件语句来在一行中执行此操作。 So: conditionalstatement = (userval >=0)? 所以:conditionalstatement =(userval> = 0)? "non-negative" : "negative"; “ non-negative”:“ negative”; this way the 0 is registered as a non-negative. 这样,0将被注册为非负数。 a simple program that you could expand on by using index or array. 一个简单的程序,您可以使用索引或数组对其进行扩展。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM