您能否仅通过查看一下来解释该代码的目的?

时间:2018-08-30 04:51:49

标签: python

result = 0
for num in numbers:
    is num < 0:
        result = result + 1 

3 个答案:

答案 0 :(得分:1)

那不是有效的Python-您需要保留空格/制表符,并且您拥有is而不是if

result = 0
for num in numbers:
    if num < 0:
        result = result + 1

代码将计算列表numbers中有多少个负数。例如:

>>> numbers = [-2,-1,0,1,2,3,4]
>>> for num in numbers:
...     if num < 0:
...         result = result + 1
...
>>> result
2

上一个问题显示了使用列表推导的更简单算法: Count negative values in a list of integers using Python?

答案 1 :(得分:0)

我不知道numbers列表在哪里定义(可能),但是我想它可能包含用户输入数字。 循环将对numbers列表中的负数进行计数,并将其存储在result变量中。

答案 2 :(得分:0)

您发布的内容不是您想要的 SELECT SectionName.UnderISMDocNumber FROM SectionName ORDER BY SectionName.UnderISMDocNumber; 而不是# Import dataframe into MySQL import sqlalchemy database_username = 'ENTER USERNAME' database_password = 'ENTER USERNAME PASSWORD' database_ip = 'ENTER DATABASE IP' database_name = 'ENTER DATABASE NAME' database_connection = sqlalchemy.create_engine('mysql+mysqlconnector://{0}:{1}@{2}/{3}'.format(database_username, database_password, database_ip, database_name)) frame.to_sql(con=database_connection, name='table_name_for_df', if_exists='append') 的无效python代码,请参见注释中的说明:

if

请记住,下次再问一个问题,请参阅How to AskHow to create a Minimal, Complete, and Verifiable example

或者您可以使用此:

is

或者,您也可以执行result = 0 # Create a variable and assign it to zero for num in numbers: # Iterate trough `numbers` list (or tuple or set..) whatever it is if num < 0: # Check if the current element smaller than zero result = result + 1 # if it is add 1 to variable `result` 而不是result = sum(1 for i in numbers if i<0)