Python Forum
Condition check differences and how to organise code?
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Condition check differences and how to organise code?
#1
Hi guys,

so I'm not a novice to programming I have been programming in other languages such as Java for a while,but I am relatively new to Python with that being said I also am not an expert and have very little experience but I digress,

so to the confusion I am having and there is a couple of questions although this code contains a GUI using tkinter I decided not to post this in the GUI section as the question relates more to general coding that the GUI itself.

So the first question relates to strings, in the method find_filter_output I check to see if the user has entered text by getting the text from the text widget (find_text) if the user has not entered/ entered an empty string a message in the message box will appear saying invalid, I done this using if not findStr, and it works great(returns true) but when I tried another method which was if findStr == " " but when I did the latter by checking to see if it was == " ", it always gave false, so this lead to a bug in my simple program, it would print words that I didn't wanted to be printed or long story short it wouldn't print invalid, so why is/was this happening, what is the difference?

Also as you can see by my code it is very unstructured methods are in between declarations of variables, if I was coding this as a real project I would need my functions lets say at the top and the rest of my code below the functions, but as Python is an interpreted language and not a compiled language I had to define the functions before the button was called so the button knew these functions existed, if I did it the other way around I would get an error pretty much stating that no function exists, likewise for my text areas I put them above the functions so I could call methods from the text area variables in them said functions, if I declared the text area( text widgets ) this wouldn't work


import os
import sys
from subprocess import Popen,PIPE
from tkinter import *
from functools import partial

def sayHi():
    print("hi")

def execute_command(command):
    process = Popen(command,stdout=PIPE,stderr=PIPE)
    return process.communicate()

def filter_output(output):
    
    pyFiles = []
    lines = output.split("\n")
    
    for line in lines:
        words = line.split(" ")

        for word in words:
            contains = ".py" in word
            if(contains):
                pyFiles.append(word)

    return pyFiles

command = ['ls','-l']
out,err = execute_command(command)
outString = out.decode("utf-8")
files = filter_output(outString)

print(files)

root = Tk()
root.title("Program filter")
root.geometry("400x400")

frame_1 = LabelFrame(root,text="frame_1")
frame_1.pack(fill="both", expand="yes")
frame_2 = LabelFrame(root,text="frame_2")
frame_2.pack(fill="both", expand="yes")

text = Text(frame_2,height=18,width=100)
text.grid(column=1, row = 0)

def printToTextArea():
    text.delete(1.0,END)
    for file in files:
        text.insert(END,file + '\n')

def clearText():
    text.delete(1.0,END)

text_label = Label(frame_1,text="Find :: ")
text_label.grid(column = 3, row = 0,padx=5)
find_text = Text(frame_1,height = 1,width= 20)
find_text.grid(column = 4, row = 0, padx=5)

def find_filter_output(output,find):
    files = []
    lines = output.split("\n")
    contains = False
    found = False
    findStr = str(find)

    if not findStr:
        word = "invalid"
        files.append(word)
        return files

    for line in lines:
        words = line.split(" ")
        
        for word in words:
            
            print("find : " + find + "::" + "word :" + word)
            contains = findStr in word
            print(contains)
            if(contains):
                found = True
                print("found")
                files.append(word)
    
    if not found:
        word = "could not find any files with " + find
        print("not found")
        files.append(word)

    return files

def find_words(output):
    
    get_text = find_text.get("1.0",'end-1c')
    fls = find_filter_output(output,get_text)
    
    for file in fls:
        text.insert(END,file + '\n')

find_words_args = partial(find_words,outString)
button = Button(frame_1,text="Search",command=find_words_args)
button.grid(column=1, row=0, padx=5)
clear_button = Button(frame_1,text="Clear",command=clearText)
clear_button.grid(column = 2, row=0,padx=5)

def on_closing():
    root.destroy()

root.protocol("WM_DELETE_WINDOW",on_closing)
root.mainloop()

I ran out of space, in another general purpose programming language like C++ you could solve the problem with function declarations, but since Python is interpreted this cannot be done or can it? and what would the solution be apart from having global variables

Thanks! :)
Reply
#2
Quote:if I was coding this as a real project I would need my functions lets say at the top and the rest of my code below the functions,
Not if in a class.
Reply
#3
if not findStr is checking for False , various things evaluate to false
print(bool(False))
print(bool(None))
print(bool(0))
print(bool(''))
print(bool([]))
print(bool())
print(bool({}))
Output:
False False False False False False False
Only one thing will evaluate to true with if findStr == " "
print(bool(' ' == ' '))
Output:
True
See this thread for an example of re organising code to use classes.
Reply
#4
ok so I changed the code

def find_filter_output(output,find):
    files = []
    lines = output.split("\n")
    contains = False
    found = False
    findStr = str(find)

    if findStr == "":
        word = "invalid"
        files.append(word)
        return files
here I test to see if findStr is empty by saying if findStr == "", this works great but I noticed when I put a space in between the "" it does not work or become true

so

 if findStr == " "
will give a boolean false value even if findStr is empty, so why does adding a blank space between "" make a difference? I thought that even if I had countless of blank spaces between the "" it would still be an empty string no?
Reply
#5
A space is still a character so not the same as an empty string,
use the string method strip to remove leading and trailing white space.
print('' == '      '.strip())
print('' == ' '.strip())
print('' == '  test    '.strip())
Output:
True True False
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  Calculate the sum of the differences inside tuple PUP280 4 1,149 Aug-12-2022, 07:20 PM
Last Post: deanhystad
  Can I check multi condition for 1 item in a easy way? korenron 4 1,537 May-01-2022, 12:43 PM
Last Post: deanhystad
  Sort Differences in 2.7 and 3.10 Explained dgrunwal 2 1,330 Apr-27-2022, 02:50 AM
Last Post: deanhystad
  Code to check folder and sub folders for new file and alert fioranosnake 2 1,877 Jan-06-2022, 05:03 PM
Last Post: deanhystad
  Try,Except,Else to check that user has entered either y or n (Code block pasted) RandomNameGenerator 3 2,302 Jun-29-2021, 08:21 PM
Last Post: RandomNameGenerator
  Can somebody check what is wrong with my code? hplus_liberation 4 2,546 Sep-16-2020, 05:52 AM
Last Post: perfringo
  How to compare two PDFs for differences Normanie 2 2,354 Jul-30-2020, 07:31 AM
Last Post: millpond
  else condition not called when if condition is false Sandz1286 10 5,739 Jun-05-2020, 05:01 PM
Last Post: ebolisa
  [HELP] Nested conditional? double condition followed by another condition. penahuse 25 7,705 Jun-01-2020, 06:00 PM
Last Post: penahuse
  Differential equations with initial condition in Python (change a working code) Euler2 1 1,796 May-29-2020, 04:06 PM
Last Post: Euler2

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020