Hi,
I started my first Python script and it works but i wanted to expand it but i cant seem to find a way to verify if there exists a parameter:
prompt2 = prompt1.split(" ")
elif prompt2[0] == ‘test’:
if prompt2[1]:
print(prompt2[1])
I tried multiple ways to check if prompt2[1] contains anything or exists, can anyone help me out?
i tried that and it was the only thing that worked yes, but there is no way to check if prompt2[1] exists or contains anything? i tried this with len too and checked if the var exists if i remember correct.
If prompt2[1] didn’t exist, the length of the list would be <2. If the length of the list is >=2 then prompt2[1] exists. If it does exist, it contains something.
… i cant seem to find a way to verify if there exists a parameter:
Assuming prompt is a string, you can test it’s “truthiness” and optionally debug it with print:
Given
message_1 = "Hello world!"
message_2 = ""
Code
def main(prompt):
args = prompt.split()
if not args:
print("DEBUG: No args found")
return args
Demo
main(message_1)
# Out: ['Hello', 'world!']
main(message_2)
# DEBUG: No args found
# Out: []
Details
Splitting a string returns a list (of arguments in this case). If there are no arguments, the list will be empty. The boolean of an empty container is False, so you can directly test the container in an if statement.