Python Basics

Data structure

empty list

1
list() or []

Check whether a list is empty

1
2
if list:
  do something
1
print(*live_ips, sep="\n")

All except the first one

1
sys.argv[1:]

String

concatenation

1
hexa = ' '.join([f'{ord(c):02X}' for c in word])

Trim

Use stri()

1
2
3
4
5
6
message = '     Learn Python  '

# remove leading and trailing whitespaces
print('Message:', message.strip())

# Output: Message: Learn Python

Padding

Forces the field to be left-aligned within the available space

1
	print(f'{"IP Address": <16}')

For more other format please see https://docs.python.org/3/library/string.html#format-specification-mini-language

Loop

You can increment not only by one when using range for i in range(3, 20, 2) the last argumnet is for the incremtal

Make the file callable

if name == ‘main’: main()

Method

Ignore return value

use underscore ignore specific value return

1
x, _, y = (1, 2, 3)

User inputs

default value

1
ip = input('Enter server IP: ') or '192.168.1.203'

get password

The response will not be displayed on the console to frustrate any shoulder-surfers

1
2
import getpass
password = getpass.getpass()

I/O

Current directory

1
os.path.dirname(os.path.realpath(__file__))

Exception

Handle the exception

1
2
3
 except Exception as e:
            print('[-] Listen failed: ' + str(e))
            sys.exit(1)

exit

exit(0) means a clean exit without any errors / problems

exit(1) means there was some issue / error / problem and that is why the program is exiting.

This is not Python specific and is pretty common. A non-zero exit code is treated as an abnormal exit, and at times, the error code indicates what the problem was. A zero error code means a successful exit.

This is useful for other programs, shell, caller etc. to know what happened with your program and proceed accordingly.

Use else

There is one big reason to use else - style and readability. It’s generally a good idea to keep code that can cause exceptions near the code that deals with them.

1
2
3
4
5
6
try:
    statements # statements that can raise exceptions
except:
    statements # statements that will be executed to handle exceptions
else:
    statements # statements that will be executed if there is no exception

OS dependent

Check whether the OS is Unix or widows

1
2
3
4
  if os.name == 'nt':
        socket_protocol = socket.IPPROTO_IP
    else:
        socket_protocol = socket.IPPROTO_ICMP

nt means that you are running windows, and posix mac

Buffering to output

Python’s standard out is buffered (meaning that it collects some of the data “written” to standard out before it writes it to the terminal). Calling sys.stdout.flush() forces it to “flush” the buffer, meaning that it will write everything in the buffer to the terminal, even if normally it would wait before doing so.

updatedupdated2024-01-172024-01-17