python - Changing global variables within a function -
i'm new programming, , i'm looking advice on do. program i'm trying write need several numbers user. want use function test if user input number or not each of values entered. if input isn't number, want function keep asking number until 1 entered. want know if there better way pass value global variable other explicitly declaring each variable in function global. i'm unsure if there better way this...
rownum = none def numtest(c, d): x = false while x not true: try: c = raw_input(d) c = float(c) x = true except: print "the value entered isn't valid number, please try again." global rownum rownum = c numtest(rownum, "enter number of rows: ") print rownum # want use numtest function on several variables... # e.g. # numtest(contourlevel, "enter number of contour levels: ") # numtest(cellsize, "enter cell size: ") # numtest(labelsize, "enter label size: ")
just make function, returns instead of manipulating global, easier maintain!
def get_num(msg): while true: try: return int(raw_input(msg)) # number of rows should int except valueerror: print "the value entered isn't valid number, please try again." num_rows = get_num("enter number of rows: ") print num_rows
instead of numtest(cellsize, "enter cell size: ")
mentioned, should doing cellsize = get_num("enter cell size: ")
. it's better practice return values.
you make function more general int
, float
so:
def get_num(msg, type_=int): while true: try: return type_(raw_input(msg)) except valueerror: print "the value entered isn't valid number, please try again."
now can have:
x = get_num("test") # normal int x = get_num("foo", float)
Comments
Post a Comment