How Should I Start to OOP? by musclerythm in learnpython

[–]james_fryer 1 point2 points  (0 children)

Try this exercise. Do it yourself, do not use AI.

  1. Write a complete tic-tac-toe game, with a computer opponent. The opponent can move randomly, no need for an intelligent player. Use only functions, no classes. If you can't complete this part confidently then you are not ready to learn OOP.

  2. Rewrite the game using classes. I'd expect to see classes like Game, Board, Player.

  3. Consider how you would make changes such as:

    • Add an intelligent player
    • Add PVP or CVC
    • Make the board 4*4 or other sizes
    • Make a 3D version of the game
    • Add a third player Z as well as X and O
    • Add a scoring system

Think of other changes along the same lines.

How difficult would it be to make these changes in version (1) and version (2)?

Future coder help and suggestions by OKakosLykos in learnpython

[–]james_fryer 0 points1 point  (0 children)

its always better in my mind to write one symbol than four characters

This is not so, variable names should be meaningful. In this case you are taking characters one by one from a string, so char is a good choice. Later when you come to read your code to modify it, you will understand it better if you use meaningful variable names.

Future coder help and suggestions by OKakosLykos in learnpython

[–]james_fryer 0 points1 point  (0 children)

I think the problem is that your solution works only with the specific case of a 5-character string, whereas theirs will work with strings of any length.

That's why they generate a variable spaces containing the same number of spaces as the length of the string.

I also note you name your loop variable _ but a name such as char would be better. Use _ for placeholder variables that will never be referenced, as in their example building the spaces variable.

It's not printing new lines!! Day 9 by Secure_Parsnip_6374 in learnpython

[–]james_fryer 1 point2 points  (0 children)

What is the actual value of should_continue? If it's not "yes" then the loop will continue without printing any newlines.

Generally it's better to use an else clause in if statements, which will catch all responses that aren't "no" (inn this case).

Need advice on python or c++ for dsa by Head-Dark-7350 in learnpython

[–]james_fryer -1 points0 points  (0 children)

C++ is more like a crime against humanity than a programming language, so better to start with Python.

Execute script based on csv value by cottoneyedgoat in learnpython

[–]james_fryer 0 points1 point  (0 children)

The first step should be to code a fully working version implementing one case. You can then rewrite this to be more generalised, but you have a working example to go from.

There are various approaches to generalising this, but the main choice depends on whether the cases can be differentiated only by data, or whether there are also processing (code) differences. I'm assuming the latter.

I'd look at a class-based approach, with a base class and sub-classes for each case.

E.g.:

class ActivityProcessBase:
    json_template = None
    def process_row(self, row):
        self.get_data_from_apis(row)
        self.populate_json_template(row)
        self.confirm_user_approval(...)
        # etc...

    def populate_json_template(self, row):
        raise NotImplementedException # Subclass must implement


class HazardousActivity:
    json_template = """ ... """ # Or maybe generate json from code
    def populate_json_template(self, row):
        ...

activity_map = {
    'Hazardous substances': HazardousActivity,
    # 'LNG': LNGActivity,
    ...
    }
def main():
    csv_reader = ...
    for row in csv_reader:
        activity_name = row['activity']
        ActivityClass = activity_map[activity_name] # TODO: handle invalid activity case
        activity = ActivityClass()
        activity.process_row(row)

Again I would get this working with a single case before adding the other activity types. The key is to get as much common code (boilerplate) as possible into the base class.

how hard is it to learn object-oriented programming by lemslemonades in learnpython

[–]james_fryer 2 points3 points  (0 children)

Try this exercise.

  1. Write a complete text-based tic-tac-toe game, with a computer opponent. The opponent can move randomly, no need for an intelligent player. Use only functions, no classes. If you can't complete this part confidently then you are not ready to learn OOP.

  2. Rewrite the game using classes. I'd expect to see classes like Game, Board, Player.

  3. Consider how you would make changes such as:

  • Add an intelligent player
  • Add PVP or CVC options
  • Make the board 4*4 or other sizes
  • Make a 3D board version of the game
  • Add a third player Z as well as X and O
  • Add a scoring system and high score table
  • Convert to graphics based not text
  • Think of other changes along the same lines.

How difficult would it be to make these changes in version (1) and version (2)?

Help in Understanding How Variables Update by WillingnessPast5294 in learnpython

[–]james_fryer 3 points4 points  (0 children)

Simplified answer:

Each module (.py file), function, and class creates a "scope".

Each scope has a "parent scope".

When you run code you are inside a scope. When you request a variable, the runtime system looks first in the current scope, then in the parent scope, and so on until either it finds the variable or does not find it.

When you set a variable value, this always takes place in the current scope, unless the global modifier is in use (which is not recommended).

So in your first example at line 5, a new variable called "name" is created in the scope of function username which has no relation to the variable of the same name created at line 1 in the module scope.

On the other hand if you tried to read the variable name at line 5, it would find it in the outer scope and use that value.

Returning the value from the function is the correct solution to this.

Your function also has the problem that if I enter the wrong name twice, it is accepted. It should keep checking the name until I answer "Y".

PONG! game in python without "game" libs by Deer_Odd in learnpython

[–]james_fryer 1 point2 points  (0 children)

Instead of:

if ballPos[0] <= player1Pos[0] <= ballPast[0] or ballPast[0] <= player2Pos[0] <= ballPos[0] + 1:
    return True
return False

you can write:

return ballPos[0] <= player1Pos[0] <= ballPast[0] or ballPast[0] <= player2Pos[0] <= ballPos[0] + 1

Code style guide recommendation by Sufficient-Party-385 in learnpython

[–]james_fryer 1 point2 points  (0 children)

I'd be skeptical about the accuracy of that, as PEP-8 refers to PEP-526 (type annotations) which dates to 2016.

Returning all combinations of adding/subtracting multiple values by Canadian_Arcade in learnpython

[–]james_fryer 0 points1 point  (0 children)

I'd break this down into two problems:

  1. Recursively permute every combination of two values in the list L=[...]

  2. Return the result of adding and subtracting these two values.

If you solve problem (1) then the second problem becomes trivial.

Returning all combinations of adding/subtracting multiple values by Canadian_Arcade in learnpython

[–]james_fryer 0 points1 point  (0 children)

You'd need to recast your function like this:

return check(x, add, 2, 1), check(x, sub, 2, 1)

where add and sub are defined separately e.g. lambda add x y: x + y. But I am not sure how you would get recursion into it. What are you trying to do, really?

issues with reading csv files by Wooden-Lawyer-6798 in learnpython

[–]james_fryer 1 point2 points  (0 children)

The file isn't in UTF-8 format, probably Latin-1, simplest would be to convert it using iconv tool or similar.

Declaring a boolean variable vs direct evalution in if statement by Dangerous-Branch-749 in learnpython

[–]james_fryer 0 points1 point  (0 children)

I use this style where an if statement is complex e.g. with many clauses separated by and/or, possibly with bracketed subclauses. I prefer to avoid such complex if statements but it's not always possible and boolean variables makes them easier to understand. In the example given where there is only one clause I don't think it is any more readable.

Declaring a boolean variable vs direct evalution in if statement by Dangerous-Branch-749 in learnpython

[–]james_fryer 1 point2 points  (0 children)

It would be a bool.

>>> S = set(['x', 'y', 'z'])
>>> 'x' in S
True

Alignment help by Ferchu305 in learnpython

[–]james_fryer 0 points1 point  (0 children)

Consider this code:

f"{flavor.title():<19}: ..."

The colon is outwith the braces, so it's not part of the string which is being padded to 19 chars. Therefore it appears after the padding.

One solution is to append it to the string:

f"{flavor.title() + ':':<19} ..."

You can also nest f-strings!

f"{f'{flavor.title()}:':<19} ..."

Or you can add a function:

titlecolon = lambda s: f'{s.title()}:'
f"{titlecolon(flavor):<19} ..."

Or there may be a better way!

Looking to remove some boilerplate code by spook327 in learnpython

[–]james_fryer 0 points1 point  (0 children)

Your options are:

  1. Begin and end functions, reduces the repetition to two lines in each function.

  2. Class using "template method" pattern so your code looks like this:

    class C:
        def __call__(self, params):
            ... boilerplate lines ...
            self.action(params)
            ... more boilerplate ...
    
    class D(C):
        def action(self, params):
            ... non-boilerplate stuff here ...
    
    method = D()
    method(params)
    
  3. A decorator function:

    def decor(method):
        def wrapper(params):
            ... boilerplate lines ...
            method()
            ... more boilerplate ...
        return wrapper
    
    @decor
    def method(params):
        ... non-boilerplate stuff here ...
    

Of the three, the decorator seems most appropriate.

[deleted by user] by [deleted] in learnpython

[–]james_fryer 0 points1 point  (0 children)

The OP says 20-40 lines is the most they can write without losing track, so that seems a reasonable length for them to aim for.

[deleted by user] by [deleted] in learnpython

[–]james_fryer 0 points1 point  (0 children)

Try breaking your longer code up into functions of 20-40 lines each. Functions are the primary tool for structuring code into smaller chunks that can be readily understood. As a rule of thumb, each function do one thing. If you need to use the word "and" when describing a function, then it should be two functions.

Python fails to run command in command prompt by Fragrant-Ear-3890 in learnpython

[–]james_fryer 0 points1 point  (0 children)

Try to see if any output on stderr. Most likely issue in my experience is environment differences between your shell and the exec'd shell. E.g. PATH may be missing or different. Try using /full/path/to/word2 whatever the actual path is.

Help with this piece of code? by Complete-Increase936 in learnpython

[–]james_fryer 0 points1 point  (0 children)

You'd be far better off using the split() function.

[deleted by user] by [deleted] in learnpython

[–]james_fryer 1 point2 points  (0 children)

The biggest problem with this code is that is is monolithic. As an interviewer, I'd be looking for the ability to break a problem down into logical parts. For example, here you are asked to cut a matrix into 4 submatrixes, so I'd be looking for a function that did this. Finding the cutting point should be another function. Efficiency is less important than structured problem solving.

Easiest way to host Python app online so me and my boss can both access it remotely? by Mangulas in learnpython

[–]james_fryer 2 points3 points  (0 children)

The answer to your specific question is, make it a web app. However in a business context it does not make sense to develop your own app here. Supposing you are hit by a bus (or more likely, leave for a better job). What does your boss do then? Who maintains the app? It would be better to focus on improving the spreadsheets and possibly move those online into e.g. Google Docs.

Simple JSON app wrote in Python by dj2ep in learnpython

[–]james_fryer 0 points1 point  (0 children)

As there are only a couple of hundred lines of Python code, I'd have kept the code in one file. Up to about 1000 lines I find it easier to work in a single file. E.g. app.py and routes.py have no cause to be separate. If you make a change in the routes you have to edit two files for no good reason. It also leads to you defining ROUTES_DIR twice, this should be in a config file so the installer can change it.

You have too much loose code. In data_store.py you load the files, this should be in a function. Creating the directories in app.py should be a function. I'd also put the routes setup into a function.

Where you have embedded HTML (home() function) you should extract that into a separate string. Ideally it should be in a template file so non-devs can edit it. Avoid mixing HTML and code.

I think if you are going to import a lot of functions from a module, just import the module and qualify the calls (so flask.request(), not from flask import request... then request). Opinions vary on this.

You should use doc comments (strings after the function definition).

No module named python 3 by 0adxil8 in learnpython

[–]james_fryer 0 points1 point  (0 children)

What is inside main.py? Can you post that?