use f strings to limit number of decimal places: print('power to heat tank ',kWh, 'kWh') power to heat tank 9.333333333333 kWh print(f'power to heat tank {kWh:.2f}', 'kWh') power to heat tank 9.33 kWh use f strings to pad numbers: print( f'{diff_days:6}', f'{diff_dunits:6}', f'{diff_dunits/diff_days:3.2f}' ) 364 10301 28.29 use f strings to print in hex: print(f'{128:x}') 80 use f strings with \n for new lines: print(f' hello \n world') hello world use the print 'sep' arg to remove leading space after a newline print('hello','\nl','world') hello world print('hello','world',sep='\n') hello world
1.1 use Del to backspace delete 1.2 !LineEdit is a "must have" for using the command line shell 1.3 Enter to quit help() mode or "q" if part way through show 1.4 comments start with hash # and continue to end of line 1.5 use 4 spaces per indentation level 1.6 Limit all lines to a maximum of 79 characters. - use backslash or preferably parentheses eg. xxxxx = 1 + 2 + 3 + 4 + 5 + 6 + 7 + 8 + 9 + 10 + 11 + 12 + 13 xxxxx = (1 + 2 + 3 + 4 + 5 +6 + 7 + 8 + 9 + 10 + 11 + 12 + 13) print('hello \ world') # multiline literal print(''' If you answer "yes" to the prompt, python will die! and you will need to reboot RISC OS to resurrect it ''') 1,7 Use CamelCase for classes and snakecase - lower_case_with_underscores for functions and methods 1.8 "Dunder names" eg, __all__ (Dunder is Double Underscore) 1.9 module sys defines prompts, path, etc >>>sys.ps1 = '--> ' --> --> print(sys.platform) --> riscos 1.A To recall last expression output use underscore _ eg >>>2+2 4 >>>_+2 6 >>> 2.1 Allow StrongED to copy and paste into a TaskWindow load the TaskWindow ModeFile change: cs-VToTask to: cs-V ReleaseShiftCtrl CB_Paste change: cs-C ToTask to: cs-V ReleaseShiftCtrl CB_Copy 2.2 StrongED search direcyory ctrl-E,ctrl-D 4.1 print output goes to standard out sys.stdout (2) error output goes to standard error sys.stderr (1) eg python3 mypgm.py 1>a 2>b eg Dir python3 .!RunImage 1>^.stdout (puts output in same dir as app) 5.0 Functions
5.1 how to define a function - def function_name(parameters): """docstring""" statement(s) 5.2 Trigonometric functions import math opp = 65 adj = 216 rad = math.atan2(opp,adj) deg = math.degrees(rad) print(rad, deg) 5.3 Date functions >>>from datetime import date >>>pr = date.today() ; print(pr) 2021-07-30 >>>from datetime import datetime >>>print(datetime.now()) 2021-07-30 18:10:18.590000 >>>from datetime import datetime >>>date1 = datetime.strptime('24 09 40','%d %m %y' ) >>>date2 = datetime.strptime('24.09.42','%d.%m.%y' ) >>>print(date1, date2) 2040-09-24 00:00:006.0 More syntax
6.1 A String cannot be changed via indexed assignment 6.2 Python has No CASE statement - if if,elif instead 6.3 For with range import math adj = 216 for opp in range(12,90,12): rad = math.atan2(opp,adj) deg = math.degrees(rad) print(opp, deg) 6.4 To get a row number with open(csvfile, newline='') as f: reader = csv.DictReader(f) for r, row in enumerate(reader): print (r, row['days'], row['dunits']) 6.5 ifs and buts if x == 0: pass elif x == 1: print('x') print('is') print('one') elif x == 2: print('x is two') else: print('x is not 1,2,or 3') 6.6 a, b = b, a swaps without needing an intermediate variable 6.7 hexadecimal - see also f strings above hex(512) '0x200' int('8A',16) 138 6.8 get response at console retry = True while retry: ans = input("unset python variables?(y/n)\n") if ans == "y" or ans == "n": retry = False7.0 Classes
7.1 example of a class class BackDrop: """manage screen background picture""" def __init__(self): # name self is conventional self.pic = "pix.b01" class Paper: """paper for magazine""" def __init__(self): self.size = "A4" self.ream = 500 self.perbox = 5 papr = Paper() print(papr.size, papr.ream, papr.perbox) 7.2 Is Class same as Type? - see eg below rent = ( "r03",192, "r02",682) print(rent) print(type(rent)) ('r03', 192, 'r02', 682) <class 'tuple'>8.0 Communicating with the Operating System
8.1 Use the swi module to issue system commands (From Chris Johns Python Release Notes) swi.swi(arg1,arg2,arg3) allows Python code to call RISC OS SWIs. arg1 is the SWI number or name, arg2 is a format string for arg3, arg3 is the rest of the arguments. syntax of arg2 format string of single byte positional keys corresponding to an input or output register in the swi definition s = string b = block i = integer I = Unsigned integer? . = not used ; end of inputs, outputs follow # examples of RISC OS SWI commands import swi as swi swi("OS_Write0","s","Hello RISC OS World") # this works swi("OS_WriteC","i",10) # line feed swi("OS_WriteC","i",13) # carrier return swi("OS_Byte","i",0) # Os version swi("OS_CLI","s","hoff") # hourglass off RISC OS additions ----------------- os.get_filetype(object) returns the file type of a given object. os.set_filetype(object,type) will set it. 8.2 Use os.system to issue * (star) commands # example RISC OS * - star commands import os os.system('fx 0') # Os version os.system('cat') os.system('hon') # hourglass on os.system('hoff') showparm = "*path*" pr = os.system("show "+ showparm) ; print(pr) 8.3 Environment variables # print list - same as RISC OS show * import os for k, v in os.environ.items(): print(f'{k}={v}') 8.4 Stop execution of a script part way through import sys sys.exit("execution stopped") 8.5 use dot for slash inside Python shell but use slash for dot in Python script eg import sqlite3 con = sqlite3.connect('eg/db') 8.6 to reference parent directory - use ^.filename 8.7 CWD Current Working Directory >>> import os >>> cwd=os.getcwd() >>> print(cwd) SCSI::SSD.$.JR.Programz.PYTHON.eg_test.tkinter You can change the current working directory import os os.chdir(path) .... Changing the current working directory in a subprocess does not change the current working directory in the parent process. This is true of the Python interpreter as well. You cannot use os.chdir() to change the CWD of the calling process. 8.8 find out where we are and set CSD def set_cwd_to_local_dir(): import os mypath = os.path.abspath(__file__) mydir = os.path.dirname(mypath) os.chdir(mydir) import os set_cwd_to_local_dir() print('cwd = ', os.getcwd())9.0 BUGS
9.1 There is a bug in RISC OS 3.8.python which sometimes leads to print output appearing in the wrong order. Use the print flush method to force immediate printing sys.stdout.flush() 9.2 Marshal Error probably a corrupted "pyc" file find and delete it - it will be regenerated 9.3 When pasting code from a webpage watch out for hard spaces. Symptons: SyntaxError: Non-UTF-8 code starting with '\xa0' in file ...
© 2021 JR