From manpritsinghece at gmail.com Wed Sep 1 12:07:40 2021 From: manpritsinghece at gmail.com (Manprit Singh) Date: Wed, 1 Sep 2021 21:37:40 +0530 Subject: [Tutor] To make a new pyarray class Message-ID: Dear sir, I need to make a new pyarray class that can accept any number of arguments, and is capable of returning a list-like object. all methods of lists can be applied to the object of this pyarray class. Other than this if i need a + operator to be overloaded for this class, + operator should add a scalar value (v) to each element of the instance of this class. Like if an instance of class pyarray is x = [2, 5, 9] then x+1 must produce and return [3, 6, 10]. class pyarray(list): def __init__(self, *args): list.__init__(self, args) def __add__(self, x): return pyarray(*(ele+x for ele in self)) x = pyarray(3, 5, 8) // pyarray class called and object x created which is a list like object print(x) // gives below written output , the output is list like [3, 5, 8] x.append(6) print( x) [3, 5, 8, 6] // list append method successfully worked. From nzbzxx at gmail.com Wed Sep 1 12:35:13 2021 From: nzbzxx at gmail.com (nzbz xx) Date: Thu, 2 Sep 2021 00:35:13 +0800 Subject: [Tutor] Print statement for dataframes Message-ID: Hi, I have the following dataframe. Is there a way to print statement results for every row & column using for loop? s_0520 s_1080 date 2018-06-29 -0.061031 -0.000006 2018-09-28 -0.000516 0.022360 From wlfraed at ix.netcom.com Wed Sep 1 23:06:59 2021 From: wlfraed at ix.netcom.com (Dennis Lee Bieber) Date: Wed, 01 Sep 2021 23:06:59 -0400 Subject: [Tutor] Print statement for dataframes References: Message-ID: On Thu, 2 Sep 2021 00:35:13 +0800, nzbz xx declaimed the following: >Hi, > >I have the following dataframe. Is there a way to print statement results >for every row & column using for loop? > > s_0520 s_1080 >date >2018-06-29 -0.061031 -0.000006 >2018-09-28 -0.000516 0.022360 What do you expect the output to look like? And, heck, what package are you using for that "dataframe"? After all, there are some Python packages that interface with R... (or, if you prefer, R packages that interface to Python). -- Wulfraed Dennis Lee Bieber AF6VN wlfraed at ix.netcom.com http://wlfraed.microdiversity.freeddns.org/ From alan.gauld at yahoo.co.uk Thu Sep 2 03:11:59 2021 From: alan.gauld at yahoo.co.uk (Alan Gauld) Date: Thu, 2 Sep 2021 08:11:59 +0100 Subject: [Tutor] To make a new pyarray class In-Reply-To: References: Message-ID: On 01/09/2021 17:07, Manprit Singh wrote: > Other than this if i need a + operator to be overloaded for this class, + > operator should add a scalar value (v) to each element of the instance of > this class. Like if an instance of class pyarray is x = [2, 5, 9] then x+1 > must produce and return [3, 6, 10]. > > class pyarray(list): > def __init__(self, *args): > list.__init__(self, args) > def __add__(self, x): > return pyarray(*(ele+x for ele in self)) Since lists are mutable why not just increment the existing pyarray objects? for idx,el in enumerate(self): self[idx] += x return self Just a thought. -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ http://www.amazon.com/author/alan_gauld Follow my photo-blog on Flickr at: http://www.flickr.com/photos/alangauldphotos From kaushalshriyan at gmail.com Thu Sep 2 01:55:49 2021 From: kaushalshriyan at gmail.com (Kaushal Shriyan) Date: Thu, 2 Sep 2021 11:25:49 +0530 Subject: [Tutor] Python Client for Cloud Monitoring API Message-ID: Hi, I am referring to https://cloud.google.com/monitoring/uptime-checks#monitoring_uptime_check_update-python. How do I use it? Any examples? Do I need to write a python script to enable monitoring? I am a little confused. Please advise. Thanks in advance. Best Regards, Kaushal From __peter__ at web.de Thu Sep 2 04:13:33 2021 From: __peter__ at web.de (Peter Otten) Date: Thu, 2 Sep 2021 10:13:33 +0200 Subject: [Tutor] To make a new pyarray class In-Reply-To: References: Message-ID: On 02/09/2021 09:11, Alan Gauld via Tutor wrote: > On 01/09/2021 17:07, Manprit Singh wrote: > >> Other than this if i need a + operator to be overloaded for this class, + >> operator should add a scalar value (v) to each element of the instance of >> this class. Like if an instance of class pyarray is x = [2, 5, 9] then x+1 >> must produce and return [3, 6, 10]. >> >> class pyarray(list): >> def __init__(self, *args): >> list.__init__(self, args) >> def __add__(self, x): >> return pyarray(*(ele+x for ele in self)) > > Since lists are mutable why not just increment the existing > pyarray objects? > > for idx,el in enumerate(self): > self[idx] += x > return self > > Just a thought. For __iadd__()/+= that would be OK, but for __add__()/+ mutating the original object is a no-go. From alan.gauld at yahoo.co.uk Thu Sep 2 04:33:05 2021 From: alan.gauld at yahoo.co.uk (Alan Gauld) Date: Thu, 2 Sep 2021 09:33:05 +0100 Subject: [Tutor] Python Client for Cloud Monitoring API In-Reply-To: References: Message-ID: On 02/09/2021 06:55, Kaushal Shriyan wrote: > I am referring to > https://cloud.google.com/monitoring/uptime-checks#monitoring_uptime_check_update-python. > How do I use it? Any examples? Do I need to write a python script to enable > monitoring? I am a little confused. Please advise. This list is really for discussion of the python language and its standard library. For details about third party packages you are usually better exploring the suppliers web pages or asking the author directly. In your case there is a lot of information on the web site but nothing obvious about the python aspects. I'd try their support pages. -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ http://www.amazon.com/author/alan_gauld Follow my photo-blog on Flickr at: http://www.flickr.com/photos/alangauldphotos From alan.gauld at yahoo.co.uk Thu Sep 2 05:03:36 2021 From: alan.gauld at yahoo.co.uk (Alan Gauld) Date: Thu, 2 Sep 2021 10:03:36 +0100 Subject: [Tutor] To make a new pyarray class In-Reply-To: References: Message-ID: On 02/09/2021 09:13, Peter Otten wrote: > On 02/09/2021 09:11, Alan Gauld via Tutor wrote: >> On 01/09/2021 17:07, Manprit Singh wrote: >> >>> Other than this if i need a + operator to be overloaded for this class, + >>> operator should add a scalar value (v) to each element of the instance of >>> this class. Like if an instance of class pyarray is x = [2, 5, 9] then x+1 >>> must produce and return [3, 6, 10]. >>> >>> class pyarray(list): >>> def __init__(self, *args): >>> list.__init__(self, args) >>> def __add__(self, x): >>> return pyarray(*(ele+x for ele in self)) >> >> Since lists are mutable why not just increment the existing >> pyarray objects? >> >> for idx,el in enumerate(self): >> self[idx] += x >> return self >> >> Just a thought. > > For __iadd__()/+= that would be OK, but for __add__()/+ mutating the > original object is a no-go. Given the OPs definition of add (adding an integer to every member) I guess it's really __iadd__() he should be overriding. I agree if you were adding two pyarray objects(or similar) together you'd need to return a new object. To the OP: have you considered what happens if you want to add multiple values not just one integer? Can you, for example, have a pyarray of [1,2,3] and add to it [2,3,4] to yield [3,5,7], say? -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ http://www.amazon.com/author/alan_gauld Follow my photo-blog on Flickr at: http://www.flickr.com/photos/alangauldphotos From wlfraed at ix.netcom.com Thu Sep 2 10:44:10 2021 From: wlfraed at ix.netcom.com (Dennis Lee Bieber) Date: Thu, 02 Sep 2021 10:44:10 -0400 Subject: [Tutor] Print statement for dataframes References: Message-ID: On Wed, 01 Sep 2021 23:06:59 -0400, Dennis Lee Bieber declaimed the following: >On Thu, 2 Sep 2021 00:35:13 +0800, nzbz xx declaimed the >following: > >>Hi, >> >>I have the following dataframe. Is there a way to print statement results >>for every row & column using for loop? >> >> s_0520 s_1080 >>date >>2018-06-29 -0.061031 -0.000006 >>2018-09-28 -0.000516 0.022360 > > What do you expect the output to look like? And, heck, what package are >you using for that "dataframe"? After all, there are some Python packages >that interface with R... (or, if you prefer, R packages that interface to >Python). Addendum: is the date column actually considered part of the row /data/, or is it considered a row label or name? If the latter, you probably have to use a different attribute to retrieve it. The rest of the data should be accessible by indexing (check the docs if it is [row, col] or [col, row]). -- Wulfraed Dennis Lee Bieber AF6VN wlfraed at ix.netcom.com http://wlfraed.microdiversity.freeddns.org/ From chandarpass at gmail.com Thu Sep 2 20:46:28 2021 From: chandarpass at gmail.com (chandar pass) Date: Thu, 2 Sep 2021 17:46:28 -0700 Subject: [Tutor] python Q Message-ID: Hello there I started python about two years ago while getting my cyber security degree, and I am cinstatantly studying, I am also a jiu jitsu practitioner and trying to create an input program where a user inputs a submission, sweep I create and get back tip on how to sharpen that request. I am just a little stuck on where to go from here. I know I am going to need a list, maybe a dictionary of moves and and feed back and how to call those items. I hope this makes sense. dont mind the commented stuff input = ("Type your favorite Jits move or submission :") ##kimura = "top side kimura" E#next = ("Establish grip, and glue opponents elbow to your chest")# From wlfraed at ix.netcom.com Fri Sep 3 12:55:04 2021 From: wlfraed at ix.netcom.com (Dennis Lee Bieber) Date: Fri, 03 Sep 2021 12:55:04 -0400 Subject: [Tutor] python Q References: Message-ID: On Thu, 2 Sep 2021 17:46:28 -0700, chandar pass declaimed the following: >Hello there I started python about two years ago while getting my cyber >security degree, and I am cinstatantly studying, I am also a jiu jitsu >practitioner and trying to create an input program where a user inputs a >submission, sweep I create and get back tip on how to sharpen that >request. I am just a little stuck on where to go from here. I know I am >going to need a list, maybe a dictionary of moves and and feed back and how >to call those items. I hope this makes sense. > dont mind the commented stuff > Unfortunately I'm unable to really make sense of what your description is really asking about. You are using terms that have a different meaning to me... """submission, sweep I create and get back tip on how to sharpen that request. """ What is a "submission" and how does it differ from "request"? What does "sweep" mean (and "sweep I create" makes no grammatical sense to me). What does "sharpen" mean with regards to a "request"? List/dictionary are internal structures. Unless you account for persistence, the contents would be lost when the program is exited. Stuff that doesn't get changed /could/ be hard-coded into the program. I'd suggest, instead, looking at SQLite database (as it is included with pretty much all Python installs). SQLite database would allow adding/modifying stuff without changing the program. Is this application meant to be console (keyboard in a command line shell), GUI tied to a computer (Tkinter, wxPython, PyQT), accessed via a web application (Django, Flask). At best, I interpret your use case to be: * User selects some named move/technique (raw input, displayed menu, drop-down list [if GUI/Web]) * Application looks up said move/technique, and displays a list of suggested practice activities specific to training that move. No records kept of who requested what... Possible improvements (really requiring database) would be to have user sign in to the application, have practice activities ranked by difficulty (and returning the easiest activity that has NOT already been shown to the user). This expands the use case to # User signs into application * User selects some named move/technique (raw input, displayed menu, drop-down list [if GUI/Web]) # Application looks up said move/technique, and looks up user/move/shown information. # Application displays next difficulty level of activity specific to training that move. If no prior record for user/move, display simplest activity. # Application records user/move/last-seen-difficulty-level -- Wulfraed Dennis Lee Bieber AF6VN wlfraed at ix.netcom.com http://wlfraed.microdiversity.freeddns.org/ From chandarpass at gmail.com Sat Sep 4 13:31:36 2021 From: chandarpass at gmail.com (chandar pass) Date: Sat, 4 Sep 2021 10:31:36 -0700 Subject: [Tutor] Python user input and return Message-ID: I am trying to have a user pick an item from a list I have created, and if it is in the list they get a response, if not they should try again. I am having a hard time with this one for some reason. Here is what I have so far. all of my "user_choice" gets returned. Any kind of help would be greatly appreciated. Thanks user_choice = ("kimura", "wrist lock", "cross choke") input("What is your second favorite Jits move? :") print("{} is a sweet submission!".format(user_choice)) From flores.sarahlu at gmail.com Sat Sep 4 13:16:16 2021 From: flores.sarahlu at gmail.com (Sarah Flores) Date: Sat, 4 Sep 2021 10:16:16 -0700 Subject: [Tutor] Python help In-Reply-To: References: Message-ID: Hello! I have never posted to python.org before. I am working on an assignment for a class that is meeting virtually and I am looking for some feedback before I have to turn this in Sunday night (9/5, midnight pacific time) Here is the assignment and the code I wrote. Can you let me know if I'm totally off base? For context, I am a total noob and this is only my 2nd class in coding. I used mostly the class notes ppt slides and random youtube videos to figure this out. It is worth like half of the grade for the class so far.) *Assignment:* > * Q1) A non-governmental organization needs a program to calculate the > amount of financial assistance for needy families. The formula is as > follows: *(300 points) > ? If the annual household income is between $30,000 and $40,000 and the > household has at least three children, the amount is $1,000 per child. > ? If the annual household income is between $20,000 and $30,000 and the > household has at least two children, the amount is $1,500 per child. > ? If the annual household income is less than $20,000, the amount is > $2,000 per child. > * Implement a function for this computation. Write a program that asks for > the household income and number of children for each applicant, printing > the amount returned by your function. Use ?1 as a sentinel value for the > input. * > > Code is attached as a txt file. > Thank you, > Sarah > Flores.SarahLu at gmail.com > -------------- next part -------------- # Q1 Write the following functions and provide a program to test them. # CONSTANTS TIER_1 = 1 TIER_2 = 2 TIER_3 = 3 TIER1_MAX = 20000 TIER2_MAX = 30000 TIER3_MAX = 40000 TIER1_BENEFIT = 2000 TIER2_BENEFIT = 1500 TIER3_BENEFIT = 1000 # Variables childNum = 0 income = 0 aid = 0 # Defining the function def main(): print("Your household income is $", income) if income >= TIER3_MAX: print("Sorry, you are ineligible for financial aid.") else: financialAid(income,aid) return financialAid # This function determines whether an applicant will qualify for aid & how much. def financialAid(income,aid): childNum = int(input("How many children live in your household? ")) if income < TIER1_MAX: aid = childNum * TIER1_BENEFIT print("You are eligible for $",TIER1_BENEFIT," per child of assistance") print("Your financial aid is $", aid) return aid elif TIER2_MAX > income >= TIER1_MAX: if childNum >= TIER_2: aid = childNum * TIER2_BENEFIT print("You are eligible for $",TIER2_BENEFIT," per child of assistance") print("Your financial aid is $", aid) return aid else: print ("Sorry. You are ineligible for financial assistance.") elif TIER3_MAX > income >= TIER2_MAX: if childNum >= TIER_3: aid = childNum * TIER3_BENEFIT print("You are eligible for $",TIER3_BENEFIT," per child of assistance") print("Your financial aid is $", aid) return aid else: aid = 0 print("Sorry. You are ineligible for financial assistance.") return aid # This portion includes the while loop and sentinel value (-1) # This portion also calls the main function income = int(input("What is the total household income for the first applicant? (enter -1 to end) $")) while income != -1: main() income = int(input("What is the total household income for the next applicant? (enter -1 to end) $")) From mats at wichmann.us Sat Sep 4 20:19:01 2021 From: mats at wichmann.us (Mats Wichmann) Date: Sat, 4 Sep 2021 18:19:01 -0600 Subject: [Tutor] Python user input and return In-Reply-To: References: Message-ID: <20b4a996-2368-c844-44ba-7a010c58d948@wichmann.us> On 9/4/21 11:31 AM, chandar pass wrote: > I am trying to have a user pick an item from a list I have created, and if > it is in the list they get a response, if not they should try again. I am > having a hard time with this one for some reason. Here is what I have so > far. all of my "user_choice" gets returned. Any kind of help would be > greatly appreciated. Thanks > > user_choice = ("kimura", "wrist lock", "cross choke") > input("What is your second favorite Jits move? :") you need to save this. you don't have a check for whether the input value is one of the possibilities. > print("{} is a sweet submission!".format(user_choice)) here you're not printing what the user selected, but the tuple of possible choices you defined above. From cs at cskk.id.au Sat Sep 4 22:29:54 2021 From: cs at cskk.id.au (Cameron Simpson) Date: Sun, 5 Sep 2021 12:29:54 +1000 Subject: [Tutor] Python help In-Reply-To: References: Message-ID: On 04Sep2021 10:16, Sarah Flores wrote: >Hello! Welcome! >I have never posted to python.org before. This is a shiny new question; please post these as new messages, not as a reply (even an edited reply) with a distinctive subject line (eg "is myassigment attempt sensible?"). Not this time! Next time! Anyway, comments inline below. >I am working on an assignment for a class that is meeting virtually and I >am looking for some feedback before I have to turn this in Sunday night >(9/5, midnight pacific time) Hah. Here on (probably) the other side of the planet this means little! I'm on GMT+10. What's your GMT offset? Also not very important :-) (Also, most places on the planet read 9/5 as the 9th day of the 5th month.) [... assigmnnent spec snipped...] >Code is attached as a txt file. You may want to paste the code inline next time; some of the python.org lists discard attachments, particularly nontext attachments. That said, your attachment arrived fine. ># CONSTANTS >TIER_1 = 1 >TIER_2 = 2 >TIER_3 = 3 > >TIER1_MAX = 20000 >TIER2_MAX = 30000 >TIER3_MAX = 40000 > >TIER1_BENEFIT = 2000 >TIER2_BENEFIT = 1500 >TIER3_BENEFIT = 1000 These are all good. Python does not have constants, but we do have a convention that values to be treated as constants are named in UPPERCASE as you have done here. Broadly your code looks like a sensible approach. There are some bugs, and there are many comments I would make, again inline below: ># Variables >childNum = 0 >income = 0 >aid = 0 These are "global" variables. I recommend avoiding them. The problem with globals has a few aspects: - it means you've only got one piece of state; if you were doing this work for several situations instead of just one this will be a problem - it means this name is known in every function; often that is not desireable - you might use it by accident, particularly when the name represents something your programme does a lot - the local variables in a function _shadow_ (hide) the global variables; this means that assigning to such a name inside a function affects the local variable, and _not_ the global one - sometimes that isn't what you want, and is confusing as well Because of all of this, we usually try to avoid global variables. Instead we pass each function the values it needs to work with. All of that said, the "constants" you defined earlier? They're just global variables. We treat them differently because: - they are visually different because of their UPPERCASE names, so confusion is less likely - because we treat them as constants, we're _not_ assigning new values to them later Also, in Python you do not need to "declare" variables - just use them. You could just discard these lines. Note that variables have scopes - namespaces where they are defined. If you assign to a name, that name is defined in the current scope. The assignments above therefore define names in the global scope. That is _distinct_ from the function local scopes which occur when you assign to a name inside a function. The flipside of Python not declaring variables is that assigning to a variable _implies_ it is part of the current scope. Example: # global variable "x" x = 1 def f(): # local or global? local, because we assign to it x = 2 print(x) print(x) # prints the global f() # calls the function, which prints its local print(x) # prints the global again That would print 1 2 1 because the function only affects its local variable. This is how globals can be confusing. If you don't use then, this situation won't occur. ># Defining the function >def main(): > print("Your household income is $", income) > if income >= TIER3_MAX: > print("Sorry, you are ineligible for financial aid.") > else: > financialAid(income,aid) > return financialAid Conventionally the "main" function is the one which runs the entire programme. Just convention though. There seems to be confusion about what this function returns. In the loop at the bottom of the script you just call main(), so anything it returns would be discarded. So you could just remove the "return financialAid" statement. (Also, "return financialAid" means to return the function "financialAid" itself - functions are objects and can be returned. But I doubt that is what you intend.) Also, financialAid computes the aid. There is no need to pass "aid" in as a parameter. (And if you drop the "declaration" assignments from earlier Python will complain that "aid" is unknown, which highlights that there is not a meaningful preexisting value to pass in. So don't!) ># This function determines whether an applicant will qualify for aid & how much. >def financialAid(income,aid): > childNum = int(input("How many children live in your household? ")) > if income < TIER1_MAX: > aid = childNum * TIER1_BENEFIT > print("You are eligible for $",TIER1_BENEFIT," per child of assistance") > print("Your financial aid is $", aid) > return aid > elif TIER2_MAX > income >= TIER1_MAX: > if childNum >= TIER_2: > aid = childNum * TIER2_BENEFIT > print("You are eligible for $",TIER2_BENEFIT," per child of assistance") > print("Your financial aid is $", aid) > return aid > else: print ("Sorry. You are ineligible for financial assistance.") > elif TIER3_MAX > income >= TIER2_MAX: > if childNum >= TIER_3: > aid = childNum * TIER3_BENEFIT > print("You are eligible for $",TIER3_BENEFIT," per child of assistance") > print("Your financial aid is $", aid) > return aid > else: aid = 0 > print("Sorry. You are ineligible for financial assistance.") > return aid This function computes aid and returns it at several points. That can be fine, but a common approach is to compute aid but return just the once at the very bottom of the function: def financialAid(income): if/elif/elif.... return aid You've got good use of Python's compound comparisons here. i would be inclined to keep their ordering consistent. For example: if income < TIER1_MAX: elif TIER1_MAX <= income < TIER2_MAX: elif TIER2_MAX <= income < TIER3_MAX: and so on, making the brackets more clear. I'd also start by offering no aid (aid = 0) before the if-statement and have the variable aid brakcets set it as appropriate. The find else aboev looks like this: else: aid = 0 print("Sorry. You are ineligible for financial assistance.") I expect both of these should have been in the else: clause, but as written the print() is not - it is unconditional and always happens. You want: else: aid = 0 print("Sorry. You are ineligible for financial assistance.") ># This portion includes the while loop and sentinel value (-1) ># This portion also calls the main function >income = int(input("What is the total household income for the first applicant? (enter -1 to end) $")) >while income != -1: > main() > income = int(input("What is the total household income for the next applicant? (enter -1 to end) $")) A common way to write this which avoids doubling up the input call is like this: while True: income = int(input("What is the total household income for the first applicant? (enter -1 to end) $")) if income == -1: break # leave the loop main() Notice that you get an income value but do not use it. Probably you should pass it to main(): main(income) and main in turn should pass it to financialAid (which you already do): def main(income): ................. financialAid(income,aid) ................. In fact main() does little enough that personally I would put its if-statement in the main "while" loop at the bottom, or better still in the financialAid() function. Then you wouldn't need main() at all. Cheers, Cameron Simpson From alan.gauld at yahoo.co.uk Sun Sep 5 08:35:13 2021 From: alan.gauld at yahoo.co.uk (Alan Gauld) Date: Sun, 5 Sep 2021 13:35:13 +0100 Subject: [Tutor] Python user input and return In-Reply-To: References: Message-ID: On 04/09/2021 18:31, chandar pass wrote: > I am trying to have a user pick an item from a list I have created, and if > it is in the list they get a response, if not they should try again. I am > having a hard time with this one for some reason. Here is what I have so > far. all of my "user_choice" gets returned. Any kind of help would be > greatly appreciated. Thanks > > user_choice = ("kimura", "wrist lock", "cross choke") Here you create a tuple (not the same as a list, terminology is very important in programming!) with your options and give it the name user_choice, [ user_choices would be a better name since there are multiple items. Having good names makes code much easier to read.] > input("What is your second favorite Jits move? :") Now you ask the user for a choice. but you do not store that choice anywhere. Python is not clever enough to know where you want to store it, you have to give it a variable name, something like: option = input(...) > print("{} is a sweet submission!".format(user_choice)) And here you print a result. But what you print is user_choice. That is the name of the tuple, not what the user entered (which you haven't stored anywhere) So far you haven't tackled the problem of determining if the user entered something in the tuple. That's OK, it's good practice to build your programs in small steps. Once you get the users choice printed you can add a check to see if it is valid. -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ http://www.amazon.com/author/alan_gauld Follow my photo-blog on Flickr at: http://www.flickr.com/photos/alangauldphotos From wlfraed at ix.netcom.com Sun Sep 5 14:31:14 2021 From: wlfraed at ix.netcom.com (Dennis Lee Bieber) Date: Sun, 05 Sep 2021 14:31:14 -0400 Subject: [Tutor] Python help References: Message-ID: <960ajgd53h1t34u9p71bargfn0mnhqneao@4ax.com> On Sat, 4 Sep 2021 10:16:16 -0700, Sarah Flores declaimed the following: >Hello! >I have never posted to python.org before. >I am working on an assignment for a class that is meeting virtually and I >am looking for some feedback before I have to turn this in Sunday night >(9/5, midnight pacific time) So my comments are probably going to come in too late to be of any use Note: This is a new query, and should have been created as such -- not attached as a reply to some other unrelated thread. >Here is the assignment and the code I wrote. >Can you let me know if I'm totally off base? For context, I am a total >noob and this is only my 2nd class in coding. I used mostly the class notes >ppt slides and random youtube videos to figure this out. It is worth like >half of the grade for the class so far.) > Have you explored the Python Tutorial... https://docs.python.org/3/tutorial/ >> * Q1) A non-governmental organization needs a program to calculate the >> amount of financial assistance for needy families. The formula is as >> follows: *(300 points) >> ? If the annual household income is between $30,000 and $40,000 and the >> household has at least three children, the amount is $1,000 per child. >> ? If the annual household income is between $20,000 and $30,000 and the >> household has at least two children, the amount is $1,500 per child. >> ? If the annual household income is less than $20,000, the amount is >> $2,000 per child. >> * Implement a function for this computation. Write a program that asks for >> the household income and number of children for each applicant, printing >> the amount returned by your function. Use ?1 as a sentinel value for the >> input. * >> >> >Code is attached as a txt file. You got lucky -- normally the Python forums strip attachments, but it looks like plain text is the exception (normal extension for Python is .py -- which may have gotten stripped even if the contents are plain text). The common convention for programs is to use if __name__ = "__main__": main() The intent is that, if someone else imports the file to use functions defined in it, it doesn't run the main() logic. main() will only be run if this is the file being executed directly. A corollary of this is that there should not be statements that actually implement logic at the top level. That said... You are asking for the income level outside of main() (and not passing it into the main routine), but you ask for the number of children buried deep within the function that computes the aid to be provided. The financialAid function, ideally, would be pure -- it would not ask the user for input, nor would it print any output itself. The income and #children values would be passed into the function, and the function would return the results of its computation to the caller (this gets back to my opening comments -- one could import the file, and invoke the function themselves, having obtained inputs from somewhere else). So -- in my view... The bottom of the file would have the above invocation of main() (no arguments/parameters). main() would contain the loop structure, asking the user for income, AND for the number of children. main() would then invoke result = financialAid(income, children) financialAid() would do the computations, and return the result of the computation. Note: a possibly advanced feature of Python is that "return" can return anything -- including a tuple or list -- so you could return a tuple containing a status along with computed values. This probably constitutes something a bit more advanced than the class is expecting return ("INELIGIBLE", 0, 0) or return("ELIGIBLE", TIERx_BENEFIT, computed_total_aid) Then, back in main(), you would test the first part of result: if result[0] == "INELIGIBLE": print( your ineligible statement ) elif result[0] == "ELIGIBLE": print( eligibility statement with result[1] for tier ) print( Total aid statement with result[2] ) else: print("*** PROGRAMMING ERROR: expected ELIGIBLE or INELIGIBLE, got %s" % result[0] Another advanced algorithm would be to put the tier limits into a list, and have financialAid loop over the limits, rather than have all those IF statements for each level (consider how many changes you'd have to make if this agency suddenly created a fourth tier). This is really going beyond your class -- using tuple unpacking in the for loop, break, etc. # (income limit for tier, minimum children for tier, benefit for tier) LIMITS = [ (20000, 1, 2000), (30000, 2, 1500), (40000, 3, 1000) ] def financialAid(income, numchildren): eligibilty = False tier = 0 aid = 0 for (il, mc, bc) in LIMITS: if income < il and numchildren >= mc: eligibility = True tier = bc aid = bc * children break return (eligibility, tier, aid) Yes, that is all that is left when structuring the tiers/limits in a list, and deferring all I/O to the calling function. The order of the limits means you don't have to do range checking. If the income is less than the first limit and they have the required number of children, you compute the aid, set the tier and eligibility values, and exit the loop. Otherwise either they didn't have the required number of children (have none, for the first case), or the income was too high -- go to second case. The second case wants even more children, so if the first case failed for lack of children, so will all others. You don't need to test for income > tier1 limit because that was checked in the first case, and (if they had children) failed the income limit to get to the second case. Adding a fourth tier just requires inserting one tuple into the list, having the next income limit, minchildren limit, and the benefit per child. No changes to blocks of IF statements. -- Wulfraed Dennis Lee Bieber AF6VN wlfraed at ix.netcom.com http://wlfraed.microdiversity.freeddns.org/ From learn2program at gmail.com Sun Sep 5 19:04:40 2021 From: learn2program at gmail.com (Alan Gauld) Date: Mon, 6 Sep 2021 00:04:40 +0100 Subject: [Tutor] Python user input and return In-Reply-To: References: Message-ID: Always use Reply All or reply List when responding to tutor mails, otherwise it only goes to the recipient. On 05/09/2021 21:35, chandar pass wrote: > I guess I am asking how I would store their input to print it out. Just assign it to a variable as I showed: > > input("What is your second favorite Jits move? :") > > > Now you ask the user for a choice. but you do not store > that choice anywhere. Python is not clever enough to know > where you want to store it, you have to give it a > variable name, something like: > > option = input(...) > See the assignment above. -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ http://www.amazon.com/author/alan_gauld Follow my photo-blog on Flickr at: http://www.flickr.com/photos/alangauldphotos From chandarpass at gmail.com Sun Sep 5 19:46:35 2021 From: chandarpass at gmail.com (chandar pass) Date: Sun, 5 Sep 2021 16:46:35 -0700 Subject: [Tutor] Python user input and return In-Reply-To: References: Message-ID: After a little research and playing around I was able to get my desired output ######Jits project###### User_input = input("What is your favorite Jits move? :") print("{} is a sweet submission!".format(User_input)) User_input2 = input("What is your second favorite Jits move? :") print("{} is also a sweet submission!".format(User_input2)) print ("Now hit the mats and rip those submissions!!") On Sun, Sep 5, 2021 at 4:04 PM Alan Gauld wrote: > Always use Reply All or reply List when responding to tutor mails, > otherwise it only goes to the recipient. > > On 05/09/2021 21:35, chandar pass wrote: > > I guess I am asking how I would store their input to print it out. > > Just assign it to a variable as I showed: > > > > input("What is your second favorite Jits move? :") > > > > > > Now you ask the user for a choice. but you do not store > > that choice anywhere. Python is not clever enough to know > > where you want to store it, you have to give it a > > variable name, something like: > > > > option = input(...) > > > See the assignment above. > > -- > > Alan G > Author of the Learn to Program web site > http://www.alan-g.me.uk/ > http://www.amazon.com/author/alan_gauld > Follow my photo-blog on Flickr at: > http://www.flickr.com/photos/alangauldphotos > > From alan.gauld at yahoo.co.uk Mon Sep 6 04:04:46 2021 From: alan.gauld at yahoo.co.uk (Alan Gauld) Date: Mon, 6 Sep 2021 09:04:46 +0100 Subject: [Tutor] Python user input and return In-Reply-To: References: Message-ID: On 06/09/2021 00:46, chandar pass wrote: > After a little research and playing around I was able to get my desired > output > > ######Jits project###### > > > User_input = input("What is your favorite Jits move? :") > print("{} is a sweet submission!".format(User_input)) > User_input2 = input("What is your second favorite Jits move? :") > print("{} is also a sweet submission!".format(User_input2)) > > print ("Now hit the mats and rip those submissions!!") I'm glad you got it working. Just a couple of small points. You don't need the second User_input variable, you could just have reused the first one. You'd only need a second if you were storing both values for later processing. Secondly, its standard programmer style to use lowercase names for variables. Capitalized names tend to be for type definitions or classes - things you probably haven't covered yet. Python doesn't care but as your programs get bigger these little style things help give you clues about what's happening in your code. It's good to develop good habits early. -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ http://www.amazon.com/author/alan_gauld Follow my photo-blog on Flickr at: http://www.flickr.com/photos/alangauldphotos From wlfraed at ix.netcom.com Tue Sep 7 19:21:55 2021 From: wlfraed at ix.netcom.com (Dennis Lee Bieber) Date: Tue, 07 Sep 2021 19:21:55 -0400 Subject: [Tutor] Python help References: <960ajgd53h1t34u9p71bargfn0mnhqneao@4ax.com> Message-ID: On Sun, 05 Sep 2021 14:31:14 -0400, Dennis Lee Bieber declaimed the following: > > So my comments are probably going to come in too late to be of any use > So... two days later, if the OP is still reading... I'd make a lousy instructor, given that I'd totally jumped the intermediate stage.. Namely: Making a "constant" "array"* for each of IncomeLimit, MinChildren, BenefitPerChild, and then looping over the len(IncomeLimit) (and using the index for the other two). for idx in range(len(IncomeLimit)): not even using for idx, IL in (IncomeLimit): ... which would be closer to most traditional languages (FORTRAN, COBOL, C, REXX, BASIC, etc.) -- Wulfraed Dennis Lee Bieber AF6VN wlfraed at ix.netcom.com http://wlfraed.microdiversity.freeddns.org/ From osmaan at mysorewala.com Thu Sep 9 02:50:45 2021 From: osmaan at mysorewala.com (Osmaan Mysorewala) Date: Wed, 8 Sep 2021 23:50:45 -0700 Subject: [Tutor] Basic Question Message-ID: Hello, I'm trying to write a python program to create the game of life (Here's the wikipedia link to how the game of life works: https://en.wikipedia.org/wiki/Conway%27s_Game_of_Life). Right now it works only for the first iteration but then the new_arr becomes something completely wrong the second time I run the function. I think something is logically wrong with the neighbors function (other than how badly the if-statements are written). For reference, I'm eventually trying to put it on a display so that's why there's some display stuff in the comments there. Here's the code: rows, cols = (22, 18) old_arr = [[0 for i in range(cols)] for j in range(rows)] new_arr = [[0 for i in range(cols)] for j in range(rows)] def game_of_life(): global new_arr, old_arr for x in range(1, 21): for y in range(1, 17): neighbors = get_neighbors(x, y) if old_arr[x][y] == 0: if neighbors == 3: new_arr[x][y] = 1 print(neighbors) else: new_arr[x][y] = 0 else: if neighbors == 2: new_arr[x][y] = 1 else: new_arr[x][y] = 0 for i in range(len(new_arr)): print(new_arr[i]) print() # for x in range(0, 20): # for y in range(0, 16): # bitmap[x, y] = new_arr[x+1][y+1] # display.show(group) # new_arr = old_arr.copy() old_arr = new_arr.copy() # The neighbors function returns how many neighbors are present def get_neighbors(a, b): neighbors = 0 if old_arr[a + 1][b] == 1: neighbors = neighbors + 1 if old_arr[a - 1][b] == 1: neighbors = neighbors + 1 if old_arr[a][b + 1] == 1: neighbors = neighbors + 1 if old_arr[a][b - 1] == 1: neighbors = neighbors + 1 if old_arr[a - 1][b - 1] == 1: neighbors = neighbors + 1 if old_arr[a + 1][b - 1] == 1: neighbors = neighbors + 1 if old_arr[a - 1][b + 1] == 1: neighbors = neighbors + 1 if old_arr[a + 1][b + 1] == 1: neighbors = neighbors + 1 """ for na in range(a - 1, a + 1): for nb in range(b - 1, b + 1): if (na != a and nb != b) and old_arr[na][nb]: neighbors = neighbors + 1 # print (neighbors) """ return neighbors #testing ground to try out new starting live cells """ old_arr[8][8] = 1 old_arr[9][8] = 1 old_arr[10][8] = 1 old_arr[7][9] = 1 old_arr[8][9] = 1 old_arr[9][9] = 1 """ old_arr[7][8] = 1 old_arr[7][9] = 1 old_arr[8][10] = 1 old_arr[9][7] = 1 old_arr[10][8] = 1 old_arr[10][9] = 1 game_of_life() game_of_life() Please tell me if something is hard to understand in my description or code. Thank You, Osmaan Mysorewala From cs at cskk.id.au Thu Sep 9 09:20:41 2021 From: cs at cskk.id.au (Cameron Simpson) Date: Thu, 9 Sep 2021 23:20:41 +1000 Subject: [Tutor] Basic Question In-Reply-To: References: Message-ID: On 08Sep2021 23:50, Osmaan Mysorewala wrote: >I'm trying to write a python program to create the game of life (Here's >the >wikipedia link to how the game of life works: >https://en.wikipedia.org/wiki/Conway%27s_Game_of_Life). Right now it works >only for the first iteration but then the new_arr becomes something >completely wrong the second time I run the function. I think something is >logically wrong with the neighbors function (other than how badly the >if-statements are written). [...] I don't think so. Since the first run looks ok, the neighbors function is probably correct or close to correct. And anyway it looks right to me. I suspect this: old_arr = new_arr.copy() This is a shallow copy. Your arrays are nested lists of lists. A shallow copy copies the outer list, but not the inner lists. Since all values are actually references this means the copy is a new list, containing references to the old lists. When you make your pass over the old array an set the values in the new array, on the second pass you're actually updating the inner lists in the old array. Before the first pass you've got (scaled down as 2x2 and broken out into distinct setups: old1 = [0, 0] old2 = [0, 0] old_arr = [old1, old2] new1 = [0, 0] new2 = [0, 0] new_arr = [new1, new2] 2 completely distinct lists of lists. After the: old_arr = new_arr.copy() action you've got a new list "old_arr" with a copy of new_arr, but only a copy of its elements: old_arr = [new1, new2] a new list, but pointing at the _original_ "new1" and "new2" lists. So now your arrays are: old_arr = [new1, new2] new_arr = [new1, new2] and when you walk old_arr (correctly) and the modify things in new_arr, you're modifying new1 or new2, and they _are_ the contents of old_arr - so you've changed the original array while you're examining it. Your neighbor calculations will then be incorrect. A better approach might be this: old_arr = new_arr new_arr = [[0 for i in range(cols)] for j in range(rows)] i.e. make old_arr point at the new grid you just computed, and create a shiny new grid to use as "new_arr" for the next pass. Remember, Python variables are references to values. An assignment just moves a reference. Cheers, Cameron Simpson From mats at wichmann.us Thu Sep 9 15:57:24 2021 From: mats at wichmann.us (Mats Wichmann) Date: Thu, 9 Sep 2021 13:57:24 -0600 Subject: [Tutor] Basic Question In-Reply-To: References: Message-ID: On 9/9/21 12:50 AM, Osmaan Mysorewala via Tutor wrote: > Hello, > > I'm trying to write a python program to create the game of life (Here's the > wikipedia link to how the game of life works: > https://en.wikipedia.org/wiki/Conway%27s_Game_of_Life). Right now it works > only for the first iteration but then the new_arr becomes something > completely wrong the second time I run the function. I think something is > logically wrong with the neighbors function (other than how badly the > if-statements are written). For reference, I'm eventually trying to put it > on a display so that's why there's some display stuff in the comments > there. Here's the code: As you work through the jobs of collections full of mutable objects, shallow and deep copies, etc - and this is definitely part of the Python learning experience, and a trap not just for beginners at Python, experienced heads get into trouble too - here are some other things you might think about: There's not really a good reason to use a pair of globals to store two generations of the Conway "board". The use of globals is frowned upon in many cases just because it's so easy to get into trouble keeping track of what the state of things is. Instead, you could think of a flow like this: def main(): # do setup things - figure out boundaries, #generatrions, etc. # create first generation datastructure # loop for generations: # board = advance(board) # optionally call a board-printing routine # (if you have a need to print, good idea to separate out the logic) def advance(obj): # calculate the next generation from obj return newobj def neighbors(point): # do what's needed to figure out neighbors info See - no globals! You almost never want to write this if you don't actually _need_ the index: for i in range(len(new_arr)): print(new_arr[i]) because new_arr is iterable already, you sould prefer: for point in new_arr: print(point) There *are* times when you want to work with the index. As a design matter, you're storing a populated matrix, which is not wrong, but since the states are completely binary, you could store something sparse instead - like keep a list of the points that are "on", only. You easily know that if a point is not in that list, then it's off, so you didn't need to explicitly store the other value anywhere. That's just a different design to a solution, you certainly don't have to use it! For the original poster, and other Python newcomers, it's not unheard of that writing a program for Comway is a job interview question... and you'll be asked to make it efficient, too, not just working. It's probably worth leaving yourself a note to come back to this problem much later, when you're a lot more experienced in Python, and seeing if you would work a new solution differently given your new knowledge :) It's good practice! From mats at wichmann.us Thu Sep 9 18:46:05 2021 From: mats at wichmann.us (Mats Wichmann) Date: Thu, 9 Sep 2021 16:46:05 -0600 Subject: [Tutor] Basic Question In-Reply-To: References: Message-ID: On 9/9/21 3:58 PM, Osmaan Mysorewala wrote: > A followup question for Mr. Wichmann, I've heard that global variables > are not great, and I see that you wrote some pseduocode on how to fix > it. Still I don't really understand how to implement that in my code. > Everytime I tried using local variables to store the arrays, it gave the > error "local variable referenced before assignment". If possible, do you > think you could go into a bit more depth on how it would work? So this is another one of the things that trips up newcomers to Python, and that's what's called scope. It seems like this particular problem was loaded with traps, I wonder if maybe it came too early in whatever course (or tutorial, or whatever) you're on? Well, no matter. Global variables in Python aren't really global, they're module-global. That's a distinction that may not make much sense at this point. It just means they're available everywhere in the particular Python file they're declared in, but if your program has other modules that are imported those wouldn't have access to this so-called global. Enough of that... Python has a kind of interesting approach to what is global and what is local. I'm sure this will be covered in your material eventually so just quite briefly: if you write a function that just accesses a variable declared not in the function, but at the module level, then that "just works". If you try to change it, then that variable is considered local to the module instead, *unless* you list it as global. Being local means you can't access it before you set it. It's maybe easier to show this in an interactive session than to try for words (I added some comments with a # comment mark). Don't worry, this will definitely come up in any course, so don't need to worry about it just now, just know that you're not nuts :) >>> FOO = 100 # this is a (module) global... >>> def myfunc(): ... print(FOO) ... ... >>> myfunc() 100 # access to global in func is fine >>> print(FOO) 100 # as it is at module level >>> def myfunc(): ... FOO = 50 ... print(FOO) ... >>> myfunc() 50 # FOO was local to myfunc >>> print(FOO) 100 # didn't change the global one >>> def myfunc(): ... print(FOO) ... FOO = 50 ... >>> myfunc() Traceback (most recent call last): File "", line 1, in myfunc() File "", line 2, in myfunc print(FOO) UnboundLocalError: local variable 'FOO' referenced before assignment # because function would write to it, it's not global # thus the print before the assignment is an error >>> def myfunc(): ... global FOO ... print(FOO) ... FOO = 50 ... >>> myfunc() 100 # declared "global", so we're printing the global one >>> print(FOO) 50 # and myfunc changed the global one, since it was declared "global" >>> From alan.gauld at yahoo.co.uk Thu Sep 9 19:46:00 2021 From: alan.gauld at yahoo.co.uk (Alan Gauld) Date: Fri, 10 Sep 2021 00:46:00 +0100 Subject: [Tutor] Basic Question In-Reply-To: References: Message-ID: On 09/09/2021 23:46, Mats Wichmann wrote: > On 9/9/21 3:58 PM, Osmaan Mysorewala wrote: > >> A followup question for Mr. Wichmann, I've heard that global variables >> are not great, and I see that you wrote some pseuduocode on how to fix >> it. Still I don't really understand how to implement that in my code. >> Everytime I tried using local variables to store the arrays, it gave the >> error "local variable referenced before assignment". If possible, do you >> think you could go into a bit more depth on how it would work? I'll come at this from a slightly different angle from Mats so that hopefully one of the two views will make sese, and hopefully each reinforce the other. Almost every program has some form of high level data structure that gets changed by different functions throughout the running of the program. The simplest for of this is a global variable that is accessed by all functions. However, hard won experience has taught us that this introduces problems that are very hard to track down (and sometimes even to detect!). So the advice is to avoid global variables as much as possible. Global variables also make it much harder to reuse code a across programs and to work with multiple versions of the data in parallel. So all in all they are "A Bad Thing". So what do we do instead? One option is to put all the top level program code inside a function, declare some variables inside that function and then pass those variables into the sub-functions used by the program. Here is an example of code with 2 sub functions (sub1 and sub2) def sub1(): print var1 def sub2(): global var1 # see mats post for what this does! var1 = var1 +1 var1 = 0 sub1() # prints 0 print(var1) # prints 0 sub2() print(var1) # prints 1 Now lets convert that to not use global var1: def sub1(var): print var def sub2(var): return var + 1 def main(): var1 = 0 sub1(var1) # prints 0 print(var1) # prints 0 var1 = sub2(var1) print(var1) # prints 1 notice that the code inside main() is very like the top level code using global var1, but now var1 is a local variable inside main(). But there are two big differences: 1) Both sub functions take an input parameter of var (note not just var1, any var. So we can call those functions and pass any value in. That makes them more reusable because they don't depend on the existence of a var1. All the data they need has been passed in as a parameter. 2) The changes to the variable(in sub2) are passed back as a returned value. The main() code does not depend on the inner workings of the sub functions. And the sub functions do not depend on main(), they are now all completely independent. This is only a small step forward from global variables but it's a big step up in improving our ability to debug the code and detect errors. Later, you'll discover even more powerful ways to reduce the use of global variables and to minimise the sharing of data between functions. But for now this should be sufficient. Note: We could have made an intermediate step by not using main() and just passing global variables into our modified sub functions. But the extra work of adding main is minimal and it removes all global variables from the code. So, in summary: - Define your functions to have parameters that represent any external data they need to do their job - Pass in any data that the function needs to do its work as arguments when you call the function. - And changes to the external data should be passed back via a return statement - And variable that is to be changed by a function should be passed into the function and the old value replaced by the new (or else create a new variable) That last point is slightly complicated, but note the line in main(): var1 = sub2(var1) ie. It passes in the old value of var1 to sub2() and then assigns the new value returned by the function to var1, thus replacing the old with the new. HTH -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ http://www.amazon.com/author/alan_gauld Follow my photo-blog on Flickr at: http://www.flickr.com/photos/alangauldphotos From osmaan at mysorewala.com Thu Sep 9 17:58:31 2021 From: osmaan at mysorewala.com (Osmaan Mysorewala) Date: Thu, 9 Sep 2021 14:58:31 -0700 Subject: [Tutor] Basic Question In-Reply-To: References: Message-ID: Thank you so much for your help Mr. Simpson. I understand why what I used doesn?t work and I understand the fix. A followup question for Mr. Wichmann, I've heard that global variables are not great, and I see that you wrote some pseduocode on how to fix it. Still I don't really understand how to implement that in my code. Everytime I tried using local variables to store the arrays, it gave the error "local variable referenced before assignment". If possible, do you think you could go into a bit more depth on how it would work? One more question. In my get_neighbors function I use a terrible if-statement spam, how would I go about replacing that? On Thu, Sep 9, 2021 at 12:58 PM Mats Wichmann wrote: > On 9/9/21 12:50 AM, Osmaan Mysorewala via Tutor wrote: > > Hello, > > > > I'm trying to write a python program to create the game of life (Here's > the > > wikipedia link to how the game of life works: > > https://en.wikipedia.org/wiki/Conway%27s_Game_of_Life). Right now it > works > > only for the first iteration but then the new_arr becomes something > > completely wrong the second time I run the function. I think something is > > logically wrong with the neighbors function (other than how badly the > > if-statements are written). For reference, I'm eventually trying to put > it > > on a display so that's why there's some display stuff in the comments > > there. Here's the code: > > As you work through the jobs of collections full of mutable objects, > shallow and deep copies, etc - and this is definitely part of the Python > learning experience, and a trap not just for beginners at Python, > experienced heads get into trouble too - here are some other things you > might think about: > > There's not really a good reason to use a pair of globals to store two > generations of the Conway "board". The use of globals is frowned upon > in many cases just because it's so easy to get into trouble keeping > track of what the state of things is. Instead, you could think of a > flow like this: > > def main(): > # do setup things - figure out boundaries, #generatrions, etc. > # create first generation datastructure > # loop for generations: > # board = advance(board) > # optionally call a board-printing routine > # (if you have a need to print, good idea to separate out the > logic) > > def advance(obj): > # calculate the next generation from obj > return newobj > > def neighbors(point): > # do what's needed to figure out neighbors info > > See - no globals! > > > You almost never want to write this if you don't actually _need_ the index: > > for i in range(len(new_arr)): > print(new_arr[i]) > > because new_arr is iterable already, you sould prefer: > > for point in new_arr: > print(point) > > There *are* times when you want to work with the index. > > As a design matter, you're storing a populated matrix, which is not > wrong, but since the states are completely binary, you could store > something sparse instead - like keep a list of the points that are "on", > only. You easily know that if a point is not in that list, then it's > off, so you didn't need to explicitly store the other value anywhere. > That's just a different design to a solution, you certainly don't have > to use it! > > For the original poster, and other Python newcomers, it's not unheard of > that writing a program for Comway is a job interview question... and > you'll be asked to make it efficient, too, not just working. It's > probably worth leaving yourself a note to come back to this problem much > later, when you're a lot more experienced in Python, and seeing if you > would work a new solution differently given your new knowledge :) It's > good practice! > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > https://mail.python.org/mailman/listinfo/tutor > From roel at roelschroeven.net Fri Sep 10 03:26:18 2021 From: roel at roelschroeven.net (Roel Schroeven) Date: Fri, 10 Sep 2021 09:26:18 +0200 Subject: [Tutor] Basic Question In-Reply-To: References: Message-ID: <44151d77-330c-2e28-1905-5269f85cbf96@roelschroeven.net> Op 10/09/2021 om 0:46 schreef Mats Wichmann: > Python has a kind of interesting approach to what is global and what > is local.? I'm sure this will be covered in your material eventually > so just quite briefly: if you write a function that just accesses a > variable declared not in the function, but at the module level, then > that "just works".? If you try to change it, then that variable is > considered local to the module instead, *unless* you list it as global. Small correction in an otherwise excellent post: "... then that variable is considered local to the *function* instead". -- "Experience is that marvelous thing that enables you to recognize a mistake when you make it again." -- Franklin P. Jones From alan.gauld at yahoo.co.uk Fri Sep 10 04:21:34 2021 From: alan.gauld at yahoo.co.uk (Alan Gauld) Date: Fri, 10 Sep 2021 09:21:34 +0100 Subject: [Tutor] Basic Question In-Reply-To: References: Message-ID: On 09/09/2021 22:58, Osmaan Mysorewala via Tutor wrote: > One more question. In my get_neighbors function I use a terrible > if-statement spam, how would I go about replacing that? I assume you mean this section: def get_neighbors(a, b): neighbors = 0 if old_arr[a + 1][b] == 1: neighbors = neighbors + 1 if old_arr[a - 1][b] == 1: neighbors = neighbors + 1 if old_arr[a][b + 1] == 1: neighbors = neighbors + 1 if old_arr[a][b - 1] == 1: neighbors = neighbors + 1 if old_arr[a - 1][b - 1] == 1: neighbors = neighbors + 1 if old_arr[a + 1][b - 1] == 1: neighbors = neighbors + 1 if old_arr[a - 1][b + 1] == 1: neighbors = neighbors + 1 if old_arr[a + 1][b + 1] == 1: neighbors = neighbors + 1 I don't think its terrible but it can be tidied up provided the values you store are zero and one. Then you can miss out the if statements and replace them with addition: neighbors = neighbors + old_arr[a + 1][b] # or using +=... neighbours += old_arr[a - 1][b] neighbours += old_arr[a][b+1] neighbours += old_arr[a][b-1] neighbours += old_arr[a - 1][b-1] neighbours += old_arr[a + 1][b-1] neighbours += old_arr[a - 1][b+1] neighbours += old_arr[a + 1][b+1] HTH -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ http://www.amazon.com/author/alan_gauld Follow my photo-blog on Flickr at: http://www.flickr.com/photos/alangauldphotos From __peter__ at web.de Fri Sep 10 10:07:40 2021 From: __peter__ at web.de (Peter Otten) Date: Fri, 10 Sep 2021 16:07:40 +0200 Subject: [Tutor] Basic Question In-Reply-To: References: Message-ID: On 10/09/2021 10:21, Alan Gauld via Tutor wrote: > On 09/09/2021 22:58, Osmaan Mysorewala via Tutor wrote: > >> One more question. In my get_neighbors function I use a terrible >> if-statement spam, how would I go about replacing that? > I assume you mean this section: > > def get_neighbors(a, b): > neighbors = 0 > if old_arr[a + 1][b] == 1: > neighbors = neighbors + 1 > if old_arr[a - 1][b] == 1: > neighbors = neighbors + 1 > I don't think its terrible but it can be tidied up provided > the values you store are zero and one. Then you can miss > out the if statements and replace them with addition: > > neighbors = neighbors + old_arr[a + 1][b] # or using +=... > neighbours += old_arr[a - 1][b] > neighbours += old_arr[a][b+1] Osmaan, while I agree with Alan that the if statements aren't "terrible" I'd like to suggest that you revisit your failed attempt to use loops: > for na in range(a - 1, a + 1): > for nb in range(b - 1, b + 1): > if (na != a and nb != b) and old_arr[na][nb]: > neighbors = neighbors + 1 This should work once (1) you get the range() calls right hint: Python's ranges are "half open", i. e. they do not include the last value: >>> list(range(3)) [0, 1, 2] >>> a = 42 >>> list(range(a-1, a+1)) [41, 42] (2) in the first condition of the if statement you only exclude the cell (a, b) hint: start with an expression that's true for (a, b), then negate that with if not (...to be done...) and old_arr[na][nb]: ... From mrbrafi1971 at gmail.com Fri Sep 10 12:48:56 2021 From: mrbrafi1971 at gmail.com (Mrb Rafi) Date: Fri, 10 Sep 2021 22:48:56 +0600 Subject: [Tutor] Basic Question In-Reply-To: References: Message-ID: Hello Osmaan, Are you working on this as a part of your homework? It's just yesterday when one of my friends asked me about this game. He has got this game as a homework in his varsity. Rafi On Fri, Sep 10, 2021 at 8:28 PM Peter Otten <__peter__ at web.de> wrote: > On 10/09/2021 10:21, Alan Gauld via Tutor wrote: > > On 09/09/2021 22:58, Osmaan Mysorewala via Tutor wrote: > > > >> One more question. In my get_neighbors function I use a terrible > >> if-statement spam, how would I go about replacing that? > > I assume you mean this section: > > > > def get_neighbors(a, b): > > neighbors = 0 > > if old_arr[a + 1][b] == 1: > > neighbors = neighbors + 1 > > if old_arr[a - 1][b] == 1: > > neighbors = neighbors + 1 > > > I don't think its terrible but it can be tidied up provided > > the values you store are zero and one. Then you can miss > > out the if statements and replace them with addition: > > > > neighbors = neighbors + old_arr[a + 1][b] # or using +=... > > neighbours += old_arr[a - 1][b] > > neighbours += old_arr[a][b+1] > > Osmaan, while I agree with Alan that the if statements aren't "terrible" > I'd like to suggest that you revisit your failed attempt to use loops: > > > for na in range(a - 1, a + 1): > > for nb in range(b - 1, b + 1): > > if (na != a and nb != b) and old_arr[na][nb]: > > neighbors = neighbors + 1 > > This should work once > > (1) you get the range() calls right > > hint: Python's ranges are "half open", i. e. they do not include the > last value: > > >>> list(range(3)) > [0, 1, 2] > >>> a = 42 > >>> list(range(a-1, a+1)) > [41, 42] > > (2) in the first condition of the if statement you only exclude the cell > (a, b) > > hint: start with an expression that's true for (a, b), then negate that > with > > if not (...to be done...) and old_arr[na][nb]: > ... > > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > https://mail.python.org/mailman/listinfo/tutor > From PyTutor at DancesWithMice.info Fri Sep 10 18:05:07 2021 From: PyTutor at DancesWithMice.info (dn) Date: Sat, 11 Sep 2021 10:05:07 +1200 Subject: [Tutor] Basic Question In-Reply-To: <44151d77-330c-2e28-1905-5269f85cbf96@roelschroeven.net> References: <44151d77-330c-2e28-1905-5269f85cbf96@roelschroeven.net> Message-ID: <3c5bbb39-bc74-81ef-08d1-e9ffc1ca0a00@DancesWithMice.info> On 10/09/2021 19.26, Roel Schroeven wrote: > Op 10/09/2021 om 0:46 schreef Mats Wichmann: >> Python has a kind of interesting approach to what is global and what >> is local.? I'm sure this will be covered in your material eventually >> so just quite briefly: if you write a function that just accesses a >> variable declared not in the function, but at the module level, then >> that "just works".? If you try to change it, then that variable is >> considered local to the module instead, *unless* you list it as global. > Small correction in an otherwise excellent post: "... then that variable +1 > is considered local to the *function* instead". Pedantic explanation: Yes, using the combination of terms in one sentence was a bit confusing. In OO theory, the terminology used for a block of code that fulfils one responsibility or requirement, is "module". Python uses the specific term "module" more in the sense of a file. In the same manner, we can talk (confusingly) about a system's logical-requirement being a "function" of the system and/or being def[ined] as a "function" in Python code. Terminology!? Way-back, when "modular programming" was revolutionising coding practice (and before OO was portrayed as a 'silver bullet'), we could discuss "modules", but implementation almost certainly required a unit such as a "paragraph", a "section", a "subroutine", or (wait for it) a "function" - no "module" in sight. (and we think English might be a language for "communication"?) Cue joke about how many words (synonyms) Eskimos have for "snow" - and then someone will come-along and debate the word "Eskimo"...) Another terminological conundrum? I've met code where the (senior programmer) writer defends having a single function which contains: - establishment code - a with/context - a while loop - some finalisation ... rather than separating those components into four Python functions/modules. The claim, is that each of the above code-units (which I could easily identify/separate by-eye when reading the program!) obeys the SRP, and therefore doesn't *need* to be located within its own "module". Theory argues that OO requires "encapsulation" - but that 'requirement' may be more related to "information-hiding" than functional considerations. Python's philosophy is to be 'open' when it comes to information-hiding - there is no real concept of "private". So, the idea of 'open' modules/functional-units not being formally encapsulated within a Python function or method would seem congruent. NB personally-speaking I don't favor their argument, and will stick with my preference for small/short functions/methods and attempts to become a classy-guy... Apparently there is plenty of room to debate which meaning of "function" to apply, and in varying contexts... More directly related to Tutor and teaching/learning Python: Whilst delving into the meta-level of OO theory: I wondered if we spend a little too much time/effort 'teaching objects'? Thus, a recently-reviewed book talked of "mammals" as a super-class, which was sub-classed into "cat" and "dog". It then disappeared into the relatively-standard discussions of behavior and attribute. Advanced topics included inheritance cf composition. A fairly standard or common progression. However, listening to the OP's needs did make me wonder (again) if we become so enamored/enamoured with the actual objects and their characteristics and associated 'rules', that we spend very little (teaching) time discussing the less-obvious, but entirely essential, need to pass "messages" between objects - see earlier excellent description of using arguments/parameters. We discuss how the cat and the dog both 'walk' in similar fashion, but how each makes a different 'noise'. How much time is spent illustrating how the dog indicates that (s)he would like to play, or that the cat wishes the dog to maintain a certain distance (or else!)? How does the student indicate an interest in registering for a course, the purchaser a wish to buy some product, ... Advanced topics find that word (messages) being re-used?over-loaded with the likes of MQ (message queuing) and specific techniques related to multi-processing and API calls. So, the base concept would seem important when writing one's first code, and will expand both conceptually and practically, with one's horizons. Your thoughts? -- Regards, =dn From osmaan at mysorewala.com Fri Sep 10 13:41:13 2021 From: osmaan at mysorewala.com (Osmaan Mysorewala) Date: Fri, 10 Sep 2021 10:41:13 -0700 Subject: [Tutor] Basic Question In-Reply-To: References: Message-ID: Thank you everyone for all your help. I feel a lot more better about global variables now. I thought that using several of statements looked somewhat messy and would be hard to debug so that?s why I thought they might be bad. To answer your question Mr Rafi, this isn?t for my homework, it?s a personal project as I was trying to learn Python more. On Fri, Sep 10, 2021 at 9:55 AM Mrb Rafi wrote: > Hello Osmaan, > > Are you working on this as a part of your homework? > It's just yesterday when one of my friends asked me about this game. He has > got this game as a homework in his varsity. > > Rafi > > On Fri, Sep 10, 2021 at 8:28 PM Peter Otten <__peter__ at web.de> wrote: > > > On 10/09/2021 10:21, Alan Gauld via Tutor wrote: > > > On 09/09/2021 22:58, Osmaan Mysorewala via Tutor wrote: > > > > > >> One more question. In my get_neighbors function I use a terrible > > >> if-statement spam, how would I go about replacing that? > > > I assume you mean this section: > > > > > > def get_neighbors(a, b): > > > neighbors = 0 > > > if old_arr[a + 1][b] == 1: > > > neighbors = neighbors + 1 > > > if old_arr[a - 1][b] == 1: > > > neighbors = neighbors + 1 > > > > > I don't think its terrible but it can be tidied up provided > > > the values you store are zero and one. Then you can miss > > > out the if statements and replace them with addition: > > > > > > neighbors = neighbors + old_arr[a + 1][b] # or using +=... > > > neighbours += old_arr[a - 1][b] > > > neighbours += old_arr[a][b+1] > > > > Osmaan, while I agree with Alan that the if statements aren't "terrible" > > I'd like to suggest that you revisit your failed attempt to use loops: > > > > > for na in range(a - 1, a + 1): > > > for nb in range(b - 1, b + 1): > > > if (na != a and nb != b) and old_arr[na][nb]: > > > neighbors = neighbors + 1 > > > > This should work once > > > > (1) you get the range() calls right > > > > hint: Python's ranges are "half open", i. e. they do not include the > > last value: > > > > >>> list(range(3)) > > [0, 1, 2] > > >>> a = 42 > > >>> list(range(a-1, a+1)) > > [41, 42] > > > > (2) in the first condition of the if statement you only exclude the cell > > (a, b) > > > > hint: start with an expression that's true for (a, b), then negate that > > with > > > > if not (...to be done...) and old_arr[na][nb]: > > ... > > > > _______________________________________________ > > Tutor maillist - Tutor at python.org > > To unsubscribe or change subscription options: > > https://mail.python.org/mailman/listinfo/tutor > > > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > https://mail.python.org/mailman/listinfo/tutor > From learn2program at gmail.com Fri Sep 10 19:24:24 2021 From: learn2program at gmail.com (Alan Gauld) Date: Sat, 11 Sep 2021 00:24:24 +0100 Subject: [Tutor] Basic Question In-Reply-To: <3c5bbb39-bc74-81ef-08d1-e9ffc1ca0a00@DancesWithMice.info> References: <44151d77-330c-2e28-1905-5269f85cbf96@roelschroeven.net> <3c5bbb39-bc74-81ef-08d1-e9ffc1ca0a00@DancesWithMice.info> Message-ID: <21aa5ec5-a3ec-d8b4-569a-1375d7edd5da@yahoo.co.uk> On 10/09/2021 23:05, dn via Tutor wrote: > However, listening to the OP's needs did make me wonder (again) if we > become so enamored/enamoured with the actual objects and their > characteristics and associated 'rules', that we spend very little > (teaching) time discussing the less-obvious, but entirely essential, > need to pass "messages" between objects - see earlier excellent > description of using arguments/parameters. It's the difference between OOP as a paradigm and OOPL as a set of language features that support the paradigm. Most courses teach OOPLs but forget all about teaching the paradigm. It is perfectly possible to program using OOP in a non OOPL, indeed the vast majority of early OOP programs were written in Pascal, Lisp and C. Some even in COBOL. Of course, OO features were added to all those languages to deliver OOPL versions of them (ie. C++, CLOS, Object Pascal and COBOL WITH OBJECTS) . But the OOP paradigm is all about message passing between objects. And an object is an encapsulation of data and the functions that operate upon it. And an OOP program is one that comprises a set of objects that communicate via messages. With each object having its own method of responding to its received messages (polymorphism). That's why we call bound functions methods. > Advanced topics find that word (messages) being re-used?over-loaded with > the likes of MQ (message queuing) and specific techniques related to > multi-processing and API calls. > > So, the base concept would seem important when writing one's first code, > and will expand both conceptually and practically, with one's horizons. The message passing paradigm is the cornerstone of OOP and is almost totally ignored in modern OOP teaching? As a result we have abominations like Java which is a class based language rather than object based and actively encourages people to write non OOP programs using objects! People have become fixated on language features and forgotten about the very concepts that make OOP effective in large scale programming. And also the concepts that tie it back to core computing and control theory with communicating sequential machines. -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ http://www.amazon.com/author/alan_gauld Follow my photo-blog on Flickr at: http://www.flickr.com/photos/alangauldphotos From mats at wichmann.us Fri Sep 10 19:33:44 2021 From: mats at wichmann.us (Mats Wichmann) Date: Fri, 10 Sep 2021 17:33:44 -0600 Subject: [Tutor] Basic Question In-Reply-To: <21aa5ec5-a3ec-d8b4-569a-1375d7edd5da@yahoo.co.uk> References: <44151d77-330c-2e28-1905-5269f85cbf96@roelschroeven.net> <3c5bbb39-bc74-81ef-08d1-e9ffc1ca0a00@DancesWithMice.info> <21aa5ec5-a3ec-d8b4-569a-1375d7edd5da@yahoo.co.uk> Message-ID: <8933af87-a56a-19a5-2950-f5f1675d4b46@wichmann.us> On 9/10/21 5:24 PM, Alan Gauld wrote: > The message passing paradigm is the cornerstone of OOP and is > almost totally ignored in modern OOP teaching? As a result we have > abominations like Java which is a class based language rather than > object based and actively encourages people to write non OOP > programs using objects! I'd go further and say "forces". AFAIK you can't write a Java program without writing a class. Much happier with Python's approach, which is objects all the way down, but you don't have to create your own object definitions (types, for which the class syntax is a shortcut) unless the available ones don't cover your use cases. Which is good news since I'm writing to a Python list :) From manpritsinghece at gmail.com Thu Sep 16 21:35:44 2021 From: manpritsinghece at gmail.com (Manprit Singh) Date: Fri, 17 Sep 2021 07:05:44 +0530 Subject: [Tutor] A Question about coding style Message-ID: Dear sir, If I have to write a program, that allows the user to input a number and assign it to a variable b, if the number entered is a negative number, assign 0 to variable b. At last print the value of variable b. The code that i have written is given below: b = int(input("Enter a number")) if b < 0: b = 0 print(b) See the whole if statement part is written in single line, is it acceptable ? Second example is of a for loop, which is also written in single line for i in range(6): print(i) # print values from 0 to 5,is it also acceptable ? Kindly guide Regards Manprit Singh From cs at cskk.id.au Thu Sep 16 22:46:48 2021 From: cs at cskk.id.au (Cameron Simpson) Date: Fri, 17 Sep 2021 12:46:48 +1000 Subject: [Tutor] A Question about coding style In-Reply-To: References: Message-ID: On 17Sep2021 07:05, Manprit Singh wrote: >If I have to write a program, that allows the user to input a number >and >assign it to a variable b, if the number entered is a negative number, >assign 0 to variable b. >At last print the value of variable b. The code that i have written is >given below: > >b = int(input("Enter a number")) >if b < 0: b = 0 >print(b) > >See the whole if statement part is written in single line, is it acceptable >? The purpose of style is readability, for yourself and others. Is it still readable? For a very short statement, probably yes. If it a significant win over a 2 line if-statement? Maybe, maybe not. The 2 line form makes it quite obvious that there is an if-statement there. Is it acceptable? That depends on the coding style in your organisation (which can, of course, be just you). >Second example is of a for loop, which is also written in single line >for i in range(6): print(i) # print values from 0 to 5,is it also >acceptable ? Same criteria: Very short things: maybe. Is it a gain in readability? Maybe not? This style is uncommon. On a personal basis I tend to use styles like this if I have several very short test/action pairs. Example: for x, y, z in some-3-tuples...: if x < 0: x = 0 if y > 5: y = 6 if y + z > 10: z /= 2 If there's a little collection of these it _can_ be useful to flatten them to one line. Particularly if you're trying to get them well defined as a group that fits in a vertical space. But if they're mixed: for x, y, z in some-3-tuples...: if x < 0: x = 0 if y > 5: call_something() y = 6 if y + z > 10: z /= 2 I might find the visual variation annoying. Cheers, Cameron Simpson From roel at roelschroeven.net Fri Sep 17 03:28:46 2021 From: roel at roelschroeven.net (Roel Schroeven) Date: Fri, 17 Sep 2021 09:28:46 +0200 Subject: [Tutor] A Question about coding style In-Reply-To: References: Message-ID: Op 17/09/2021 om 3:35 schreef Manprit Singh: > If I have to write a program, that allows the user to input a number and > assign it to a variable b, if the number entered is a negative number, > assign 0 to variable b. > At last print the value of variable b. The code that i have written is > given below: > > b = int(input("Enter a number")) > if b < 0: b = 0 > print(b) > > See the whole if statement part is written in single line, is it acceptable > ? Another way for enforcing lower bounds (and similarly for upper bounds) is using the max function: b = max(0, b) > Second example is of a for loop, which is also written in single line > for i in range(6): print(i) # print values from 0 to 5,is it also > acceptable ? Personally I would advice against it, though I guess it can be acceptable for very short simple things like that. -- "Il semble que la perfection soit atteinte non quand il n'y a plus rien ? ajouter, mais quand il n'y a plus rien ? retrancher." "Perfectie is niet bereikt als er niets meer toe te voegen is, maar als er niets meer weg te nemen is." -- Antoine de Saint-Exup?ry From alan.gauld at yahoo.co.uk Fri Sep 17 04:18:03 2021 From: alan.gauld at yahoo.co.uk (Alan Gauld) Date: Fri, 17 Sep 2021 09:18:03 +0100 Subject: [Tutor] A Question about coding style In-Reply-To: References: Message-ID: On 17/09/2021 02:35, Manprit Singh wrote: > If I have to write a program, that allows the user to input a number and > assign it to a variable b, if the number entered is a negative number, > assign 0 to variable b. > At last print the value of variable b. The code that i have written is > given below: > > b = int(input("Enter a number")) > if b < 0: b = 0 > print(b) > > See the whole if statement part is written in single line, is it acceptable The thing about coding style is that it is subjective (within limits). But in the real world it will be set by the organisation for which you work. They will likely have a set of coding guidelines that you must follow. In one place they may ban single line constructs. In another they may mandate them. It probably won't be your choice, it will be set by the QA team. They may even have built tools that reformat your code to comply. Of much greater importance is that your code does not handle errors such as the user typing "two" instead of a numeric character. A loop and/or a try/except would normally be involved which would automatically make your code more complex. while True: try: b = input(...) if b<0:... except: continue Now we have two single lines (if and except) or not, as the rules allow. -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ http://www.amazon.com/author/alan_gauld Follow my photo-blog on Flickr at: http://www.flickr.com/photos/alangauldphotos From alan.gauld at yahoo.co.uk Fri Sep 17 06:10:18 2021 From: alan.gauld at yahoo.co.uk (Alan Gauld) Date: Fri, 17 Sep 2021 11:10:18 +0100 Subject: [Tutor] A Question about coding style In-Reply-To: References: Message-ID: On 17/09/2021 09:18, Alan Gauld via Tutor wrote: > while True: > try: > b = input(...) > if b<0:... > except: continue And that of course is buggy since there is no exit from the loop so there should be a break after the if... Apologies. -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ http://www.amazon.com/author/alan_gauld Follow my photo-blog on Flickr at: http://www.flickr.com/photos/alangauldphotos From mats at wichmann.us Fri Sep 17 10:30:10 2021 From: mats at wichmann.us (Mats Wichmann) Date: Fri, 17 Sep 2021 08:30:10 -0600 Subject: [Tutor] A Question about coding style In-Reply-To: References: Message-ID: <4761e2b7-4ecf-2a78-4754-96429ea09cd1@wichmann.us> On 9/17/21 02:18, Alan Gauld via Tutor wrote: > The thing about coding style is that it is subjective (within limits). > But in the real world it will be set by the organisation for which you > work. They will likely have a set of coding guidelines that you must > follow. In one place they may ban single line constructs. In another > they may mandate them. It probably won't be your choice, it will be set > by the QA team. They may even have built tools that reformat your code > to comply. I'll reiterate this. There have been coding style arguments since there was coding, probably. Some earlier languages (Fortran on punchcards) had quite a rigorous requirement on the syntax, so less flexibility on "style", so less arguments? Well, not so much... Nowadays, people are tired of arguments - public code reviews and code review tools have surfaced no end of style arguments - so there's increasingly the use of tools to enforce a style and try to take the argument out of it. So that would be the advice: don't worry about it, let a code formatter answer those questions for you. Aside as to multiple statements on one line: I work on a project that actually says don't do it, *except* for debug/trace statements, where it's encouraged to have those provide less visual impact on the function they may be used in, so you might see this: T = self.tm.trace if T: T.write(self.trace_message,... in an area that's complex and has lots of tracing msgs, to keep so many of the interesting bits from being pushed off the screen. That's going to go by the wayside when automatic reformatting comes in, which in discussion. From siyamak1981 at gmail.com Sat Sep 18 03:40:16 2021 From: siyamak1981 at gmail.com (siyamak1981 at gmail.com) Date: Sat, 18 Sep 2021 00:40:16 -0700 (PDT) Subject: [Tutor] Hiring Python Developer Message-ID: <614597e0.1c69fb81.8374a.fe94@mx.google.com> * * * * * * * * * * * * * * * * * * [1]Backend Developer [2]s-abasnezhad Hi I'm Siyamak I hope you are doing well Full Stack Web Developer with 4 years of practical experience in object-oriented programing and design patterns and extensive experience with PHP and Python. Proven ability in optimizing web functionality that improve data retrieval and workflow efficiencies. I am interested in new and hard challenges and an interest in teamwork. Are there opportunity for me in your company? For more information please download my resume in below link or contact with me Contact Info My Site Mazandaran, Iran [3]s-abasnezhad.ir +98 919 885 9723 [4]Linkedin Email:siyamak1981 at gmail.com References Visible links 1. http://s-abasnezhad.ir/ 2. http://s-abasnezhad.ir/ 3. http://s-abasnezhad.ir/ 4. https://www.linkedin.com/in/siyamak-abasnezhadtorki From manpritsinghece at gmail.com Sun Sep 19 03:11:05 2021 From: manpritsinghece at gmail.com (Manprit Singh) Date: Sun, 19 Sep 2021 12:41:05 +0530 Subject: [Tutor] using a variable inside function, provided the variable is assigned a value after the function definition Message-ID: Dear Sir , Consider an example given below : def sumofnumber(x): return x+b b = 3 a = 4 ans = sumofnumber(a) print(ans) gives the answer = 7 which is the sum of 4 & 3 . the formal parameter x receives the value of variable a which is 4 and the function returns x+ b , which is 4 +3 = 7 , because 3 is the value of variable b . Here the variable b which is assigned a value 3 after or below the function definition sumofnumber, is used inside the same function. My question is : A variable which is assigned a value below or after the function definition , can be used inside that function definition or not ? is it a good practise ? Regards Manprit Singh Regards Manprit Singh From alan.gauld at yahoo.co.uk Sun Sep 19 04:06:16 2021 From: alan.gauld at yahoo.co.uk (Alan Gauld) Date: Sun, 19 Sep 2021 09:06:16 +0100 Subject: [Tutor] using a variable inside function, provided the variable is assigned a value after the function definition In-Reply-To: References: Message-ID: On 19/09/2021 08:11, Manprit Singh wrote: > def sumofnumber(x): > return x+b > > b = 3 > a = 4 > ans = sumofnumber(a) > print(ans) gives the answer = 7 which is the sum of 4 & 3 . > A variable which is assigned a value below or after the function > definition , can be used inside that function definition or not ? is it a > good practise ? As you've already seen Python doesn't care, so technically it works. But it is very bad practice to rely on global variables inside a function. If the function has to add two numbers then two numbers should be passed in and a result returned. That way the function is reusable in contexts that do not have a variable called b (or use b for some other purpose) In addition the use of an external variable makes the function much more difficult to maintain since the reader has to scan the external code to find out what and where b is. Additionally, if other functions change b as well it becomes very difficult to know or predict the program behaviour, especially in concurrency scenarios. About the only scenario where it is a reasonable thing to do is if b is actually a constant (in which case style says it should be B not b) and therefore never changed. Otherwise always pass in the data your functions need. The other related scenario is inside a class where the methods all access the shared attributes. But that is an order of magnitude less troublesome since it is the object that gets reused not the methods, and the attributes are encapsulated with the methods for maintenance. That leaves only the concurrency problem to deal with. -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ http://www.amazon.com/author/alan_gauld Follow my photo-blog on Flickr at: http://www.flickr.com/photos/alangauldphotos From cs at cskk.id.au Sun Sep 19 18:14:44 2021 From: cs at cskk.id.au (Cameron Simpson) Date: Mon, 20 Sep 2021 08:14:44 +1000 Subject: [Tutor] using a variable inside function, provided the variable is assigned a value after the function definition In-Reply-To: References: Message-ID: On 19Sep2021 12:41, Manprit Singh wrote: >Consider an example given below : >def sumofnumber(x): > return x+b > >b = 3 >a = 4 >ans = sumofnumber(a) >print(ans) gives the answer = 7 which is the sum of 4 & 3 . >the formal parameter x receives the value of variable a which is 4 and the >function returns x+ b , which is 4 +3 = 7 , because 3 is the value of >variable b . >Here the variable b which is assigned a value 3 after or below the function >definition sumofnumber, is used inside the same function. > >My question is : >A variable which is assigned a value below or after the function >definition , can be used inside that function definition or not ? is it a >good practise ? This is just a normal example of having some global state in a global variable. Generally globals are... discouraged. It is usually better to pass state as an formal parameter - that way you functions are "pure" - they do not rely on or change anything outside then, and have no side effects. They're easier to test, too, because you do not need to maintain the external state when you set up the test. Where "b" is initialised is kind of beside then point. It _is_ typical to at least initialise it before the function definition if only so that someone reading the code has seen that initialisation before they try to figure out how the function works. Cheers, Cameron Simpson From sjeik_appie at hotmail.com Thu Sep 23 03:34:59 2021 From: sjeik_appie at hotmail.com (Albert-Jan Roskam) Date: Thu, 23 Sep 2021 09:34:59 +0200 Subject: [Tutor] A Question about coding style In-Reply-To: Message-ID: > This style is uncommon. On a personal > basis I tend to use styles like this if I have several very short test/action pairs. Example: for x, y, z in some-3-tuples...: if x < 0: x = 0 if y > 5: y = 6 if y + z > 10: z /= 2 ==>> I don't have Python here, but won't the "black" code prettifier correct this? It's in my git hooks From cs at cskk.id.au Thu Sep 23 05:36:59 2021 From: cs at cskk.id.au (Cameron Simpson) Date: Thu, 23 Sep 2021 19:36:59 +1000 Subject: [Tutor] A Question about coding style In-Reply-To: References: Message-ID: On 23Sep2021 09:34, Albert-Jan Roskam wrote: > > This style is uncommon. On a personal > > > basis I tend to use styles like this if I have several very short > test/action pairs. Example: > > for x, y, z in some-3-tuples...: > if x < 0: x = 0 > if y > 5: y = 6 > if y + z > 10: z /= 2 > > ==>> I don't have Python here, but won't the "black" code prettifier > correct this? It's in my git hooks "correct"? Reformat, sure. "correct" is in the eye of the beholder, and 'black" is a very unforgiving beholder. I use yapf for my personal code, and it would might fold the lines above because it uses weights to make some of these decisions. "black" enforces a very rigid interpretation of PEP8. "yapf" is more flexible, and has many knobs to adjust its behaviour - its defaults are basicly PEP8 and indeed you can define a style as "start with PEP8 but make these changes", which is how I've defined my personal style for "yapf". Cheers, Cameron Simpson From tcm2118 at columbia.edu Thu Sep 23 08:29:25 2021 From: tcm2118 at columbia.edu (Tristin Cara Moone) Date: Thu, 23 Sep 2021 08:29:25 -0400 Subject: [Tutor] A Question about coding style In-Reply-To: References: Message-ID: On Thursday, September 23, 2021, Cameron Simpson wrote: > On 23Sep2021 09:34, Albert-Jan Roskam wrote: > > > This style is uncommon. On a personal > > > > > basis I tend to use styles like this if I have several very short > > test/action pairs. Example: > > > > for x, y, z in some-3-tuples...: > > if x < 0: x = 0 > > if y > 5: y = 6 > > if y + z > 10: z /= 2 > > > > ==>> I don't have Python here, but won't the "black" code prettifier > > correct this? It's in my git hooks > > "correct"? Reformat, sure. "correct" is in the eye of the beholder, and > 'black" is a very unforgiving beholder. I use yapf for my personal code, > and it would might fold the lines above because it uses weights to make > some of these decisions. > > "black" enforces a very rigid interpretation of PEP8. "yapf" is more > flexible, and has many knobs to adjust its behaviour - its defaults are > basicly PEP8 and indeed you can define a style as "start with PEP8 but > make these changes", which is how I've defined my personal style for > "yapf". > > Cheers, > Cameron Simpson > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > https://mail.python.org/mailman/listinfo/tutor > -- Thank you. From ke.akers.matos at icloud.com Thu Sep 23 21:38:07 2021 From: ke.akers.matos at icloud.com (Kaysi Matos) Date: Thu, 23 Sep 2021 20:38:07 -0500 Subject: [Tutor] Creating a Loop Message-ID: I wrote this program to calculate the square root. I am needing to add a loop to be able to enter multiple integers. This is what I have so far. def main(): print("This program calculates the square root.") digit = int(input("Enter an integer number: ")) square = digit*digit print(f"Square of {digit} is {square}") main() From PyTutor at DancesWithMice.info Sat Sep 25 05:17:15 2021 From: PyTutor at DancesWithMice.info (dn) Date: Sat, 25 Sep 2021 21:17:15 +1200 Subject: [Tutor] Creating a Loop In-Reply-To: References: Message-ID: <8a4b5034-af6d-4097-2cfa-e5e2ed776cf0@DancesWithMice.info> On 24/09/2021 13.38, Kaysi Matos via Tutor wrote: > I wrote this program to calculate the square root. I am needing to add a loop to be able to enter multiple integers. > This is what I have so far. > def main(): > print("This program calculates the square root.") > digit = int(input("Enter an integer number: ")) > square = digit*digit > print(f"Square of {digit} is {square}") > > main() Which type of loop would be best? -- Regards, =dn From joel.goldstick at gmail.com Sat Sep 25 16:01:11 2021 From: joel.goldstick at gmail.com (Joel Goldstick) Date: Sat, 25 Sep 2021 16:01:11 -0400 Subject: [Tutor] Creating a Loop In-Reply-To: <8a4b5034-af6d-4097-2cfa-e5e2ed776cf0@DancesWithMice.info> References: <8a4b5034-af6d-4097-2cfa-e5e2ed776cf0@DancesWithMice.info> Message-ID: On Sat, Sep 25, 2021 at 5:18 AM dn via Tutor wrote: > > On 24/09/2021 13.38, Kaysi Matos via Tutor wrote: > > I wrote this program to calculate the square root. I am needing to add a loop to be able to enter multiple integers. > > This is what I have so far. > > def main(): > > print("This program calculates the square root.") > > digit = int(input("Enter an integer number: ")) > > square = digit*digit > > print(f"Square of {digit} is {square}") > > > > main() > > you want you program to do this line only once: > > print("This program calculates the square root.") so that should not be in your loop This part of you program you want to do repeatedly: > > digit = int(input("Enter an integer number: ")) > > square = digit*digit > > print(f"Square of {digit} is {square}") > Which type of loop would be best? > > -- > Regards, > =dn > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > https://mail.python.org/mailman/listinfo/tutor -- Joel Goldstick From manpritsinghece at gmail.com Sun Sep 26 00:56:01 2021 From: manpritsinghece at gmail.com (Manprit Singh) Date: Sun, 26 Sep 2021 10:26:01 +0530 Subject: [Tutor] "*" operator to unpack argument from a list or tuple Message-ID: Dear Sir, In python documentation there is a very good example of * as unpacking operator, as given below: ls = [3, 6] print(sum(range(*ls))) returns 12 which is a right answer, placing *ls inside range() created a sequence of numbers as given - 3, 4, 5 and their sum is 12. See here in this example there is only one iterable being unpacked inside a function call . Can we unpack more than one iterable inside function call using "*' ? Let's assume an example to find addition of all the numbers inside a list, tuple & set, using function ls = [2, 3] tu = (3, 6) st = {9, 1} The sum will be 24 The implementation is given below: def sumno(*seq): sumno = 0 for num in seq: sumno += num return sumno ls = [2, 3] tu = (3, 6) st = {9, 1} ans = sumno(*ls, *tu, *st) print(ans) returns 24, which is the right answer. If you can see, i have unpacked the list, tuple & set inside the function call, and i am concluding that all the numbers present inside the list, tuple and set will be received by formal parameter seq in the form of tuple, and hence the function sumno will return the sum of all numbers . I just need to know if i can unpack multiple iterables using * in function call or not as done in the previous example ? A second example to generate a pattern given below: 1 1 2 1 1 2 3 2 1 1 2 3 4 3 2 1 1 2 3 4 5 4 3 2 1 For the above pattern, if i write code as given below, is it correct instead of that multiple for loop version conventional example taught in schools. num = 5 for row in range(num): print(" "*(num-row-1), *range(1, row+2), *range(row, 0, -1)) Need your comments Regards Manprit Singh From PyTutor at DancesWithMice.info Sun Sep 26 03:22:56 2021 From: PyTutor at DancesWithMice.info (dn) Date: Sun, 26 Sep 2021 20:22:56 +1300 Subject: [Tutor] "*" operator to unpack argument from a list or tuple In-Reply-To: References: Message-ID: <4e00b159-3edb-92fb-7f7e-16c0615c8b37@DancesWithMice.info> On 26/09/2021 17.56, Manprit Singh wrote: > Dear Sir, > In python documentation there is a very good example of * as unpacking > operator, as given below: > ls = [3, 6] > print(sum(range(*ls))) returns 12 which is a right answer, placing *ls > inside range() created a sequence of numbers as given - 3, 4, 5 and their > sum is 12. > > See here in this example there is only one iterable being unpacked inside a > function call . Can we unpack more than one iterable inside function call > using "*' ? > > Let's assume an example to find addition of all the numbers inside a list, > tuple & set, using function > ls = [2, 3] > tu = (3, 6) > st = {9, 1} > The sum will be 24 > > The implementation is given below: > def sumno(*seq): > sumno = 0 > for num in seq: > sumno += num > return sumno > > ls = [2, 3] > tu = (3, 6) > st = {9, 1} > ans = sumno(*ls, *tu, *st) > print(ans) returns 24, which is the right answer. > If you can see, i have unpacked the list, tuple & set inside the function > call, and i am concluding that all the numbers present inside the list, > tuple and set will be received by formal parameter seq in the form of > tuple, and hence the function sumno will return the sum of all numbers . > > I just need to know if i can unpack multiple iterables using * in function > call or > not as done in the previous example ? Not sure if have understood the question: the code works, ie the arguments are unpacked and then combined into a (single) tuple, which becomes parameter seq. As long as the arguments-provided can be interpreted as *seq, anything goes... > A second example to generate a pattern given below: > > 1 > 1 2 1 > 1 2 3 2 1 > 1 2 3 4 3 2 1 > 1 2 3 4 5 4 3 2 1 > > For the above pattern, if i write code as given below, is it correct instead > > of that multiple for loop version conventional example taught in schools. > > > num = 5 > for row in range(num): > print(" "*(num-row-1), *range(1, row+2), *range(row, 0, -1)) To answer your own question: Is the unpacking process a repetition, ie a form of loop? -- Regards, =dn -- Regards, =dn From PythonList at DancesWithMice.info Sun Sep 26 03:20:46 2021 From: PythonList at DancesWithMice.info (dn) Date: Sun, 26 Sep 2021 20:20:46 +1300 Subject: [Tutor] "*" operator to unpack argument from a list or tuple In-Reply-To: References: Message-ID: On 26/09/2021 17.56, Manprit Singh wrote: > Dear Sir, > In python documentation there is a very good example of * as unpacking > operator, as given below: > ls = [3, 6] > print(sum(range(*ls))) returns 12 which is a right answer, placing *ls > inside range() created a sequence of numbers as given - 3, 4, 5 and their > sum is 12. > > See here in this example there is only one iterable being unpacked inside a > function call . Can we unpack more than one iterable inside function call > using "*' ? > > Let's assume an example to find addition of all the numbers inside a list, > tuple & set, using function > ls = [2, 3] > tu = (3, 6) > st = {9, 1} > The sum will be 24 > > The implementation is given below: > def sumno(*seq): > sumno = 0 > for num in seq: > sumno += num > return sumno > > ls = [2, 3] > tu = (3, 6) > st = {9, 1} > ans = sumno(*ls, *tu, *st) > print(ans) returns 24, which is the right answer. > If you can see, i have unpacked the list, tuple & set inside the function > call, and i am concluding that all the numbers present inside the list, > tuple and set will be received by formal parameter seq in the form of > tuple, and hence the function sumno will return the sum of all numbers . > > I just need to know if i can unpack multiple iterables using * in function > call or > not as done in the previous example ? Not sure if have understood the question: the code works, ie the arguments are unpacked and then combined into a (single) tuple, which becomes parameter seq. As long as the arguments-provided can be interpreted as *seq, anything goes... > A second example to generate a pattern given below: > > 1 > 1 2 1 > 1 2 3 2 1 > 1 2 3 4 3 2 1 > 1 2 3 4 5 4 3 2 1 > > For the above pattern, if i write code as given below, is it correct instead > > of that multiple for loop version conventional example taught in schools. > > > num = 5 > for row in range(num): > print(" "*(num-row-1), *range(1, row+2), *range(row, 0, -1)) To answer your own question: Is the unpacking process a repetition, ie a form of loop? -- Regards, =dn From lucascpcavalcante at gmail.com Mon Sep 27 15:14:38 2021 From: lucascpcavalcante at gmail.com (Lucas Cavalcante) Date: Mon, 27 Sep 2021 22:14:38 +0300 Subject: [Tutor] Looking for open source projects to contribute Message-ID: Hello dear Pythonista colleagues, I'm looking for an open-source project to contribute. I've been studying, practicing, and working with Python for the last 6 years, and Django for the last 2 years, etc. I'm currently employed in a private business, but I'm eager to "level up" as a developer. I also have this particular goal to cause a positive impact on society through coding. May you have any advice or recommendations? Looking forward to hearing from you, Lucas Cavalcante From mats at wichmann.us Mon Sep 27 20:27:28 2021 From: mats at wichmann.us (Mats Wichmann) Date: Mon, 27 Sep 2021 18:27:28 -0600 Subject: [Tutor] Looking for open source projects to contribute In-Reply-To: References: Message-ID: On 9/27/21 13:14, Lucas Cavalcante wrote: > Hello dear Pythonista colleagues, > > I'm looking for an open-source project to contribute. > > I've been studying, practicing, and working with Python for the last 6 > years, and Django for the last 2 years, etc. > I'm currently employed in a private business, but I'm eager to "level up" > as a developer. > I also have this particular goal to cause a positive impact on society > through coding. > > May you have any advice or recommendations? It's easy to find OSS projects that need some help: it's basically all of them. Not quite all of them are as prepared to accept new help, depending on personalities of maintainers, etc. Some projects - you can search for this on github - use a help-wanted label to mark issues that need a contributor. You can look like this (two examples): https://github.com/topics/help-wanted https://github.com/topics/contributions-welcome etc. Then you get to decide if those are worth pursuing. Many issues get filed that are very important to someone, but for the maintainers they're only "that sound like it would be nice to have, but not a priority, we might consider merging it in if someone contributed it" - that kind are not really the road to future happiness. The hard part is picking the right one... offering an opinion, you should pick a project or projects that really interest you, because the hump to becoming a productive contributor involves a lot of hard work and in some cases can be very frustrating in the beginning. It's easier to come through that with an attitude of "This is really cool stuff, and I'd like to help make it better" than with the less personal "I'd like to make a difference, so maybe this is a good place". There are a lot of resources on this on the Internet, not all of which are at all well organized. From leamhall at gmail.com Mon Sep 27 20:36:41 2021 From: leamhall at gmail.com (Leam Hall) Date: Mon, 27 Sep 2021 19:36:41 -0500 Subject: [Tutor] Looking for open source projects to contribute In-Reply-To: References: Message-ID: <28bcfa67-f07f-dfd2-5522-f3cfe633df05@gmail.com> On 9/27/21 7:27 PM, Mats Wichmann wrote: > The hard part is picking the right one... offering an opinion, you should pick a project or projects that really interest you, because the hump to becoming a productive contributor involves? a lot of hard work and in some cases can be very frustrating in the beginning. It's easier to come through that with an attitude of "This is really cool stuff, and I'd like to help make it better" than with the less personal "I'd like to make a difference, so maybe this is a good place". This paragraph should be framed and sent out to the entire planet. -- Systems Programmer (reuel.net/resume) Scribe: The Domici War (domiciwar.net) General Ne'er-do-well (github.com/LeamHall) From adameyring at gmail.com Mon Sep 27 21:23:53 2021 From: adameyring at gmail.com (Adam Eyring) Date: Mon, 27 Sep 2021 21:23:53 -0400 Subject: [Tutor] Looking for open source projects to contribute In-Reply-To: <28bcfa67-f07f-dfd2-5522-f3cfe633df05@gmail.com> References: <28bcfa67-f07f-dfd2-5522-f3cfe633df05@gmail.com> Message-ID: One way is to look for coding groups in your area that provide data science services. One is Code for Philly. https://codeforphilly.org/ AME On Mon, Sep 27, 2021, 8:37 PM Leam Hall wrote: > On 9/27/21 7:27 PM, Mats Wichmann wrote: > > > The hard part is picking the right one... offering an opinion, you > should pick a project or projects that really interest you, because the > hump to becoming a productive contributor involves a lot of hard work and > in some cases can be very frustrating in the beginning. It's easier to come > through that with an attitude of "This is really cool stuff, and I'd like > to help make it better" than with the less personal "I'd like to make a > difference, so maybe this is a good place". > > This paragraph should be framed and sent out to the entire planet. > > > -- > Systems Programmer (reuel.net/resume) > Scribe: The Domici War (domiciwar.net) > General Ne'er-do-well (github.com/LeamHall) > > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > https://mail.python.org/mailman/listinfo/tutor > From manpritsinghece at gmail.com Tue Sep 28 20:20:41 2021 From: manpritsinghece at gmail.com (Manprit Singh) Date: Wed, 29 Sep 2021 05:50:41 +0530 Subject: [Tutor] Valid usage of lambda expression Message-ID: Dear sir, Suppose i have to make 3 functions in a program 1) sqr for returning square of a number 2) cube for returning cube of a number 3) cuberoot for getting cube root of a number Now if start with a function definition like this : def make_powerfunction(n): return lambda x: x**n and then : square = make_powerfunction(2) cube = make_powerfunction(3) cuberoot = make_powerfunction(1/3) and then doing some maths >>> square(3) 9 >>> cube(4) 64 >>> cuberoot(27) 3.0 My question is, is it a good practice to derive new functions in this way, as i have derived the functions square, cube and cuberoot from make_powerfunction. Regards Manprit Singh From cs at cskk.id.au Tue Sep 28 23:59:19 2021 From: cs at cskk.id.au (Cameron Simpson) Date: Wed, 29 Sep 2021 13:59:19 +1000 Subject: [Tutor] Valid usage of lambda expression In-Reply-To: References: Message-ID: On 29Sep2021 05:50, Manprit Singh wrote: >Suppose i have to make 3 functions in a program >1) sqr for returning square of a number >2) cube for returning cube of a number >3) cuberoot for getting cube root of a number > >Now if start with a function definition like this : >def make_powerfunction(n): > return lambda x: x**n > >and then : >square = make_powerfunction(2) >cube = make_powerfunction(3) >cuberoot = make_powerfunction(1/3) > >and then doing some maths >>>> square(3) >9 >>>> cube(4) >64 >>>> cuberoot(27) >3.0 > >My question is, is it a good practice to derive new functions in this way, >as i have derived the functions square, cube and cuberoot from >make_powerfunction. Seems fine to me, given the situation described. What you're doing is essentially currying: providing a more complex function with some of its parameters prefilled: https://en.wikipedia.org/wiki/Currying You can do this in a few ways in Python. Your method is one, using a closure to provide "n" from the scope where you defined the function (lambda). There is also the "partial" function from the functools module. You could also define a callabe class (one with a __call__ method) and prefill instances with some of the function parameters. Once again, good practice in Python is often pragmatic: is your implemenetation concise and readable and efficient? Then it is probably good practice. Cheers, Cameron Simpson From alan.gauld at yahoo.co.uk Wed Sep 29 03:43:55 2021 From: alan.gauld at yahoo.co.uk (Alan Gauld) Date: Wed, 29 Sep 2021 08:43:55 +0100 Subject: [Tutor] Valid usage of lambda expression In-Reply-To: References: Message-ID: <020317C4-9FFE-49F3-868D-219C1821D1B4@yahoo.co.uk> > Now if start with a function definition like this : > def make_powerfunction(n): > return lambda x: x**n > > and then : > square = make_powerfunction(2) > cube = make_powerfunction(3) > cuberoot = make_powerfunction(1/3) > > My question is, is it a good practice to derive new functions in this way, > There are two separate issues here: 1) the use of a factory function to return other functions, specifically partial functions. 2) The use of lambda My response would be that the use of a factory function to create partial functions is fine and quite common in functional programming circles. However the use of lambda is limited to very small functions - a single expression - and the use of partial functions is often used when dealing with more complex expressions. So in practice we would normally it used like: Def complex_func(lots,of,params): Stuff here Def partial1(parm): Return lambda x: complex_func(parm,?1?,x) def partial2(parm): Return lambda x : complex_func(1,parm,x) Etc Where lambda is used only to create the call to complex_func() with the right parameters but not to create the complex func itself. You could replace the lambda with a nested def inside the factory: Def partial3(parm) Def fun(x) Return fun(x,?2?,parm) Return fun So you can do partial functions without use of lambda, the two issues are separate. PS. Apologies for all the uppercase letters, I?m on a tablet and the auto correct is on? Alan G. From juliushamilton100 at gmail.com Wed Sep 29 11:59:52 2021 From: juliushamilton100 at gmail.com (Julius Hamilton) Date: Wed, 29 Sep 2021 17:59:52 +0200 Subject: [Tutor] edit JSON or file in real time Message-ID: Hey, I would like to edit some data - essentially, a 2d array, a spreadsheet of rows and columns - in a live Python shell. I can imagine preferring that the file will remain in a tab-delimited .txt file, because it's very readable and easy to pass between different applications and so on. However, I also would like a smooth, convenient way to load that data into Python in a data type easy to work with in Python, i.e. lists. I also would like to make sure that if I edit something in that data structure it is saved immediately to the corresponding file. I wouldn't want to make an edit to an entry in the data in the live shell and somehow lose my progress because it wasn't written to the file. However, I don't want to explicitly execute a "write list back to file" command every time a change a value in the list. I would rather find some simple mode or mechanism where Python knows the list I am editing corresponds to a file, and it understands the correspondence. I.e., list(0) is the first entry in the tab-delimited file. Is there any way that I could edit a list's value and it would automatically write to the file? Do I need to create my own object with its own methods, rather than the native Python list? Thank you, Julius From vimanuelt at fastmail.fm Mon Sep 27 19:32:43 2021 From: vimanuelt at fastmail.fm (vimanuelt) Date: Tue, 28 Sep 2021 08:32:43 +0900 Subject: [Tutor] Looking for open source projects to contribute In-Reply-To: References: Message-ID: <12bdf9ea-5dbd-4517-bf02-366858a7dc02@www.fastmail.com> Hello Lucas and all, GhostBSD, a distribution of FreeBSD, is in need of Pythonista volunteers who want to build graphical system utilities for improving the desktop experience. Most applications are written in Python. About GhostBSD: Download: https://download.ghostbsd.org/development/amd64/latest/ Sources: https://github.com/GhostBSD Telegram: https://t.me/ghostbsd_dev && https://t.me/ghostbsd Happy Hacking, Vic Thacker On Tue, Sep 28, 2021, at 04:14, Lucas Cavalcante wrote: > Hello dear Pythonista colleagues, > > I'm looking for an open-source project to contribute. > > I've been studying, practicing, and working with Python for the last 6 > years, and Django for the last 2 years, etc. > I'm currently employed in a private business, but I'm eager to "level up" > as a developer. > I also have this particular goal to cause a positive impact on society > through coding. > > May you have any advice or recommendations? > > Looking forward to hearing from you, > Lucas Cavalcante > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > https://mail.python.org/mailman/listinfo/tutor From PyTutor at DancesWithMice.info Wed Sep 29 14:40:17 2021 From: PyTutor at DancesWithMice.info (dn) Date: Thu, 30 Sep 2021 07:40:17 +1300 Subject: [Tutor] edit JSON or file in real time In-Reply-To: References: Message-ID: On 30/09/2021 04.59, Julius Hamilton wrote: > Hey, > > I would like to edit some data - essentially, a 2d array, a spreadsheet of > rows and columns - in a live Python shell. > > I can imagine preferring that the file will remain in a tab-delimited .txt > file, because it's very readable and easy to pass between different > applications and so on. > > However, I also would like a smooth, convenient way to load that data into > Python in a data type easy to work with in Python, i.e. lists. > > I also would like to make sure that if I edit something in that data > structure it is saved immediately to the corresponding file. I wouldn't > want to make an edit to an entry in the data in the live shell and somehow > lose my progress because it wasn't written to the file. > > However, I don't want to explicitly execute a "write list back to file" > command every time a change a value in the list. > > I would rather find some simple mode or mechanism where Python knows the > list I am editing corresponds to a file, and it understands the > correspondence. I.e., list(0) is the first entry in the tab-delimited file. > > Is there any way that I could edit a list's value and it would > automatically write to the file? Do I need to create my own object with its > own methods, rather than the native Python list? https://duckduckgo.com/?t=ffab&q=spreadsheet+python&atb=v269-1&ia=web Includes libraries which will facilitate spreadsheet I/O, and Python versions of spreadsheet software. -- Regards, =dn From wlfraed at ix.netcom.com Wed Sep 29 16:28:33 2021 From: wlfraed at ix.netcom.com (Dennis Lee Bieber) Date: Wed, 29 Sep 2021 16:28:33 -0400 Subject: [Tutor] edit JSON or file in real time References: Message-ID: On Wed, 29 Sep 2021 17:59:52 +0200, Julius Hamilton declaimed the following: > >However, I also would like a smooth, convenient way to load that data into >Python in a data type easy to work with in Python, i.e. lists. If it is a tab separated file, the CSV module can read it if you provide the proper "dialect". > >I also would like to make sure that if I edit something in that data >structure it is saved immediately to the corresponding file. I wouldn't >want to make an edit to an entry in the data in the live shell and somehow >lose my progress because it wasn't written to the file. > You can't unless every record has exactly the same number of bytes (if the data is UTF-8, and you use any characters that are not in the 7-bit ASCII set, the number of bytes in the row might change). A change in the number of bytes means you either leave old data (number of bytes got smaller) OR you overwrite part of the next record (more bytes in record). For the case where bytes stays the same (but one record may be different length than another), you would have to use lower level file I/O that provides seek/tell functions; use tell() before a record read to save the start position of the record; read the record, process it, use seek() to go back to the start of that record, write the record (you may or may not need to use seek() using the value from tell() + length of record to ensure you are positioned at the proper start of the next record). > >I would rather find some simple mode or mechanism where Python knows the >list I am editing corresponds to a file, and it understands the >correspondence. I.e., list(0) is the first entry in the tab-delimited file. > https://docs.python.org/3/library/dbm.html but you will have to convert the data first -- DBM files act like simple on-disk dictionaries; each record has a string key (for you, likely the record number, but the record data would have to be a string -- the TSV row as is, not split into a list). https://docs.python.org/3/library/shelve.html#module-shelve similar to DBM, but the data value can be a Python list rather than TSV -- the key must still be a string. Problem is that shelves are not really portable to non-Python applications, so you still need to have import/export converters to go between portable TSV and internal working shelf file. Neither has "automatic" update of the file. The normal sequence is internal_data = dbm_shelf [ key ] #read record dbm_shelf [ key ] = process(internal_data) #write record shelf with writeback=True will keep a cache of accessed records, and can write all records using a single .sync() call. -- Wulfraed Dennis Lee Bieber AF6VN wlfraed at ix.netcom.com http://wlfraed.microdiversity.freeddns.org/ From rajeshkoot190 at gmail.com Wed Sep 29 21:48:28 2021 From: rajeshkoot190 at gmail.com (Rajesh Koot) Date: Thu, 30 Sep 2021 07:18:28 +0530 Subject: [Tutor] Mp3 to MP4 using pyhon Message-ID: Hello, I just wanted to know if there is some method to convert MP3 file into MP4 using coding(running script)in python in automation. Please reply ASAP From chris_roysmith at internode.on.net Thu Sep 30 04:12:40 2021 From: chris_roysmith at internode.on.net (Chris Roy-Smith) Date: Thu, 30 Sep 2021 18:12:40 +1000 Subject: [Tutor] Mp3 to MP4 using pyhon In-Reply-To: References: Message-ID: <574a5a76-fa50-af34-d5f9-04491f8ce2c4@internode.on.net> On 30/9/21 11:48 am, Rajesh Koot wrote: > Hello, > I just wanted to know if there is some method to convert MP3 file into MP4 > using coding(running script)in python in automation. > Please reply ASAP > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > https://mail.python.org/mailman/listinfo/tutor > is this any help? https://codereview.stackexchange.com/questions/191204/converting-mp3-albums-into-mp4-videos-for-youtube regards, Chris Roy-Smith From alan.gauld at yahoo.co.uk Thu Sep 30 04:52:34 2021 From: alan.gauld at yahoo.co.uk (Alan Gauld) Date: Thu, 30 Sep 2021 09:52:34 +0100 Subject: [Tutor] Mp3 to MP4 using pyhon In-Reply-To: References: Message-ID: On 30/09/2021 02:48, Rajesh Koot wrote: > Hello, > I just wanted to know if there is some method to convert MP3 file into MP4 > using coding(running script)in python in automation. > Please reply ASAP I'd suggest a wrapper around ffmpeg to set the various options. A simple command alias could do the same job but a Python script could do more in the way of user friendliness and intelligent argument validation. As far as I can recall ffmpeg is available on Windows, Mac and Linux. -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ http://www.amazon.com/author/alan_gauld Follow my photo-blog on Flickr at: http://www.flickr.com/photos/alangauldphotos From manpritsinghece at gmail.com Thu Sep 30 04:59:59 2021 From: manpritsinghece at gmail.com (Manprit Singh) Date: Thu, 30 Sep 2021 14:29:59 +0530 Subject: [Tutor] filter() builtin function Message-ID: Dear sir, For the filter function in Python documentation , a line is written as below: Construct an iterator from those elements of *iterable* for which *function* returns true. *What does that true means - Boolen value True or true object - for example 1* *Like if I need only odd numbers from a list , what will be the correct lambda function to be placed inside the filter function ?* *lambda x: x%2 (That will return 1 for odd numbers which is a true object)* *or * *lambda x : x%2 == 1 ( Will return Boolean True for odd numbers)* *seq = [2, 3, 6, 9, 0, 7]list(filter(lambda x: x%2, seq)) gives the answer = *[3, 9, 7] seq = [2, 3, 6, 9, 0, 7] list(filter(lambda x: x%2 == 1, seq)) also gives the same answer = [3, 9, 7] Which one is the correct way to do the task solved just above in 2 ways ? Regards Manprit Singh From alan.gauld at yahoo.co.uk Thu Sep 30 05:54:26 2021 From: alan.gauld at yahoo.co.uk (Alan Gauld) Date: Thu, 30 Sep 2021 10:54:26 +0100 Subject: [Tutor] filter() builtin function In-Reply-To: References: Message-ID: On 30/09/2021 09:59, Manprit Singh wrote: > Dear sir, > > For the filter function in Python documentation , a line is written as > below: > > Construct an iterator from those elements of *iterable* for which *function* > returns true. > > *What does that true means - Boolen value True or true object In lower case it means something that Python considers true. True, Non-empty, non-zero etc. > *lambda x: x%2 (That will return 1 for odd numbers which is a true > object)* > > *or * > > *lambda x : x%2 == 1 ( Will return Boolean True for odd numbers)* Why not just try it and see? The interpreter is the definitive answer. > *seq = [2, 3, 6, 9, 0, 7]list(filter(lambda x: x%2, seq)) gives the answer > = *[3, 9, 7] > > seq = [2, 3, 6, 9, 0, 7] > list(filter(lambda x: x%2 == 1, seq)) also gives the same answer = [3, 9, > 7] > > Which one is the correct way to do the task solved just above in 2 ways ? They are both correct. And in modern python the normal way to do this would be to use neither. Instead use a list comprehension or generator expression: [n for n in seq if n%2] filter is rarely(never?) needed nowadays. -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ http://www.amazon.com/author/alan_gauld Follow my photo-blog on Flickr at: http://www.flickr.com/photos/alangauldphotos From mmssdd1920 at gmail.com Thu Sep 30 04:07:03 2021 From: mmssdd1920 at gmail.com (Msd De) Date: Thu, 30 Sep 2021 13:37:03 +0530 Subject: [Tutor] precision handling Message-ID: Hello, The two same numbers generated in python 2.7 when subtracted should give zero. Instead it gives - 4.7393372903e-07. The number are given below: 176697092.941 - 176697092.941 = - 4.7393372903e-07 How would I increase the precision for the whole document in python? Thanks in advance. Regards, From roel at roelschroeven.net Thu Sep 30 05:07:19 2021 From: roel at roelschroeven.net (Roel Schroeven) Date: Thu, 30 Sep 2021 11:07:19 +0200 Subject: [Tutor] Mp3 to MP4 using pyhon In-Reply-To: References: Message-ID: <132c2098-adf0-8c96-59a0-26126d46899b@roelschroeven.net> Op 30/09/2021 om 10:52 schreef Alan Gauld via Tutor: > On 30/09/2021 02:48, Rajesh Koot wrote: > > Hello, > > I just wanted to know if there is some method to convert MP3 file into MP4 > > using coding(running script)in python in automation. > > Please reply ASAP > > > I'd suggest a wrapper around ffmpeg to set the various options. > > A simple command alias could do the same job but a Python script > could do more in the way of user friendliness and intelligent > argument validation. > > As far as I can recall ffmpeg is available on Windows, Mac > and Linux. Yep, ffmpeg is the common workhorse for all kinds of audio and/or video conversions. Get it from https://ffmpeg.org/download.html or from your OS's package manager. Ffmpeg is very versatile, with the disadvantage that it can be quite a chore to figure out the correct command line for your use case. In this case, you'll probably need something like this (from https://stackoverflow.com/a/16376637/59122): ??? ffmpeg? -i Kalimba.mp3 -c:a aac -vn Kalimba.m4a (for auto MP4 files, .m4a is commonly used as the file extension) To execute ffmpeg from your Python script, use the subprocess module. -- "Il semble que la perfection soit atteinte non quand il n'y a plus rien ? ajouter, mais quand il n'y a plus rien ? retrancher." "Perfectie is niet bereikt als er niets meer toe te voegen is, maar als er niets meer weg te nemen is." -- Antoine de Saint-Exup?ry From roel at roelschroeven.net Thu Sep 30 05:16:05 2021 From: roel at roelschroeven.net (Roel Schroeven) Date: Thu, 30 Sep 2021 11:16:05 +0200 Subject: [Tutor] filter() builtin function In-Reply-To: References: Message-ID: <86b51f83-a0e0-dea7-26ef-d15ef2dd877b@roelschroeven.net> Op 30/09/2021 om 10:59 schreef Manprit Singh: > For the filter function in Python documentation , a line is written as > below: > > Construct an iterator from those elements of *iterable* for which *function* > returns true. > > *What does that true means - Boolen value True or true object - for > example 1* It's not stated explicitly but they probably mean 'true' as a shorthand for 'any value which evaluates to True in a boolean context'. That means True, numbers different from 0, non-empty collections and strings, and probably some other things I'm forgetting. Basically anything for which bool(thing) == True. > *Like if I need only odd numbers from a list , what will be the correct > lambda function to be placed inside the filter function ?* > > > *lambda x: x%2 (That will return 1 for odd numbers which is a true > object)* > > *or * > > *lambda x : x%2 == 1 ( Will return Boolean True for odd numbers)* Both are correct and will generate the same answer. My preference is the second, because it states the intention much cleaner: keep the elements which have 1 as remainder when divided by 2 (which is what odd numbers are). Always remember that you write code as much for other programmers (including future yourself) as for the computer (even more for programmers than for the computer, one could argue), therefore barring significant performance issues it's always best to write code that best states your intention. -- "Il semble que la perfection soit atteinte non quand il n'y a plus rien ? ajouter, mais quand il n'y a plus rien ? retrancher." "Perfectie is niet bereikt als er niets meer toe te voegen is, maar als er niets meer weg te nemen is." -- Antoine de Saint-Exup?ry From cs at cskk.id.au Thu Sep 30 05:22:52 2021 From: cs at cskk.id.au (Cameron Simpson) Date: Thu, 30 Sep 2021 19:22:52 +1000 Subject: [Tutor] filter() builtin function In-Reply-To: References: Message-ID: On 30Sep2021 14:29, Manprit Singh wrote: >For the filter function in Python documentation , a line is written as >below: > >Construct an iterator from those elements of *iterable* for which *function* >returns true. > >*What does that true means - Boolen value True or true object - for >example 1* A true object will do. >*Like if I need only odd numbers from a list , what will be the correct >lambda function to be placed inside the filter function ?* A test that a number is odd: lambda n: test-if-n-is-odd >*lambda x: x%2 (That will return 1 for odd numbers which is a true >object)* That would do. I would probably be inclined to go the whole way: lambda x: x%2 == 1 to make my meaning clear. >*lambda x : x%2 == 1 ( Will return Boolean True for odd numbers)* I'd do that, but only for purposes of clarity. >seq = [2, 3, 6, 9, 0, 7] >list(filter(lambda x: x%2, seq)) >gives the answer >= [3, 9, 7] Seems correct. >seq = [2, 3, 6, 9, 0, 7] >list(filter(lambda x: x%2 == 1, seq)) also gives the same answer = [3, 9, 7] > >Which one is the correct way to do the task solved just above in 2 >ways ? They're both correct. The second one more precisely specifies "oddness". You seem heavily invested in "correct" and 'acceptable" ways to do things. For many of us, there are good ways and bad ways to do things, but things are only "incorrect" if they will give wrong answers i.e. they are buggy. As usual my generic advice is: - concise - readable Cheers, Cameron Simpson From wlfraed at ix.netcom.com Thu Sep 30 10:43:23 2021 From: wlfraed at ix.netcom.com (Dennis Lee Bieber) Date: Thu, 30 Sep 2021 10:43:23 -0400 Subject: [Tutor] precision handling References: Message-ID: On Thu, 30 Sep 2021 13:37:03 +0530, Msd De declaimed the following: >Hello, >The two same numbers generated in python 2.7 when subtracted should give >zero. Instead it gives - 4.7393372903e-07. >The number are given below: > >176697092.941 - 176697092.941 = - 4.7393372903e-07 > >How would I increase the precision for the whole document in python? What "document"? You state "generated" -- but don't show the code doing that generation. You have just encountered the fact that floating point arithmetic is not exact -- there may be some small tail-end that is not displayed, etc. Note that entering the exact text you have above does produce 0.0 PythonWin 3.8.2 (default, Aug 25 2020, 15:54:26) [MSC v.1900 64 bit (AMD64)] on win32. Portions Copyright 1994-2018 Mark Hammond - see 'Help/About PythonWin' for further copyright information. >>> 176697092.941 - 176697092.941 0.0 >>> >>> a = 176697092.0 + 0.941 >>> a 176697092.941 >>> a - 176697092.0 0.9410000145435333 >>> >>> a - 176697092.0 - 0.941 1.454353337759784e-08 >>> Try using the Decimal package -- but you may need to modify a lot of code to ensure the numbers stay decimal throughout. -- Wulfraed Dennis Lee Bieber AF6VN wlfraed at ix.netcom.com http://wlfraed.microdiversity.freeddns.org/ From roel at roelschroeven.net Thu Sep 30 10:34:01 2021 From: roel at roelschroeven.net (Roel Schroeven) Date: Thu, 30 Sep 2021 16:34:01 +0200 Subject: [Tutor] Mp3 to MP4 using pyhon In-Reply-To: <132c2098-adf0-8c96-59a0-26126d46899b@roelschroeven.net> References: <132c2098-adf0-8c96-59a0-26126d46899b@roelschroeven.net> Message-ID: <6f6fe638-78c2-053f-3000-ca3abb73659c@roelschroeven.net> Op 30/09/2021 om 11:07 schreef Roel Schroeven: > (for auto MP4 files, .m4a is commonly used as the file extension) That should read "audio MP4 files" instead of "auto MP4 files". Sorry for any confusion. -- "I've come up with a set of rules that describe our reactions to technologies: 1. Anything that is in the world when you?re born is normal and ordinary and is just a natural part of the way the world works. 2. Anything that's invented between when you?re fifteen and thirty-five is new and exciting and revolutionary and you can probably get a career in it. 3. Anything invented after you're thirty-five is against the natural order of things." -- Douglas Adams, The Salmon of Doubt From PyTutor at DancesWithMice.info Thu Sep 30 14:37:37 2021 From: PyTutor at DancesWithMice.info (dn) Date: Fri, 1 Oct 2021 07:37:37 +1300 Subject: [Tutor] Mp3 to MP4 using pyhon In-Reply-To: <6f6fe638-78c2-053f-3000-ca3abb73659c@roelschroeven.net> References: <132c2098-adf0-8c96-59a0-26126d46899b@roelschroeven.net> <6f6fe638-78c2-053f-3000-ca3abb73659c@roelschroeven.net> Message-ID: <22840372-c8e4-047e-20e5-918274cf8d2c@DancesWithMice.info> On 01/10/2021 03.34, Roel Schroeven wrote: > Op 30/09/2021 om 11:07 schreef Roel Schroeven: >> (for auto MP4 files, .m4a is commonly used as the file extension) > That should read "audio MP4 files" instead of "auto MP4 files". Sorry > for any confusion. Thanks for this: I was just looking-up "auto" in the "manual"... -- Regards, =dn From PyTutor at DancesWithMice.info Thu Sep 30 14:54:42 2021 From: PyTutor at DancesWithMice.info (dn) Date: Fri, 1 Oct 2021 07:54:42 +1300 Subject: [Tutor] filter() builtin function In-Reply-To: References: Message-ID: On 30/09/2021 22.22, Cameron Simpson wrote: > On 30Sep2021 14:29, Manprit Singh wrote: >> For the filter function in Python documentation , a line is written as >> below: >> >> Construct an iterator from those elements of *iterable* for which *function* >> returns true. >> >> *What does that true means - Boolen value True or true object - for >> example 1* > > A true object will do. > >> *Like if I need only odd numbers from a list , what will be the correct >> lambda function to be placed inside the filter function ?* > > A test that a number is odd: > > lambda n: test-if-n-is-odd > >> *lambda x: x%2 (That will return 1 for odd numbers which is a true >> object)* > > That would do. I would probably be inclined to go the whole way: > > lambda x: x%2 == 1 > > to make my meaning clear. > >> *lambda x : x%2 == 1 ( Will return Boolean True for odd numbers)* > > I'd do that, but only for purposes of clarity. > >> seq = [2, 3, 6, 9, 0, 7] >> list(filter(lambda x: x%2, seq)) >> gives the answer >> = [3, 9, 7] > > Seems correct. > >> seq = [2, 3, 6, 9, 0, 7] >> list(filter(lambda x: x%2 == 1, seq)) also gives the same answer = [3, 9, 7] >> >> Which one is the correct way to do the task solved just above in 2 >> ways ? > > They're both correct. The second one more precisely specifies "oddness". > > You seem heavily invested in "correct" and 'acceptable" ways to do > things. For many of us, there are good ways and bad ways to do things, > but things are only "incorrect" if they will give wrong answers i.e. > they are buggy. > > As usual my generic advice is: > - concise > - readable +1 Surely though, are themselves arguments against using an (unnamed) lambda function, instead of: def is_odd( number ): return number % 2 == 1 leading to: list( filter( is_odd, seq) ) instead of: list(filter(lambda x: x%2, seq)) Zen: explicit > implicit If valuing "concise" and "clever", consider employing list-comprehensions/generators. -- Regards, =dn From alan.gauld at yahoo.co.uk Thu Sep 30 16:20:42 2021 From: alan.gauld at yahoo.co.uk (Alan Gauld) Date: Thu, 30 Sep 2021 21:20:42 +0100 Subject: [Tutor] precision handling In-Reply-To: References: Message-ID: On 30/09/2021 09:07, Msd De wrote: > Hello, > The two same numbers generated in python 2.7 when subtracted should give > zero. Instead it gives - 4.7393372903e-07. You do realize that Python 2.7 is unsupported legacy software? You should really be using Python 3 by now. > The number are given below: > > 176697092.941 - 176697092.941 = - 4.7393372903e-07 Not in any version of python I've tried - including 2.7. Can we see your actual code and output? And which OS too, just to be sure. -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ http://www.amazon.com/author/alan_gauld Follow my photo-blog on Flickr at: http://www.flickr.com/photos/alangauldphotos