我的Python代码中预期的表达式错误[已关闭]

ff29svar  于 2023-07-01  发布在  Python
关注(0)|答案(2)|浏览(197)

**已关闭。**此问题为not reproducible or was caused by typos。目前不接受答复。

此问题是由打印错误或无法再重现的问题引起的。虽然类似的问题在这里可能是on-topic,但这个问题的解决方式不太可能帮助未来的读者。
22小时前关闭
Improve this question
我第一次尝试用python编写代码,我试图创建这个条件,但对于其他情况,它给了我预期的表达式。错误是Expected expression pylance [40,1]。这是代码:

import subprocess
import time
import datetime

def process_exists(process_name): 
    call = 'TASKLIST', '/FI', f'imagename eq {process_name}'
    output = subprocess.check_output(call).decode()
    last_line = output.strip().split('\r\n')[-1]
    return last_line.lower().startswith(process_name.lower())

if process_exists('chrome.exe'):
 def countdown(h, m, s):
 
    # Calculate the total number of seconds
    total_seconds = h * 3600 + m * 60 + s
 
    # While loop that checks if total_seconds reaches zero
    # If not zero, decrement total time by one second
    while total_seconds >= 0:
 
        # Timer represents time left on countdown
        timer = datetime.timedelta(seconds = total_seconds)
        
        # Prints the time left on the timer
        print(timer, end="\r")
 
        # Delays the program one second
        time.sleep(1)
 
        # Reduces total time by one second
        total_seconds += 1
 
 # Inputs for hours, minutes, seconds on timer
 h = (0)
 m = (0)`
 s = (0)

countdown(int(h), int(m), int(s))

else: 
print("no")

time.sleep(4)
z9ju0rcb

z9ju0rcb1#

看起来这是一个缩进问题。在Python中,没有括号或结束语句来将代码排列成块。相反,解释器使用行的缩进来将代码排列在控制语句下(if,else,for,while,with等)。在本例中,看起来第33-38行的缩进是错误的;你需要给它们添加一个缩进,这样它们就和if语句中的其他代码处于相同的缩进级别(和第12行的def关键字相同)。另外,在else之后缩进print语句。
我不知道你使用的是什么编辑器,但是如果你下载了任何好的Python IDE(例如PyCharm或VSCode),它应该会自动突出显示这些东西。

vltsax25

vltsax252#

代码中的问题在于缩进和else语句的使用。在Python中,else语句应该与if语句处于相同的缩进级别。此外,if块中的所有代码也应该缩进。以下是代码的更正版本:

import subprocess
import time
import datetime

def process_exists(process_name): 
    call = 'TASKLIST', '/FI', f'imagename eq {process_name}'
    output = subprocess.check_output(call).decode()
    last_line = output.strip().split('\r\n')[-1]
    return last_line.lower().startswith(process_name.lower())

if process_exists('chrome.exe'):
    def countdown(h, m, s):
        # Calculate the total number of seconds
        total_seconds = h * 3600 + m * 60 + s
 
        # While loop that checks if total_seconds reaches zero
        # If not zero, decrement total time by one second
        while total_seconds >= 0:
            # Timer represents time left on countdown
            timer = datetime.timedelta(seconds=total_seconds)
            # Prints the time left on the timer
            print(timer, end="\r")
            # Delays the program one second
            time.sleep(1)
            # Reduces total time by one second
            total_seconds -= 1

    # Inputs for hours, minutes, seconds on timer
    h = 0
    m = 0
    s = 0

    countdown(int(h), int(m), int(s))
else:
    print("no")

time.sleep(4)

相关问题