Some basic Python, starting Oct 22, 2018 for UBC course Math 441: Copyright Joel Friedman, 2018 ---------------------------------------------------------- --Some basic python commands: variables, types, file opening/closing, functions, etc. --Some basic Gurobi commands (especially addConstrs( ... ) ) --Look at some examples in http://www.gurobi.com/documentation/8.0/examples/a_list_of_the_gurobi_examp.html ---------------------------------------------------------- Specific Python words/commands you should know (aside from the basics about variables and assignment): quit(), help(), print(), open(), close(), while, for, range(), ---------------------------------------------------------- SOME RESOURCES: The following websites seem to have good info on Python General info: https://www.python.org https://wiki.python.org/moin/SimplePrograms https://www.w3schools.com/python/ https://www.pythonforbeginners.com Some Python basics: http://hetland.org/writing/instant-python.html ---------------------------------------------------------- WARNING -- You have to indent (with TAB key, it seems) e.g., x = 5 while x > 0 : print(x) --- now python complains that it was expecting indentation x = 5 while x > 0 : print(x) x = x-1 --- now python does what you want ---------------------------------------------------------- HELP: Typing help() into Python brings you to its interactive help shell. Typing the RETURN-key (sometimes ENTER-key) will get you back to python. >>> help() Welcome to Python 3.7's help utility! [Followed by a long message with some instructions] help> Now if you hit the RETURN-key: You are now leaving help and returning to the Python interpreter. [Followed by some more stuff] >>> Exercise: at the help prompt (i.e., help>), try typing (without quotation marks) the following: "keywords", "modules", "modules functions", "help", "topics", "FUNCTIONS" [These days you might use a search engine, e.g., Google, for help.] Then try running Gurobi and type "help()". You will get help specific to Gurobi... ---------------------------------------------------------- OBJECTS: [This section is to explain why you type commands like: m.optimize(), m.printAttr("X") in Gurobi, and in Python, C++, etc. This section is extremely abbreviated and imprecise.] (1) In the old days, you had to set up separate variables and arrays and declare their type (in most programming languages), e.g., float UBC_student_bill[1000] ; char UBC_student_names[1000][20] ; int UBC_student_num_of_courses[1000] ; int i ; float my_salary ; The first statement above sets up an array of 1000 floating point numbers which can be referred to as: UBC_student_bill[0], UBC_student_bill[1], ..., UBC_student_bill[999] UBC_student_bill[i], UBC_student_bill[i+j], etc., assuming i,j are of type Typically all such declarations had to appear in the start of a program. [These days most computer languages allow you to create new variables/arrays "dynamically", i.e., whenever you want during the time that you run your program. This feature introduced a number of problems, such as "memory leaks"...] (2) Later, for convenience, many languages allowed programmers to declare their own types or structures, which bundled together related variables, e.g., struct student { float bill ; char name ; int num_of_courses ; } To set up an array of 1000 UBC students, plus a variable "current_student" consisting of a single student, one would use the statement struct student UBC_student[1000] ; struct student current_student ; You would refer to the parts of the above students as follows: current_student.num_of_courses, current_student.bill, etc., UBC_student[32].bill, UBC_student[i].name, etc., assuming i is of type int (3) What is known as "object-oriented programming" began with the idea that structures should have their own built-in programs, and that a large software projects should divided the program into (1) (mostly) writing programs within each structure, and (2) a small amount of communication between the various structures. These structures are typically called "classes", and variables declared to be of such a type is called an "object" (of the class). So when you type m.optimize(), m.printAttr("X") you are running the programs (built by the people at Gurobi): optimize (which takes no input) printAttr (which needs a string, such as "X", as input) which are built into a class (each "instance" or "object" of which forms an LP/IP/QP/etc. model). When you write my_lp = read("myTSPsolver.lp") the Python/Gurobi reads your file "myTSPsolved.lp" and creates the object "my_lp" whose class is that of an LP/IP/QP/etc. model. So typing my_lp.optimize() runs the program optimize(), which your object "my_lp" has built into it. Object-oriented program is designed to (a) divide up tasks so that you can modify a small part of a program without having to know the entire program, and (b) make software bugs easier to detect (hopefully if you have a subtle bug, you can at least tell which class(es) is at fault), (c) etc. (4) These days there are a number of variants on the idea of object-oriented programming. In general, a lot of software engineering is geared towards large computer programs involving many independent parts and many programmers. ---------------------------------------------------------- VARIABLES AND ASSIGNMENT: Python allows you to introduce new variables whenever you want and does not force you to declare their type. Strings are specified in single quotes or double quotes. E.g. >>> a = "Hi there." >>> a 'Hi there.' >>> print(a) Hi there. >>> print(a+a) Hi there.Hi there. Python understands "a+a" to mean two copies of the string a , provided that the variable a is a string. Note that there is a difference between typing "a" and "print(a)" in Python. There are special characters like "\n" for "new line" (or "carriage return" or "return"). >>> a = "Hi there.\nHow are you?" >>> a 'Hi there.\nHow are you?' >>> print(a) Hi there. How are you? If the variable a is an integer, then a + a is the usual addition, and a ** a is "a to the power a": >>> a = 34 >>> a + a 68 >>> a ** a 11756638905368616011414050501310355554617941909569536 >>> print(a ** a) 11756638905368616011414050501310355554617941909569536 Notice that "==" tests whether the two sides are equal. >>> 3 == 4 False >>> 3 == 2+1 ---------------------------------------------------------- LOOPS: How to write repetitive tasks in Python. Above we gave an example using the "while" statement. Here is another example, upon typing the two lines: for i in range(5,8): print("The square of the number " , i , " is " , i ** 2) into Python. You get the following: >>> for i in range(5,8): ... print("The square of the number " , i , " is " , i ** 2) ... The square of the number 5 is 25 The square of the number 6 is 36 The square of the number 7 is 49 If you forget to type the colon (the ":") at the end of the first statement, Python complains: >>> for i in range(5,8) File "", line 1 for i in range(5,8) ^ SyntaxError: invalid syntax If you forget to type the TAB-key before the print statement, Python complains: >>> for i in range(5,8): ... print("The square of the number " , i , " is " , i ** 2) File "", line 2 print("The square of the number " , i , " is " , i ** 2) ^ IndentationError: expected an indented block ---------------------------------------------------------- FILES: How to read and write to files. https://www.pythonforbeginners.com/files/reading-and-writing-files-in-python (this page contains a misprint involving "F" and "f") a = open("example.txt","r") --- can also use "w","a" (append), "r+" print a.read() --- reads all of a a.close() a = open("example.txt","r") b = a.readline() --- reads one line at a time print b a.close() c = open("my_new_file.txt","w") c.write(b) c.close() ---------------------------------------------------------- STRINGS, LISTS -- Examples in class: In Python type the following (the "\u" is for unicode, the "\n" is for "new line") help(STRINGS) a = "\u4ECA\u5292, \u6211\u5F88\u7D2F\u3002" print("\n\n" + a + "\n\n" + "Today, I am tired. \n\n\n\n" ) String splitting: (see https://www.pythonforbeginners.com/dictionary/python-split) fib = "1,1,2,3,5,8,13,21,Good morning,Good evening,Bye\nbye" # this is a string fib fib.split(",") spl = fib.split(",") spl[0] spl[1] spl[2] spl[6] spl[9] for i in range(0,10) # python complains because of the missing colon (:) for i in range(0,11): print(spl[i]) for i in range(0,12): print(spl[i]) # our list/array is out of range for i in range(0,len(spl)) # len(spl) refers to the length of spl print(spl[i]) # if there is only one number in range(), then range begins with 0 for i in range(len(spl)) print(spl[i]) for s in spl: print("Here is the string: " + s) ---------------------------------------------------------- CONVERTING STRINGS TO INT, FLOAT, ETC. This uses int(), float() (which need a string as the argument), and str() spl[6] spl[6] * 2 int( spl[6] ) * 2 a = "10.3" a * a # this will make Python unhappy b = float(a) b * b str(100000.3) + str(2222222.3) 3 + "Hi there." # adding an integer and a string makes Python complain. ----------------------------------------------------------