User Tools

Site Tools


python

This is an old revision of the document!


Bra moduler

  • pyserial – Comport
  • matplotlib – Matlabliknande plotverktyg
  • numpy – Matlabliknande matte
  • pandas – Importera och exportera till olika filformat, ex CSV, tydligen också för att behandla data

Official reference

Saker jag vill ha svar på

  • Grundläggande datastrukturer i Python
  • Grundläggande datastrukturer i NumPy
  • Grundläggande datastrukturer i Pandas
  • Grundläggande datastrukturer i Matplotlib
  • Hur man läser syntaxguide i pythons dokumentation
  • Hur man använder context managers

Cheat sheet

empty_list = []
 
# Tuples are immutable, can contain different datatypes
empty_tuple = ()
populated_tuple = (1, 2, "Kalle", 4.32)
singleton_tuple = (3,)
 
# Ranges are also immutable
r1 = range(0,20,2) # Start stop step
 
# Strings
single_str = 'Single quotes allows "double quotes" to be embedded'
double_str = "Single quotes allows 'single quotes' to be embedded"
triple_str = '''Can be initiated with either single or double quotes
                and can span multiple lines, including all whitespaces.'''
no_escape = r"This string doesn't escape where the \backslash character is encountered"
concatenation = 'Literals' " can be concatenated" ''' in this
way actually'''
 
 
# Dictionaries, keys must be hashable
>>> a = dict(one=1, two=2, three=3)
>>> b = {'one': 1, 'two': 2, 'three': 3}
>>> c = dict(zip(['one', 'two', 'three'], [1, 2, 3]))
>>> d = dict([('two', 2), ('one', 1), ('three', 3)])
>>> e = dict({'three': 3, 'one': 1, 'two': 2})
>>> a == b == c == d == e
True
>>> empty_dict = {}
 
my_dict = {'shit': 1337, 'man': 2021, 'dude':1991}
all_keys = list(my_dict)
leet = my_dict['shit']
 
# Set types must contain hashable objects. They are not ordered and cannot be indexed
>>> my_pants = {1, 2, 'shit', 'dude'}
>>> 'shit' in my_pants
True
 
# Byte objects are very similar to strings, but each character has a value 0-255
# They are created in the same way, but with the prefix 'b'
my_bytes = b'Yoman!'
ten_zero_bytes = bytes(10)
int_to_bytes = bytes([10])
int_to_bytes_again = bytes([10, 4, 21, 0, 255])
my_bytes = 'This is a string'.encode()
my_str = my_bytes.decode()
 
 
# Print formatted outputs
print("Id: {0}, value: {1:02X}\n".format(my_id, my_hex_value))
 
# Print without newline
print("No newline after this!", end='')

Parser

import argparse
 
def parse_arguments():
    parser = argparse.ArgumentParser(description="Some description",epilog="Huh?")
 
    parser.add_argument('integers', metavar='N', type=int, nargs='+', 
                         help='an integer for the accumulator')
 
    parser.add_argument('--sum', dest='accumulate', action='store_const',
                         const=sum, default=max, help='sum the integers (default: find the max)')
 
    parser.add_argument('-v', '--verbose', action='store_true', help='Verbose mode')
 
    args = parser.parse_args()
    return args
 
 
def main():
    args = parse_arguments()
    if args.verbose:
        print(dir(args))
 
if __name__ == '__main__':
    main()

Signals

Signals python documentation

import signal
 
def signal_handler_C_c(sig, frame):
    print('C-c detected, exiting..')
 
def main():
    signal.signal(signal.SIGINT, signal_handler_C_c)
 

Exceptions

https://docs.python.org/3/tutorial/errors.html

# Catch exceptions
a_list = ['yo', 'man']
try:
  print(a_list[3])
except IndexError:
  print("Index out of range! :(")
 
 
a_list = ['yo', 'man']
try:
  print(a_list[3])
except Exception as e:
  print("Ett fel har uppstått...")
  print(e)
  print(type(e))
# Raise exceptions:
raise ValueError("Passed array is not of the right shape")
python.1627898299.txt.gz · Last modified: 2022/09/12 00:30 (external edit)

Except where otherwise noted, content on this wiki is licensed under the following license: CC0 1.0 Universal
CC0 1.0 Universal Donate Powered by PHP Valid HTML5 Valid CSS Driven by DokuWiki