mersenneforum.org A Guide for Python
 User Name Remember Me? Password
 Register FAQ Search Today's Posts Mark Forums Read

 2019-11-03, 04:29 #3 Dylan14     "Dylan" Mar 2017 10010100002 Posts How to get/use Python Of course, before we can actually go about and learn how to use Python, we need to first acquire the Python interpreter/environment. There are several ways to do this: 1. Download Python from the official website, https://www.python.org/downloads/. This is the easiest method to get up and running with Python on a standalone interpreter. It will give you the following by default (at least on a Windows install): * documentation files * pip (a useful tool to install additional packages) * tcl/tk and IDLE (a dev environment) * the python test suite * the py launcher (makes it easier to run the interpreter) There are multiple versions available; it is recommended to run the latest version (which at the time of post is 3.8.1)(*), as I will be using Python 3 here for this guide (**). 2. Use a pre-built distribution of Python, which includes a bunch of packages right off the bat. There are several of these available, although not all of them are compatible with every OS choice. For this I recommend the Anaconda distribution (available here, which installs a bunch of packages which will be useful later on (like numpy, matplotlib, etc.) and has pip which allows one to install more packages. Of course, you may pick a different one, see, for example, https://wiki.python.org/moin/PythonDistributions. 3. (Linux only) In several distros of Linux, Python is automatically installed. If for some reason, it is not, you can use the package manager included on your distro. To do this on Ubuntu, do the following: * first run sudo apt-get update to update the repositories (inserting your root password if needed) * then run sudo apt-get install python3 python3-pip and answer y when prompted. This will install the python interpreter, the pip package manager and any dependencies. If you have a different distribution of Linux, then you may have to change apt-get to the appropriate name and parameters for your package manager (pacman, yum, etc.). 4. Online editors: there are several of them out there. The only ones that I have major experience with here are the ones on Google Colaboratory and Kaggle. Both of these use notebook style interfaces which are not too dissimilar to the Jupyter notebook that is used in the Anaconda distribution. For the Colab, you will need a Google account to proceed, and for Kaggle you will need to make an account. Once done, you can create notebooks. More information on these can be found in the following two threads. Note: if you running the code locally, it will be useful to have a text editor, like emacs, gedit, or notepad++. Running the interpreter: Once you have the interpreter installed on your machine, then you can call the interpreter by invoking the following Code: python or Code: python3 This assumes that python is in your path, if not, you will need to type the full path in to the interpreter, or add the path to the directory where python lives to your environment variables. The end result should look like this: Code: C:\Users\Dylan>"C:\Users\Dylan\Anaconda\envs\Python 3\python.exe" Python 3.7.4 (default, Aug 9 2019, 18:34:13) [MSC v.1915 64 bit (AMD64)] :: Anaconda, Inc. on win32 Warning: This Python interpreter is in a conda environment, but the environment has not been activated. Libraries may fail to load. To activate this environment please see https://conda.io/activation Type "help", "copyright", "credits" or "license" for more information. >>> (ignore the warning here, this is a thing from conda). If you are using Colab, once you login you will have a window which will show the available notebooks. Click on "New Python 3 notebook" and then a new notebook will open. If you are using Kaggle, once you login, go to "Notebooks", then click on "New Notebook". Leave the settings as is, and then click on "Create". A new kernel will be created with a cell filled with an example piece of code, and an empty cell. Once ready, we can move on to the next bit. (*) The download page has pretty much every single minor version and bugfix version of Python, and there are even tarballs for version 1 of Python. (**) Python 1 is very much out of date (1.6 was released in 2000). Python 2 reached end of life on January 1, 2020. It is of course still available in some Linux repos (for example, Debian 10 (Buster) still ships with it, but Ubuntu 20.04 LTS (Focal) will not have Python 2 in the main repository). Last fiddled with by Dylan14 on 2020-01-09 at 00:01 Reason: update newest version and end of life notice on Python 2
 2019-11-04, 00:36 #4 Dylan14     "Dylan" Mar 2017 24·37 Posts Basic Syntax In order to code, you must understand two things: 1. The functions that make up the language (otherwise you aren't going to do anything). 2. The syntax used in the language. This is arguably more important than knowing the functions. You may have a nice program that spans 10000 lines, but if you have simply one syntax error, the compiler/interpreter will complain with a syntax error, and you will be forced to scan through your entire code to find the error. Now, each function has its own syntax depending on what it takes as arguments. For a simple example, let's take a look at SeedSequence from the random module in numpy: Code: class numpy.random.SeedSequence(entropy=None, *, spawn_key=(), pool_size=4) This function has 3 arguments, all of them optional, since each of them have a default value. The default value for each of these is defined by using the equals sign and then after the equals sign a value is given. Each of these arguments also takes a certain type of input. For example, the "entropy" argument may take the value of "None", an integer, or a sequence of integers. We'll get to functions later on in the guide. For now, we will deal with the basic syntax of Python. Firstly, we can't just enter random characters into a prompt(*). Typing Code: x will yield an error: Code: NameError Traceback (most recent call last) in ----> 1 x NameError: name 'x' is not defined In fact, before you can reference a "name", you need to define it first. So, say we want to initialize x to 0 (as for a counter). We can do this by typing the following: Code: x = 0 Now, x is defined. If we type x now in a new cell, we get the following Code: 0 The next thing that we need to be wary of is the types of our variables(**). It will not end well if you try to add, say, an integer and a string. Try Code: x + "a" Here, if you defined x = 0 as above, then x is an integer and "a" is a string. Clearly addition or concatenation doesn't work between these two types, and we get a TypeError: Code: TypeError Traceback (most recent call last) in ----> 1 x + "a" TypeError: unsupported operand type(s) for +: 'int' and 'str' But it clearly works if we have an integer. Typing this Code: x+1 should yield 1, and no errors. Now another thing to note is that in Python, we use indents to denote control flow blocks, and we do not need to end lines with the semicolon character. This is in stark comparison to C, where you use curly braces to denote control flow blocks, and you use semicolons. Here's a symbolic example: Python: Code: while(x <= 10): dosomething() dosomethingelse() (***) C (****): Code: while(x <= 10) { dosomething(); dosomethingelse(); } With this style of demarcation, you must be careful with your indents. Editors may have different styles. For example, on Colab, it uses 2 spaces for an indent, whereas on Kaggle and notepad++ it uses 4 spaces. On others a tab is used. I will use 4 spaces for the code examples. More specific syntax will be introduced when we need it. (*) Well, you can, but first you need to make the line a comment line first. See the section on Comments for more information. (**) Some information on some common types in plain Python are located in the post labeled "Basic Constructs". (***) Don't actually try to run this: this is only here as an example of the indent style. (****) This follows the Allman brace placement. There are several other ones, but this is outside the scope of this guide. Last fiddled with by Dylan14 on 2019-11-10 at 02:45 Reason: initial draft of this section
 2019-11-04, 00:37 #5 Dylan14     "Dylan" Mar 2017 24·37 Posts Comments Perhaps the most useful thing of good code is well commented code. After all, without them, we would just have to rely on reading the source code and hope that we understand what is going on in the code. Of course, the comments should be about the code (or, at the very least, clean, without obscenities. I.e., don't be like Ponytail in 1790!) So what do I mean by well commented code? I say that code is "well commented" if it satisfies the following: 1. Each piece of a script or program is commented. 2. The comments are relevant and explain clearly what is going on at that point. Comments need not be sentences or regular statements (sometimes a question is best). 3. Comments are marked in the right place within the code (meaning, if you have a function withing the code that takes a function and then plots it, you would not mark a comment saying to plot the function when you are evaluating the function at multiple points). 4. (Optional) If a piece of code goes through multiple iterations, it may be worth commenting what versions and changes have gone on over time. The last point is optional since a) version control via svn or git keeps track of changes in the code, and b) some authors may include a file called changes.txt which says what has changed. Now how does one do comments in Python. This is very simple. For a single line comment, one can preface the line with the following character: Code: # Once this character is placed in a line, the rest of the line is not evaluated when the interpreter is run. As an example, run a script with the following: Code: #This comment comes from mersenneforum's Python guide. (nothing should come out and you should return to the prompt). The # character can also come anywhere in the line and everything after that is treated as a comment. Such a comment is an inline comment. An example can be found in my mlucas compilation script, where we check to see if the error log is empty before we go and and link: Code: if os.stat("erroravx512.log").st_size == 0: #grep came up empty Now what about multiline comments? Unlike, say, Java, you can't just do something like Code: /* Some comments need more than one line, like this one */ Or like this: Code: #Some comments need more than one line, like this one (the second code example will ignore the first line, but the code will error out with a syntax error when it hits the second line). So how do we do a multi-line comment? We have two options: 1. For each line, we preface the line with a # character. 2. Encase the comment in triple quotes. Applying this to the last code block, the following are equivalent(*): Code: #Some comments need #more than one line, #like this one Code: """ Some comments need more than one line, like this one """ (*) Care has to be taken with the triple quotes. In actuality this is a string that isn't referenced by anything, so it doesn't do anything in the program. Also, if you use this construct inside a function, then the object becomes a docstring (documentation string) associated with that function. If in doubt, just use the # character! Last fiddled with by Dylan14 on 2019-11-06 at 21:01 Reason: initial draft
 2019-11-04, 00:37 #6 Dylan14     "Dylan" Mar 2017 11208 Posts Basic Constructs: strings, integers, floats, complexes, bools Okay, we've covered how to get python, we've covered how to be wary of our syntax, and we've learned how to comment and (hopefully) do it properly. We should be ready to go, right? Not so fast. In codes, unless we're doing something very simple like printing "Hello World!" to the screen (*), we will generally have functions that take some input, do stuff (**) with that input, and then return something back to the user, either directly or into another function. Now in something like C or C++, functions themselves have type, like int, void, etc. etc. This is not the case with Python. Here, the variables themselves are typed, and the functions are not. This is important! Okay, but what types are there to use? In standard Python 3, we have many different types that we can use. These include: * bool (a boolean, which can take the value 0 or 1, or alternatively "True" or "False" * int (an integer) * float (a floating point number) * complex (a complex number of the form a + bj) (***) * containers and iterators (iterate over objects within the container) * lists (mutable sequence, used to store collections of similar objects) * tuples (immutable sequences containing heterogeneous data, or for use in sets/dictionaries) * ranges (used for "for" loops) * strings (for text data) * and more (see https://docs.python.org/3.8/library/stdtypes.html for all built in types) Some modules will introduce other types. A notable example is the array class in numpy (which can be thought of as a matrix). Here, we will focus on 5 classes which appear very often in python: strings, integers, floats, complexes and bools. Bools: A bool is short for a boolean. This is a type which has two values: either 0 (denoting "off" or "false") or 1 (denoting "on" or "true"). The values themselves are not really helpful in themselves, but they are useful when setting conditions for while loops and for if/else statements, which we will cover later. The Boolean operators are "and", "or", and "not". To understand these, one should know the truth tables of these expressions (****). Let a and b be logical statements. Then the operators will yield *and - evaluates false if one of a or b are false. *or - evaluates false if both a and b are false. *not - evaluates true if the statement is false, else it's false. Booleans also come about when using comparisons, of which there are 8 of these defined in Python - < (less than), <= (less than or equal), > (greater than), >= (greater than), == (equal), != (not equal), is (object identity) and is not (negated object identity). Some of these operators (such as <, <=, > and >=) are only defined in certain cases. For example, if one of the arguments is a complex number, then a TypeError will be raised. Int: Int is short for integer. Integers are defined as you would expect in mathematics. You can have integers as large as you would like in Python 3, as long as you have enough memory. For example, here is M1693: Code: (2**1693)-1  yields Code: 440334444803013926723870430995863483703366909461783710471893932957885075695846526218526403061701134167211016236435527577005050015233222965976326940896095207044707758848508612460210362291110289652838518022120032380292451462329609095153231156707074655775395637629132002575140637348625684412427398984395674716936018562692034858963987306844991080918202832393268803551844553169715869473510245310131838410602687073367986808845044441458533294015993729099271507428272873558378015567915849627392090773401429909849505791 The usual operators can be used for integers, such as +, -, *, /, % (modulus), abs(x) (absolute value), and ^ (exponentiation, which can be implemented by using ** or pow(x, y)). There is also //, which is the floored quotient function (or integer division), which gives the whole integer value of the division, rounded down. Also, there is the divmod function, which gives the pair x // y, x % y. Float: Floats are floating point numbers. This type is needed because often times, it is not necessary to have infinite precision (or even possible) to have infinite precision, due to memory constraints. Depending on what scale we are working with (nanoscale or planetary scale), we need to have accuracy at different scales. To deal with this, floating point numbers are needed. Floating point numbers are defined by the IEEE 754 standard (*****). These have the same operations available as integers. Complexes: Complexes cover complex numbers. A complex number can be written in Python via the following: Code: complex(real, (imag)) For example, the number 3 + 4i can be written by typing: Code: complex(3, 4) or Code: 3+4j You can't use the % operator or the divmod operator for complexes. However, you also get a new operator in the c.conjugate() function which returns the complex conjugate. Strings: The last class we will cover are strings. Strings are used to convey text information. These can be parsed and stripped and otherwise manipulated (we will go over this later when we deal with list comprehension). A string is denoted by either single quotes ' ', double quotes " ", or triple quotes in either version (""" """ or ''' '''). The triple quotes can be used to do multiline strings. Strings can contain any character you'd like, but some characters need to be escaped. To escape a character, you use a \ (backslash). This is used, for example, if you need to add a tab or a new line character. You can also use \ to prefix special characters like the quotes, or for characters defined by their ASCII or Unicode values. For example, typing Code: print("\u03b3") will yield Code: γ the symbol for lowercase gamma. All of the escape characters can be found on this site: https://www.quackit.com/python/refer..._sequences.cfm. (*) The "Hello World" program is usually the first program that people learning to program will write up. Granted, it's not really that useful on its own (you could just type echo "hello world" in a command prompt and do the same thing without invoking python). However, printing stuff to screen can be useful when you go debug a program. I will cover this in the next section. (**) I'm pretty sure "stuff" is the technical term here. (***) This is the notation that Python uses for complexes, which is similar to what an electrical engineer would use. Mathematicians should interpret this a + bi. Still, they mean the same thing: $i = j = \sqrt {-1}$ (****) A truth table is a construct in logic used to determine the validity of a logical statement. More information can be found here: https://en.wikipedia.org/wiki/Truth_table. (*****) See https://www.geeksforgeeks.org/ieee-s...point-numbers/ for an overview. Last fiddled with by Dylan14 on 2020-08-11 at 14:04 Reason: actually spell out the symbol name, delete some extra return lines Firefox likes to add
 2019-11-10, 02:48 #7 Dylan14     "Dylan" Mar 2017 24×37 Posts The Print Command and your first program Now in the previous post in this guide I mentioned the "Hello World" program being the first program that aspiring programmers type out in the language of their choice. With our background that we have developed so far, we are now ready to get to this concept of printing messages to the screen, which is ultimately what the "Hello World" program demonstrates. The "print" command: Print is a simple built-in function that takes in a string and then prints it to the screen. This is invoked by typing the following: Code: print(string) This is the simplest invocation of the print command. Note here that the "string" can be a chain of strings strung together, using concatenation. We can also format the string using the format command. These will be the subjects of the next two sections of the guide. Actually, print has some keyword arguments, although these are hardly used. The full syntax for the print command is Code: print(*objects, sep=' ', end='\n', file=sys.stdout, flush=False) Here's what all the arguments mean: * *objects - specifies what objects should be printed. The * indicates that we can link multiple objects. Objects to be printed have to be separated with commas. * sep = ' ' - objects are to separated with this string. By default, it is a space. * end = '\n' - The object to be printed at the end of the objects. By default, it is a new line (note the escape character). *file = sys.stdout - Specifies where the output will be sent to. The output location must be an object with the write(string) method. By default, it is sent to sysout, i.e., it gets output to the screen. *flush - Takes either the value of True or False. If True, the stream is forcibly flushed. If False, it is not. The default is False. Your first program: Now, we have a function that we can play around with. Therefore, we can create programs with it. The simplest one that we can write is the "Hello World" program, which I have mentioned a few times already. To create this, open up a Python shell/notebook and type the following: Code: print("Hello world!") This will yield the following: Code: Hello world! Congrats! You have now written your first program in Python! Ok, celebrations aside, this is great, but it is limited to whatever we put in the string. To improve this, we can use the input() (*) command, which will ask for user input. Try this code: Code: string = input("Type something: ") print(string) This yields, after user input: Code: Type something: Welcome to mersenneforum's python guide Welcome to mersenneforum's python guide Now, we can type whatever we'd like to print. Which is always nice. In the future we can use format() and string concatenation to make more intricate things to print. (*) The input command will be covered in more detail later. Last fiddled with by Dylan14 on 2019-11-12 at 23:06 Reason: initial draft
 2019-11-12, 23:07 #8 Dylan14     "Dylan" Mar 2017 24·37 Posts Concatenation of strings and the "input" command In the previous section, we dealt with the print command and we also took our first serious look at strings. However, we kept it very simple, and we considered only one string at a time. Now, what if we want to have multiple strings? This is very simple: we can define two variables as strings. We can also print said strings: Code: string1 = "This is a string" string2 = "I like mersenneforum" print(string1) print(string2) This yields: Code: This is a string I like mersenneforum Now, suppose we want to connect the strings together, so that we have one string that contains both string1 and string2. In order to do this, we need to use string concatenation. Luckily, we can do easily in Python. If we use the plus sign between two string objects, we can "concatenate" them together. Going back to the previous strings that we defined, we could concatenate as follows: Code: string1 = "This is a string" string2 = "I like mersenneforum" string3 = string1 + string2 print(string3) This gives the following: Code: This is a stringI like mersenneforum This leads to a thing about concatenation: it just sticks the strings together into one, without putting any white space between the two.(*) Now, what if we have more than two strings that we want to concatenate? Easy! Just put a plus sign between each string you want to string together, like so: Code: print("This is a string " + "and " + "I like mersenneforum") which yields Code: This is a string and I like mersenneforum Note that I only used three strings in this example. You can expand this to N strings, where N is any positive number greater than 2. Just make sure to put a plus sign next to each pair of strings.(**) The "input" command: In the previous section, I used the input() command to get Python to print whatever we wanted to type. It would be wrong to just ignore what it does before we get too deep into the guide, so we will cover it here. The input function is a simple function, which may take either 0 or 1 arguments. It basically interrupts the interpreter, requests user input, and then when the user presses Enter on the keyboard, the program will continue. The only argument that can be placed in the function is a string, which will be a prompt which will be printed when the interpreter reaches that point in the program. The input function will encounter an error if an end of file character is received (***). Example of input() without a prompt: Code: print(input()) This will print out whatever you type in. Example of input() with a prompt: Code: age = input('Enter your age: ') print("You are " + str(age) + " years old") this prints out the user's age: Code: Enter your age: 23 You are 23 years old The EOFError (on Google Colab, after pressing Ctrl+D in input())(****): Code: EOFError Traceback (most recent call last) in () ----> 1 print(input()) /usr/local/lib/python3.6/dist-packages/ipykernel/kernelbase.py in _input_request(self, prompt, ident, parent, password) 743 if value == '\x04': 744 # EOF -->745 raise EOFError 746 return value 747 EOFError:  (*) You can kind of think of string concatenation as "gluing" strings together. (**) Note that they must be strings, otherwise you will get a TypeError (see Basic Syntax). You can bypass this by using the str() command, which will try to change the type of the thing inside the parentheses to a string. I'll explain this in more detail later. (***) On Unix/Linux systems, pressing Ctrl+D will send the EOF signal, whereas on a Windows machine, pressing Ctrl+Z+Enter will do this. (****) In the error, we have the string '\x04'. So, hex character 04 is the EOF character (recall \xhh inside a string means to escape the character with hex value hh. In ASCII, hex 04 is not defined to anything, and hex 26 is reserved for the DOS end of file character. In general this is not really important since in most cases you will have non empty input. Last fiddled with by Dylan14 on 2020-08-11 at 14:07 Reason: fix another code block, delete extra return lines
 2019-11-12, 23:07 #9 Dylan14     "Dylan" Mar 2017 24×37 Posts The format command Do you know that in a lot of programs one can change how things are formatted? For example, many word processors (including the WYSIWYG editor that I am using to type this part of the tutorial) have many options available to change how text looks, such as font size, color and alignment. In programming, this isn't what we are referring to, but rather how things are presented to the end user. This can be seen in various programs that are used on Mersenneforum and elsewhere. A teaser: a look at mfaktc's PrintFormat option(*): Mfaktc has several options available to influence how it operates. Most of the options affect the usage of the GPU, but there is an option in the ini file to adjust what it prints on the screen when it completes a class. This option is called "PrintFormat". I won't go through the full options (refer to the threads linked, or in your instance of mfaktc), but we'll look at a few of the options. First, we'll look at %t, which is the option for the time elapsed per class. There are four ways it can be printed, depending on the number that needs to be displayed: "%6.0f" (no decimal places), "%6.1f" (1 decimal place), "%6.2f" (2 decimal places), or "%6.3f" (3 decimal places). These will display up to 6 digits. As another example, we can look at %M, the exponent. This is a number which can be up to 10 decimal digits (as the exponent limit of mfaktx is 2^32-1). This is expressed in the format string, "%-10u". The rest should make more sense after we go through how Python handles string formatting. Python's format command: The format command is part of the core language, in the string.py file. The syntax is the following: Code: {}.format(string_to_be_formatted, /, args, kargs) As a simple example, we will consider a substitution of text in the format: Code: print("mersenneforum likes the following program: {}".format("Prime95")) This yields the following string: Code: mersenneforum likes the following program: Prime95 As we can see, python inserted the text Prime95 in the space marked by the curly brackets. Now, of course, we can specify multiple sets of curly brackets, and when we do that, Python will substitute those in. In modern versions of Python (**), you don't need to specify positional arguments in the format command, meaning the following are equivalent: Code: '{} and {}'.format("spam", "eggs") Code: '{0} and {1}'.format("spam", "eggs") Both yield the string, 'spam and eggs'. By changing the numbers instead to 1 and 0, we get 'eggs and spam'. So if the positional arguments are not set, then they will be in the order that you specify them in the format command. Do note, that if you do specify positional arguments but you index a non-existent entry (say, by typing in a 2 instead of 0 in our example), you will get an IndexError. Formatting numbers: So now that we have handled text, how do we handle numbers in our format command? In python, we have several options on how we can handle numbers. These are 'e' - print the number in exponent notation, using e to indicate the exponent. 'E' - same as e, but use E instead. 'f' - displays a number as a fixed point number. 'F' - same as 'f' but nan (not a number) is displayed as NAN and inf (infinity) is displayed as INF. 'g' - general format. For a given precision >=1, round the number to p significant figures and then format using 'f' or 'e' depending on the magnitude of the number. +/-infinity, +/-0 and not a number is formatted as inf, -inf, 0, -0 and nan. (***) 'G' - similar to g but use E if the number is too large. Also capitalizes inf and nan. 'n' - uses the current locale to insert the appropriate number separator characters, but otherwise the same as g. '%' - percentage. none - similar to 'g' but when fixed point notation is used the number has at least one digit past the decimal point. Simple example: truncating pi As we all know, pi is approximately 3.14159265358979323846... . However, this takes up a lot of space. Let's make it 5 decimal places long: Code: pidecimaldigits = 3.14159265358979323846 print("{:.5f}".format(pidecimaldigits)) This yields the number 3.14159. Returning to mfaktc - reproducing the format of a progress indicator Armed with our knowledge, we can reproduce the progress line in mfaktc in Python. Let's reproduce a simple line, with class, time, rate: Code: Class = 348 time = 21.824 rate = 912.1 print("Class: {0}/4620, time: {1:.2f} s, GhZ-d/day: {2:.2f}".format(str(Class), time, rate)) This yields the following: Code: Class: 348/4620, time: 21.82 s, GhZ-d/day: 912.10 (*) The options should be similar in the OpenCL equivalent, mfakto, as well as the Double Mersenne program, mmff. More information can be found here, or here. (**) Applies for version 3.1+. In 3.4+ they can also be omitted for the Formatter, which is the class that contains the format command. (***) More precise rules can be found at https://docs.python.org/3/library/st...-mini-language. Last fiddled with by Dylan14 on 2020-04-14 at 21:30 Reason: initial draft
 2019-11-19, 02:24 #10 Dylan14     "Dylan" Mar 2017 24·37 Posts If/else, part 1: the if command and the else command Now that we have dealt with the print command and other related commands (such as the format command and the input command), it's time to move on to stuff that will form the backbone of many programs: loops and if/else statements. We can classify these as follows: * if/elif/else - We test if a logical statement (possibly a chain of logical statements) is true or not. If it is true, we execute something. If not, then depending on what we have following it, we will run something else. * for loop - We have a counter (usually i, but it doesn't have to be). This is initialized to some value. The loop will iterate for some number of iterations. During one of these iterations, we do something. * while - While a logical statement is true, we run whatever is in the loop. As soon as the logical is no longer true, we stop. Loops will come later, after we deal with modules and functions. For now, we will focus on the first part of the list: if/else statements(*). If/else statements: In real life, we often do stuff based on whether certain conditions are true. For example (using mersenneforum's favorite program): If the temperature is less than 40 degrees Fahrenheit, I will run Prime95 on my computers to warm the room. Today's high temperature is 38 degrees. Therefore, I will run Prime95 today. Much like in real life, certain code will run if a certain condition is true or not. The way we can implement this in Python (and really any programming language) is to use if statements. Systematically, the if statement works like this: Code: if(expr): dosomething() We will break this down further. The first line in the if statement reads "if(expr)". This is interpreted as follows: We test the truthiness of the expression inside the parentheses. There are two outcomes of testing the expression: a) The expression evaluates True. If this is the case, then we evaluate whatever is in the body, which is everything after the colon (i.e., we do something). Note that whatever is in the block must be indented(**). If it isn't, you will get a IndentationError. b) The expression evaluates False. If this is the case, then we skip over the code and move to the next piece of code, or we stop if this is the last piece of code. If we want to implement our good piece of advice, we could type the following into our shell: Code: temp = input("Enter a number") if(float(temp) <= 40): print("run Prime95") What this does is if the user enters a number, then we check if the input is less than or equal to 40. If it is, then we are told to run Prime95. If not, then we get nothing. If we don't get a number as input, then we get an error. Now we only have one thing inside the block. We can of course have as many statements as we like inside the block. We can even have more if statements within the block, as long as we indent properly. Now, say we want the code to do something else if our expression evaluates as false. We can do this by using else statements. Else statements must follow an if statement, they can't be alone. For example, if we type this in: Code: else: print("hi")  we will get a SyntaxError. Systematically, the if/else construct works like this: Code: if(expr): #code to run if expr is true dosomething() else: #code to run if expr is false dosomethingelse() Note the indentation! So let's suppose that we have the computers off when the temperature is above 40 degrees. We can modify the code as follows: Code: temp = input("Enter a number") if(float(temp) <= 40): print("run Prime95") else: #temp > 40 print("Turn your computers off, it's warm out there!") Now, if the input is below 40, we run prime95. If not, then the input is either a number above 40, or it's something else. If it is a number, then we are told that we should keep our computers off. If it is something else, we will get an error. A few more notes: 1) Expressions can be compounded using the operators "and" and "or". So we can have something like this for an if statement: Code: if(expr1 and expr2): #evaluates if expr1 and expr2 are both true dosomething() or this Code: if(expr1 or expr2): #evaluates if expr1 or expr2 are true dosomething() or something more complicated, like (expr1 and (expr2 or expr3)). Using "and" and "or", you can fine tune exactly when a piece of code runs. 2) You can write if/else expressions in a single line, and if you have multiple statements you want to run, then you separate with semicolons. For example, this is perfectly valid: Code: temp = input("Enter a number: ") if(float(temp)<=40): print('run Prime95'); print(str(temp))  However, for complicated statements, this can be quite messy to read. I will avoid using this style, and just use the indents(***). 3) If you have an if or else statement with nothing in it, you will get an error: Code: if(3 > 2): yields a SyntaxError due to an unexpected end of file. To fix this, you can use the Pass command, which does nothing, but is included to ensure proper syntax. So this would be valid: Code: if(3 > 2): pass #don't do anything here, 3 is indeed bigger than 2, but we don't do anything, since we have the pass command inside the if block. (*) The elif command is more useful for when we have more complicated logical chains, or when we are defining functions with recursion. We will cover this in the next section. (**) As I have stated before, most text editors will have their own definition of an indent in Python. See the section "Basic Syntax" for more information. (***) Even though they can be a pain to ensure they line up properly here.
 2019-11-24, 01:49 #11 Dylan14     "Dylan" Mar 2017 11208 Posts If/else, part 2: the elif command In the last section, we learned about the if command and the else command. This allowed us to run a piece of code if a logical expression was true, and another thing if it was false. Now suppose instead we want to have more than two code snippets (for example, one if a logical expression is true, another one if that logical statement is false, but a second logical statement is true, and a third if both logical statements are false). We can do this by using the elif command. The elif statement: The elif statement works very much like the if statement. The statement has the following syntax: Code: elif(expr): dosomething() There is a few things to keep in mind when you use the elif command: 1. There must be an if statement prior to the first invocation of the elif statement. If you don't do this, or you have a bare elif statement, you will get a SyntaxError. 2. You can have as many elif statements as you want. You have to make sure that each of these have the same indent level as the if statement that precedes all of the them, or you will get a SyntaxError. 3. If there is a else statement, it must be after all elif statements. 4. The same syntax that applies for if and else applies for the elif statement. Putting it all together: With the if, else and elif statements, we can build the most general if statement that we can make in Python. This works as follows: Code: if(expr1): #code to run if expr1 is true elif(expr2): #code to run if expr1 is false, but expr2 is true elif(expr3): #code to run if expr1 and expr2 are false, but expr3 is true . . . elif(exprn): #code to run if expr1, expr2, ..., exprnminus1 are false, but exprn is true else: #code to run if all n expressions are false Again, note the indentations. With this construct, we can build recursion relations(*), or complex checks. Example: Code: #code to check the sign of a number num = input("Enter an integer: ") if(int(num) > 0): print(str(num) + " is positive") elif(int(num) == 0): print(str(num) + " is zero") else: print(str(num) + " is negative")  This code uses if, elif and else to test whether an integer is positive, negative or zero. It's important to try limiting cases: try the following inputs: 2 (positive) 0 (zero) -167 (negative) b (an error should occur) (*) Recursion relations can be defined in functions. We will cover these in a future section of the guide.

 Similar Threads Thread Thread Starter Forum Replies Last Post Mr. Odd YAFU 4 2017-04-24 15:40 Caribou007 Software 18 2013-06-18 19:57 OmbooHankvald Operation Billion Digits 4 2009-08-26 08:18 tinner Linux 23 2009-06-23 02:39 OmbooHankvald 3*2^n-1 Search 3 2005-07-13 21:03

All times are UTC. The time now is 01:25.

Sat May 28 01:25:48 UTC 2022 up 43 days, 23:27, 0 users, load averages: 1.14, 1.49, 1.56

Copyright ©2000 - 2022, Jelsoft Enterprises Ltd.

This forum has received and complied with 0 (zero) government requests for information.

Permission is granted to copy, distribute and/or modify this document under the terms of the GNU Free Documentation License, Version 1.2 or any later version published by the Free Software Foundation.
A copy of the license is included in the FAQ.

≠ ± ∓ ÷ × · − √ ‰ ⊗ ⊕ ⊖ ⊘ ⊙ ≤ ≥ ≦ ≧ ≨ ≩ ≺ ≻ ≼ ≽ ⊏ ⊐ ⊑ ⊒ ² ³ °
∠ ∟ ° ≅ ~ ‖ ⟂ ⫛
≡ ≜ ≈ ∝ ∞ ≪ ≫ ⌊⌋ ⌈⌉ ∘ ∏ ∐ ∑ ∧ ∨ ∩ ∪ ⨀ ⊕ ⊗ 𝖕 𝖖 𝖗 ⊲ ⊳
∅ ∖ ∁ ↦ ↣ ∩ ∪ ⊆ ⊂ ⊄ ⊊ ⊇ ⊃ ⊅ ⊋ ⊖ ∈ ∉ ∋ ∌ ℕ ℤ ℚ ℝ ℂ ℵ ℶ ℷ ℸ 𝓟
¬ ∨ ∧ ⊕ → ← ⇒ ⇐ ⇔ ∀ ∃ ∄ ∴ ∵ ⊤ ⊥ ⊢ ⊨ ⫤ ⊣ … ⋯ ⋮ ⋰ ⋱
∫ ∬ ∭ ∮ ∯ ∰ ∇ ∆ δ ∂ ℱ ℒ ℓ
𝛢𝛼 𝛣𝛽 𝛤𝛾 𝛥𝛿 𝛦𝜀𝜖 𝛧𝜁 𝛨𝜂 𝛩𝜃𝜗 𝛪𝜄 𝛫𝜅 𝛬𝜆 𝛭𝜇 𝛮𝜈 𝛯𝜉 𝛰𝜊 𝛱𝜋 𝛲𝜌 𝛴𝜎𝜍 𝛵𝜏 𝛶𝜐 𝛷𝜙𝜑 𝛸𝜒 𝛹𝜓 𝛺𝜔