![]() |
![]() |
#1 |
"Dylan"
Mar 2017
11278 Posts |
![]()
This thread is intended to be a guide to program in Python, starting (hopefully) from the beginning. It is intended for those using the Colab/Kaggle interface, but it can be useful for those using a standalone Python interpreter.
There is a separate thread for comments (https://mersenneforum.org/showthread.php?t=24906). Post comments on this guide in that thread. Table of contents: 1. Table of contents (this post) 2. Motivation for this guide https://mersenneforum.org/showpost.p...20&postcount=2 3. How to get/use Python https://mersenneforum.org/showpost.p...21&postcount=3 4. Basic syntax https://mersenneforum.org/showpost.p...94&postcount=4 5. Comment lines https://mersenneforum.org/showpost.p...95&postcount=5 6. Some basic constructs: strings, integers, floats, complexes, bools https://mersenneforum.org/showpost.p...96&postcount=6 7. The "print" command and your first program https://mersenneforum.org/showpost.p...60&postcount=7 8. String concatenation and the "input" command https://mersenneforum.org/showpost.p...08&postcount=8 9. The "format" command https://mersenneforum.org/showpost.p...09&postcount=9 10. If/else, part 1: the if statement and the else statement https://mersenneforum.org/showpost.p...2&postcount=10 11. If/else, part 2: the elif statement https://mersenneforum.org/showpost.p...6&postcount=11 12. Functions https://mersenneforum.org/showpost.p...9&postcount=12 13. A slight digression: modules https://mersenneforum.org/showpost.p...9&postcount=13 14. For loops, part 1: introduction to for loops https://mersenneforum.org/showpost.p...2&postcount=14 15. For loops, part 2: break and continue https://mersenneforum.org/showpost.p...2&postcount=15 16. While loops https://mersenneforum.org/showpost.p...3&postcount=16 17. Putting all the loops together https://mersenneforum.org/showpost.p...0&postcount=17 18. More on strings - indexing, repeating, slicing https://www.mersenneforum.org/showpo...7&postcount=18 19. Miscellaneous string operations https://www.mersenneforum.org/showpo...8&postcount=19 20. Introduction to lists 21. Operations on lists - indexing, slicing, concatentation, etc. 22. The math module 23. The cmath module 24. etc tbd Last fiddled with by Dylan14 on 2021-01-17 at 15:20 Reason: remove disclaimer warning as the thread is locked |
![]() |
![]() |
#2 |
"Dylan"
Mar 2017
599 Posts |
![]()
So you might be wondering why I am writing this guide here. This is a valid point. In fact, I can see multiple points of contention:
1. There is, like, a thousand other tutorials out there on the Internet that do the same thing (in fact, the Python devs themselves have a tutorial, see https://docs.python.org/3/tutorial/.) Why would this be any different? 2. Why Python, out of all languages? It's not as efficient as, say C, or Fortran, or (insert any other compiled language). 3. Why not just stick with the codes that already exist? All of these are valid points. To justify this guide, I can reason as follows: 1. With regards to the availability of tutorials on the Internet and in books, it is easy to find information on the language. But say you want something that's more obscure, like for certain packages that you can find on PyPi. Then chances are, you won't find any tutorials on this, and you are left to study the source and you have no idea what's going on. Also, some tutorials are arranged differently than others. While most tutorials will start with the usual stuff like syntax, strings, variables, etc., there is a limit to where the guides go to, and then you have to switch to another one, or rely on the Python documentation which may be cryptic at some points. And some things that are covered may not be needed. For example, certain Linux programs can be run on Colab/Kaggle without calling Python. 2. There are several reasons why I chose to use Python for this guide. a) The code is easy to read, especially with properly commented code. b) The code is well defined and has specific syntax. c) Python can be extended easily by importing modules. Want to plot stuff? Use matplotlib! Need to deal with large arrays of numbers? Use numpy! Want to simulate a particle collider, use vegas! etc. etc. d) Code will work as long as you have an interpreter, which exists for Windows, Mac and Linux. e) Python can be linked to databases like MySql. 3. The easy answer (which is more of a question in its self): What if say the code doesn't exist that solves your problem? A more valid answer: let's consider the OEIS database. There are a lot of sequences that don't have code. Some are due to the fact that the function is not computable, or the next term in the sequence is not known, so creating code for this would be impossible or impractical (for example, the busy beaver sequence). Others are trivial to make code for, but they have no code in a language (for example, 210009 - a formula exists which is a recursion relation which can be coded up). And this is just for math stuff! What about more practical things? 4. Learning a new language might help your programming in other languages. 5. You might have the next big idea that assists people or assists the search for primes, or factors. Being able to code will allow others to benefit. (Hell, you might be able to improve prime95/mprime*). Thus, this guide is created to provide a detailed study of Python and other useful modules. (*) This might be hard. George Woltman et al. have done a great job in optimizing the program and implementing things that make primality checking fast and reliable. Last fiddled with by Dylan14 on 2019-11-18 at 04:24 Reason: gotta love typos |
![]() |
![]() |
#3 |
"Dylan"
Mar 2017
599 Posts |
![]()
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 Code:
python3 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. >>> 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 |
![]() |
![]() |
#4 |
"Dylan"
Mar 2017
599 Posts |
![]()
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) 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 Code:
NameError Traceback (most recent call last) <ipython-input-2-6fcf9dfbd479> in <module> ----> 1 x NameError: name 'x' is not defined Code:
x = 0 Code:
0 Code:
x + "a" Code:
TypeError Traceback (most recent call last) <ipython-input-5-3fb36790c1e0> in <module> ----> 1 x + "a" TypeError: unsupported operand type(s) for +: 'int' and 'str' Code:
x+1 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(); } 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 |
![]() |
![]() |
#5 |
"Dylan"
Mar 2017
599 Posts |
![]()
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:
# Code:
#This comment comes from mersenneforum's Python guide. 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 Unlike, say, Java, you can't just do something like Code:
/* Some comments need more than one line, like this one */ Code:
#Some comments need more than one line, like this one 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 """ Last fiddled with by Dylan14 on 2019-11-06 at 21:01 Reason: initial draft |
![]() |
![]() |
#6 |
"Dylan"
Mar 2017
11278 Posts |
![]()
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 Code:
440334444803013926723870430995863483703366909461783710471893932957885075695846526218526403061701134167211016236435527577005050015233222965976326940896095207044707758848508612460210362291110289652838518022120032380292451462329609095153231156707074655775395637629132002575140637348625684412427398984395674716936018562692034858963987306844991080918202832393268803551844553169715869473510245310131838410602687073367986808845044441458533294015993729099271507428272873558378015567915849627392090773401429909849505791 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)) Code:
complex(3, 4) Code:
3+4j 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") Code:
γ 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: (****) 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 |
![]() |
![]() |
#7 |
"Dylan"
Mar 2017
599 Posts |
![]()
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) 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) * *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!") Code:
Hello world! 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) Code:
Type something: Welcome to mersenneforum's python guide Welcome to mersenneforum's python guide 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 |
![]() |
![]() |
#8 |
"Dylan"
Mar 2017
599 Posts |
![]()
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) Code:
This is a string I like mersenneforum 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) Code:
This is a stringI like mersenneforum 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") Code:
This is a string and I like mersenneforum 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()) Example of input() with a prompt: Code:
age = input('Enter your age: ') print("You are " + str(age) + " years old") Code:
Enter your age: 23 You are 23 years old Code:
EOFError Traceback (most recent call last) <ipython-input-6-6610b0876cd9> in <module>() ----> 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: (**) 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 |
![]() |
![]() |
#9 |
"Dylan"
Mar 2017
599 Posts |
![]()
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) Code:
print("mersenneforum likes the following program: {}".format("Prime95")) Code:
mersenneforum likes the following program: Prime95 Code:
'{} and {}'.format("spam", "eggs") Code:
'{0} and {1}'.format("spam", "eggs") 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)) 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)) Code:
Class: 348/4620, time: 21.82 s, GhZ-d/day: 912.10 (**) 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 |
![]() |
![]() |
#10 |
"Dylan"
Mar 2017
59910 Posts |
![]()
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() 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") 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") Code:
if(expr): #code to run if expr is true dosomething() else: #code to run if expr is false dosomethingelse() 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!") 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() Code:
if(expr1 or expr2): #evaluates if expr1 or expr2 are true dosomething() 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)) 3) If you have an if or else statement with nothing in it, you will get an error: Code:
if(3 > 2): Code:
if(3 > 2): pass #don't do anything (*) 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. |
![]() |
![]() |
#11 |
"Dylan"
Mar 2017
11278 Posts |
![]()
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() 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 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") 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. |
![]() |
![]() |
Thread Tools | |
![]() |
||||
Thread | Thread Starter | Forum | Replies | Last Post |
Guide to compiling YAFU | Mr. Odd | YAFU | 4 | 2017-04-24 15:40 |
Overclock Testing Guide? | Caribou007 | Software | 18 | 2013-06-18 19:57 |
Guide | OmbooHankvald | Operation Billion Digits | 4 | 2009-08-26 08:18 |
guide me about linux | tinner | Linux | 23 | 2009-06-23 02:39 |
Guide | OmbooHankvald | 3*2^n-1 Search | 3 | 2005-07-13 21:03 |