How would make an if statement to print something if there is no output for the command?

Viewed 21

I have the winapps custom module. If the software is present, it prints the details; otherwise it does nothing.

How would I make an if statement to print something if the software wasn't found?

Here is the code:

with open('output3.txt', 'w') as f:
    for item in winapps.search_installed('ledger'):
        print(item, end='\n\n', file=f)
1 Answers

I'd suggest putting the matching apps into a list so you can easily test whether it's empty or not before deciding what to do with it:

ledger_apps = list(winapps.search_installed('ledger'))
if ledger_apps:
    with open('output3.txt', 'w') as f:
        print(*ledger_apps, sep='\n\n', end='\n\n', file=f)
else:
    print("Software wasn't found.")
Related