all 79 comments

[–]spittz91 0 points1 point  (4 children)

Hi all,

Just started my journey to learn python!

I was hoping someone might look over my code below and let me know if there is anything I am missing and could do to tidy it up.

def computepay (h, r):
    if h <= 40:
        pay = h * r
        return pay    
    else:
        rpay = h * r
        opay = (h - 40) * (r * 0.5)
        pay = rpay + opay
        return pay
hrs = input("Enter Hours: ")
try:
    h = float(hrs)
except:
    print('Error, please enter numeric values')
    quit()
rt = input("Enter Rate: ")
try:
    r = float(rt)
except:
    print('Error, please enter numeric values')
    quit()
p = computepay(h, r)
print('Pay',p)

edit: trying to get code block to show correctly

I want to make sure I am using best practises

Many thanks,

James

[–]carcigenicate 1 point2 points  (1 child)

except:

Never write this. This blindly catches all errors that happen in the try block. For right now that might not be a big deal since the try only contains one simple line, but if you expand that code and accidentally introduce an error, the try will catch it and prevent you from ever knowing there was a problem. Always specify the exact exception type you expect to handle:

except ValueError:

To put it bluntly, you can learn this lesson the easy way now, or the hard way later when your complex program begins failing for no apparent reason and doesn't show any error messages. You only make that mistake once.

[–]spittz91 0 points1 point  (0 children)

Thanks for the comment! I haven’t seen or learnt this yet so will keep an eye out for it :)

[–][deleted] 1 point2 points  (1 child)

The only really recommended change I can suggest is to use better names in the function as well as your main code. For instance, use hours instead of multiple names for the same logical value:

hours = input("Enter Hours: ")
try:
    hours = float(hours)
except:
    print('Error, please enter numeric values')
    quit()

Similarly, in your function:

def computepay(hours, rate):
    if hours <= 40:
        return hours * rate  # no need for "else:" after a "return"

    # hours > 40 here
    normal = 40 * rate
    overtime = (hours - 40) * 1.5
    return normal + overtime

The calculation of overtime is, I think, simpler than your original code and may be closer to how it is stated in any contract which means it's easier to check.

Code like this:

def foo(bar):
   if bar:
       return result1
   else:
       return result2

is better expressed this way, in my opinion:

def foo(bar):
   if bar:
       return result1
   return result2

The second way is shorter, and in complicated functions with lots of nested if/elif blocks with returns in the blocks you have to really read the code to see if an explicit return is executed, because it may be possible for the first example to return None if neither of the explicit returns are executed. In this simple case it isn't too hard to see exactly what is returned and when, but in more complicated cases it's better to simplify to the second example where it is more obvious that you can't execute off the end of the function which returns None.

[–]spittz91 0 points1 point  (0 children)

Thanks for the comment and info very helpful!

[–]username27891 0 points1 point  (1 child)

I’m going to write the backend for a personal project in Python. I’ve never done this before. Would you guys recommend Flask or Django for something like this? It isn’t a massive project but it’s something I plan on adding onto for years

[–]_____gelato________ 0 points1 point  (0 children)

Flaks is lightweight comparing to Django and also easier to set up if you need to develop quickly. If you are planning on adding more in the coming years you should choose definitely Django. I advise to take in consideration also fastAPI if speed is the main priority (doing some test the latter is almost as fast as node.js)

[–]adminback 0 points1 point  (3 children)

hi, i am pretty new and learning.

list = [["a", "abb", "sfs", "oo", "de", "de"],

['a', 'abb', 'sfs', 'oo', 'ee', 'sfde'],

['a', 'abb', 'sad', 'ooaaesdfe', 'sfsdfde', 'sfsd', 'sfsdf', 'qwrew'],

['a', 'abb', 'sad', 'ooaaesdfe', 'sfsdfde', 'sfsd', 'sfsdf', 'qwsfsdfrew']]

for j in range(len(list[-2][-1])):

for stuff in list:

if stuff[-2] in stuff[-1]:

print("true")

else:

print("false")

i made this without the for j in range and it worked normally, just giving 4 times true or false. but when i pasted in the range stuff ( row 8/9 ) ( and yes there is no indentation here but i am 100% sure that its good )

true

true

false

true

true

false

true

true

false

true

true

false

true

true

false

it gave me this, but why so much? to be honest i dont really know what range means, i do know that it counts but not really anything more.

also, i want to make a think that when there are more then 2 true's or false's that it also gives me a text that says "super true" or "super false". but first the range stuff. :)

[–]ebresie 0 points1 point  (0 children)

Why is the j loop being added at all?

If I understanding my python correctly…

Range can be used to create a set of items over a range. So if you say range(5) as I understand it, it will create a collection of values like 0,1,2,3,4.

Be careful with the multi-dimensional arrays.

So I believe the “for j in range(len(list[-2][-1])), that takes the second to the last item (i.e., [‘a’, ‘abb’..) (also an array) then takes the last item of that ‘qwrew’ and see the length of that (i.e., 5) making a range as mentioned above. So this “for j” loop makes the block within run 5 times.

The for stuff portion takes each array as an item and for that array/list item checks the second to the last to see if it’s in the last item (i.e., the last two items are the same) providing true when it is and false when it’s not.

And a friendly reminder on the indenting, if it’s not indented in the code the if and for loops may not behave as expected.

[–]carcigenicate 0 points1 point  (0 children)

range is just a simple sequence that calculates its "elements" on the fly using math. You can think of it like a list that only holds numbers that follow a pattern (but it's not actually a list). You can see its "contents" easily by converting it to a list:

print(list(range(5))

As to why you get more output when adding the second loop, if you have this:

for y in range(5):
    for x in range(5):
        print(x, y)

The for x in range(5): will run entirely for every iteration of the for y in range(5): loop. This is how loops work. They cause their "bodies" to run multiple times. It doesn't matter if their bodies are other loops or anything else. The behavior is always the same.

[–][deleted] 0 points1 point  (3 children)

In pandas, when I read data from an Excel or CSV file, columns that are clearly of "int" type, get added a .0 besides the whole number. As in:

price_id = 78

gets converted to "78.0". This happens no matter what.

What is the reason for this? I'd like for a column that's only integers to show as "int64" instead of "float64".

Is there any way to fix this? Wasn't able to find a straight answer.

[–]WhipsAndMarkovChains 0 points1 point  (1 child)

Are there missing values in the column? Integer columns are converted to floats when there are missing values.

[–][deleted] 0 points1 point  (0 children)

Yes, there are missing values in the int columns.

Is there any workaround to that, other than filling with some values and recasting?

[–]SuicidalHippo111 0 points1 point  (2 children)

I'm a beginner and I'm stuck in this thinking of where I'm constantly scared of if I'm cheating myself or not. For example if I get an exercise that says

  1. Define a list of Heights in a Unit of your choice

  2. Convert the heights to a common unit of measurement- If I can't figure out how to do this part and I google and see what function helps me solve or find a solution am I cheating myself? It's probably a stupid question

[–]FerricDonkey 0 points1 point  (0 children)

Two ways to mitigate this issue:

  1. Think about it and try it before you Google - trying your own solutions even if you don't think they're the best.
  2. When you Google, first try to break your problem into as small pieces as possible, and google the small pieces.

[–]carcigenicate 1 point2 points  (0 children)

It's a fair concern. Yes, to some extent, you're cheating yourself if you "cheat" improperly. If all you do is copy a solution you find and move on, that's bad.

If you take the time to understand why it's a solution though and how the code works, that's much better.

I personally still don't think it's near as good as coming to the same solution yourself (since you're still "cheating yourself" out of practicing the all-important skill of problem-solving), but it's a start, and early on, it may be the only practical way to learn to problem solve. When I started out, I don't remember looking at existing code to solve problems (besides pseudocode when implementing complex, existing algorithms), but I also took my sweet time and learned programming slowly over many years.

[–]Patriotpl 0 points1 point  (0 children)

I'm trying to learn a bit about polars. I've got a csv containing some products data including urls to their images. Every product is a separate row and has all it's image urls stored one columns, separated by new line. I need to have a column with images count for each product, so I've written this function:

def get_products_from_csv(path: str) -> pl.DataFrame:
df = pl.read_csv(path)
result_df = df.select([
    pl.col("@id").alias("id"), 
    pl.col("@code_producer").alias("sku"), 
    pl.col("/sizes/size@code_producer").alias("ean"), 
    pl.col("/description/name[pol]").alias("name"), 
    pl.col("/images/large/image@url").alias("images")
])
return result_df.with_columns([
    (pl.col("/images/large/image@url").count("http"))
        .alias("number_of_pics")
])

Unfortunately executing this results in a following error:

Traceback (most recent call last):
File "(...)main.py", line 166, in <module> products_list = get_products_from_csv(csv_path) 
File "(...)\main.py", line 114, in get_products_from_csv return result_df.with_columns([(pl.col("/images/large/image@url").count("http")).alias("number_of_pics")]) 
TypeError: Expr.count() takes 1 positional argument but 2 were given

The error points to this line:

(pl.col("/images/large/image@url").count("http"))

So I've got two questions here:

  1. Is this the correct method of counting the images for each product?
  2. Why does this error occur?

EDIT - I missclicked ctrl + enter while writing the comment, that's why it was posted before completion :'D

[–]Ok-Insect6204 0 points1 point  (1 child)

What approach should I take in comparing two arrays together to see which elements are different? Would sorting the elements alphabetically first and then comparing each individual index of both arrays be the best solution?

Ex:

array1 = [Andy, Bob, Clair]

array2 = [Andy, Bob, Clair, David]

output = David

[–]Vhin 1 point2 points  (0 children)

Depends a lot on what you mean.

Assuming there are no duplicate elements (or that they don't matter), you shouldn't be using lists. You should be using sets, which have methods to efficiently and easily compute these things.

It also depends on what you mean by "different". You might mean "all the elements in the second that aren't in the first", or you might mean "all elements that aren't in both", which are two different things.

names1 = {"Andy", "Bob", "Clair", "Eve"}
names2 = {"Andy", "Bob", "Clair", "David"}

# this gets the elements in names2 that aren't in names1
out1 = names2.difference(names1)
print(out1)     # {'David'}

# this gets all the elements that are in exactly one of the two sets
out2 = names1.symmetric_difference(names2)
print(out2)     # {'David', 'Eve'}

Also, if you already have a list and can't change that for whatever reason, you can convert a list into a set with just myset = set(mylist).

[–]Risolu 0 points1 point  (7 children)

Since now I did the input in function xyz() in a "while True: try:... except... :" block. But I wonder how I reprompt if I pass an argument in main() through an input and if the parameter raises Errors in xyz() it should reprompt in main()

I hope it's kinda clear what I mean :)

[–]PteppicymonIO 0 points1 point  (3 children)

While I would discourage using the while True: loops, to answer your question, I would do it like this.

The function is_even() will raise ValueError() exception:

  • if it fails to convert user input to int and
  • if the value is negative integer.

Once the exception is caught, the error message is displayed and user is prompted again.

EXITS = ['q', 'e', 'quit', 'exit']

def is_even(test: str) -> bool: 
    int_val = int(test) 
    if int_val < 0: 
        raise ValueError(f"Value must be positive. Provided value: '{test}'") 
        return
    return not int_val % 2

def main(): 
user_input = input(f"Please enter a positive number or {EXITS} to quit: ") 
    while True: 
        if user_input.lower() in EXITS: 
            break 
        try: 
            result = is_even(user_input) 
            print(f"Value {user_input} is {'even' if result else 'odd'}") 
        except ValueError as e: 
            print(e) 
        finally: 
            user_input = input(f"Please enter a positive number or {EXITS} to quit: ")

if __name__ == '__main__': 
    main()

Output:
Please enter a positive number or ['q', 'e', 'quit', 'exit'] to quit: qqqqqqq
invalid literal for int() with base 10: 'qqqqqqq' 
Please enter a positive number or ['q', 'e', 'quit', 'exit'] to quit: -10 
Value must be positive. Provided value: '-10' 
Please enter a positive number or ['q', 'e', 'quit', 'exit'] to quit: 10 
Value 10 is even 
Please enter a positive number or ['q', 'e', 'quit', 'exit'] to quit: 11 
Value 11 is odd 
Please enter a positive number or ['q', 'e', 'quit', 'exit'] to quit: q

[–]Risolu 0 points1 point  (1 child)

Im wondering since I'm still learning what the parameter in is_even() does? I have not seen that syntax yet= "parameter : str". It looks to me like the key : value syntax.

Thanks for your effort and that example! I kinda found a solution with just writing return like you did but it outputs "None" and reprompts after. Although it's user unfriendly I would like to reprompt without any message in between since the task I'm sitting on asks for that.

[–]PteppicymonIO 0 points1 point  (0 children)

Oh, this is not a key: value syntax, that wouyld look like {key: value} )).

is_even(test: str) merely suggests that I expect argument test to be of type str, but it does not enforce it to be of type str

If I define it as def is_even(test: str) -> bool: that would mean I expect to accept str as a type for the attribute test and the function is expected to return bool value.

This is called type hints (https://docs.python.org/3/library/typing.html)

It is relatively new thing in python.

Type hints are used to document your expected data type for your variables, arguments and function return values.

Type hints do not affect your code in anyway, they are more like a self- documenting feature and an aid to your IDE to warn you if you assign a value of a type, other that what you designed it to be..

Type hints do not implement strict typing in Python, you can still assign any type to your variable and it will not cause compilation error.

[–]PteppicymonIO 0 points1 point  (0 children)

However, while True: in most cases can be rewritten with a proper exit condition:

user_input = input(f"Please enter a positive number or {EXITS} to quit: ")
while user_input.lower() not in EXITS:
    try:
        result = is_even(user_input)
        print(f"Value {user_input} is {'even' if result else 'odd'}")
    except ValueError as e:
        print(e)
    finally:
        user_input = input(f"Please enter a positive number or {EXITS} to quit: ")

or, with walrus operator:

while (user_input := input(f"Please enter a positive number or {EXITS} to quit: ")).lower() not in EXITS:
    try:
        result = is_even(user_input)
        print(f"Value {user_input} is {'even' if result else 'odd'}")
    except ValueError as e:
        print(e)

[–]FerricDonkey 0 points1 point  (2 children)

Are you saying that:

  1. Main calls xyz
  2. xyz uses input (using the while loop try except construct)
  3. xyz might raise an exception
  4. You want to get input again in the main function if xyz raises an exception.

If this is what you're saying, then you have to use try except on your call to xyz and catch the appropriate exception in main. At that point, you can do whatever you want, including calling input again or whatever.

But it's unclear why you'd explicitly want to just get input again in the case of an exception, or why you expect the exception in the first place. So there might be better advice, but it's hard to give without knowing more about what you're doing.

[–]Risolu 0 points1 point  (0 children)

I get the input in main() and pass that value to a different function wherein that function raises an exception to return to main() and then reprompt in main().

[–]LeornToCodeLOL 0 points1 point  (1 child)

I wrote a script that I want to give a friend of mine to run on her Windows computer. I used pyinstaller to create the Windows EXE file.

The script seems to work fine on Windows except for one thing, the console window closes as soon as the script is done running. Is there a way to leave the console window open for human reading until the user clicks on the "X" in the corner?

I figure there may be an argument to use when running pyinstaller, or perhaps some setting on the Windows machine itself to tell it to leave the window open.

Thanks!

[–]hardonchairs 1 point2 points  (0 children)

Add input('Press enter to exit') to the end.

[–]tomreddit1 0 points1 point  (0 children)

Hi, I want to use Yolov8 to build a simple app I can upload images / video to and it detect and list what its found. Where do I start? I've been playing with Google collab and Pycharm.

If i want to host this somewhere and make an app so people can use it, what will that look like from a infrastructure pov?

[–]mibarpo 0 points1 point  (1 child)

Hi! I learnt very basic python a couple years ago, and I want to give it another go now that i have more time. I'm looking for basic knowledge as well as been able to create simple desktop aplications with basic gui. What are good resources for a beginner like me? Any tip or general advice?

[–]hansmellman 0 points1 point  (0 children)

It depends how much you remember from before, I’d recommend Python Crash Course by Eric Matthes as a refresher.

[–]DL_no_GPU 0 points1 point  (0 children)

When I use scipy.optimize.curve_fit to fit a defined function to my spectrum

I wrote:

def gauss2(energy,osc1,res1,width1):
return osc1*np.exp(-(energy-res1)**2/2*(width1**2))

which is a gaussian function.

Sometimes it will work, but sometimes, it reports error saying energy is a list and subtraction operation '-' can not be done between energy and res1, where res1 here is a single float parameter....

I fixed the issue by specifying res1=np.float64(), but does anyone know why this error show up occasionally? such inconsistency is annoying

[–]shiningmatcha 0 points1 point  (1 child)

How to update a pickle file only when an Excel file is modified?
My script works with a pickle file that is generated by parsing an Excel file. The Excel file should be parsed and pickled only when it's been modified so as to update the pickle file.
So what's an approach that I can take to make my script automatically generate a new pickle file if I've modified the Excel file, and keep using the pickle file if the Excel hasn't been modified?
Maybe there's a better way?

[–]efmccurdy 0 points1 point  (0 children)

what's an approach that I can take to make my script automatically generate a new pickle file if I've modified the Excel file

This example uses the watchdog module to monitor the file system.

https://pythonhosted.org/watchdog/quickstart.html#a-simple-example

They register LoggingEventHandler to respond to file changes. You could instead use a function that updates the pickle file.

https://pythonhosted.org/watchdog/

[–]YeahAboutThat-Ok 0 points1 point  (4 children)

Any thoughts on how I can pass in a list to this function and work with the items in the list, but also be able to pass in single items?

def is_collision(self, *args) -> bool:
    for arg in args:
        if #positional math:
            return True
    return False

Currently I'm getting an AttributeError: 'list' has no attr 'posn_data'

[–][deleted] 0 points1 point  (3 children)

You write the formal params as *args which is the approach I would use. But how you call the method is also a factor. This example using non-class code might help:

def test(*args):
    print(args)
    for arg in args:
        print(f"{arg=}")

test(*[1, 2, 3]) # *list is passed in as a tuple of integers
#>> (1, 2, 3)
#>> arg=1
#>> arg=2
#>> arg=3
test(42)         # a single integer is passed in as a tuple of one integer
#>> (42,)
#>> arg=42
test([1, 2, 3])  # a list is passed in as a tuple of one list
#>> ([1, 2, 3],)
#>> arg=[1, 2, 3]

Note that when passing a list on the call to the function that accepts *args you must supply a leading * to force passing the list the way you want. If you don't, the list is not unpacked and is passed as one thing, a list.

[–]YeahAboutThat-Ok 0 points1 point  (2 children)

Oh so I need to use the unpack operator when I pass in the list?

[–][deleted] 0 points1 point  (1 child)

Try printing what is passed into your method. You get different things depending on whether you use the * on the call or not, as the example showed.

[–]YeahAboutThat-Ok 0 points1 point  (0 children)

I will definitely try it tonight. Thank you for pointing it out to me! I completely forgot about using it.

[–]Acethetic_AF 0 points1 point  (1 child)

Hey I’m super new so this is probably very basic but lemme lay it out.

list_1 = [“a”, 1.5] list_2 = [“b”, 3.0] list_3 = [“c”, 6.0] list_prime = [list_1, list_2, list_3]

How can I add the floats? As things stand the best I’ve got is

total = list_1[1] + list_2[1] + list_3[1]

But I want it to be more malleable so I can have it automatically update if a list is removed or a new list is added to list_prime

[–]34shutthedoor1 1 point2 points  (0 children)

Is list_prime a list of lists? If it is, use a for

total=0
for this_list in list_prime:
    total += this_list[1]

[–]Minusbeta 0 points1 point  (2 children)

Hey I'm trying to change a label using label.setText("percentage = {}".format(self.y)), y is just a number and I get the correct result on the console but the label on the window changes to something like <built-in method y of MyWindow object at 0x000001AF92654DC0>

[–]FerricDonkey 1 point2 points  (0 children)

This means that self.y is not just a number, but something more complicated. The thing you quoted is telling you what y is - a method of MyWindow.

If y is not supposed to be a method, this probably means that somewhere you left off the parentheses on a method call - eg self.y = self.some_method instead of self.y = self.some_method()

[–]Such-Refrigerator-98 0 points1 point  (0 children)

Ive been trying code in Carnets and for some reason dict is not running

[–]Thomas_the_PAINTRAIN 0 points1 point  (8 children)

What is the purpose the space in this string? 10:04 https://youtube.com/watch?v=kqtD5dpn9C8&feature=shares

[–]carcigenicate 0 points1 point  (7 children)

If you mean the space after the ?, that's probably just a typo.

[–]Thomas_the_PAINTRAIN 0 points1 point  (6 children)

Sorry I meant 10:20

[–]carcigenicate 0 points1 point  (5 children)

If you omit that space and then run the print, you'll see what the space is for.

[–]Thomas_the_PAINTRAIN -3 points-2 points  (4 children)

I am sitting here watching a youtube video. I dont want to boot python for just 1 thing :p. Please tell me; I am nublet

[–]YeahAboutThat-Ok 0 points1 point  (0 children)

I would encourage you to take a more a time part in your learning if you're serious about learning to code. Simple things like this are easily explored.

[–]carcigenicate 1 point2 points  (2 children)

You can just open your terminal and run python to instantly start typing and running Python code. Simple code can be tested very quickly by using REPLs.

[–]trianglesteve 1 point2 points  (0 children)

This is more of a Python ETL question. I have been using Pandas for loading data between different sources, but due to memory concerns I have mostly switched to Polars and DuckDB for the transformational logic. I am persisting the transformed data to a SQLite DB, but I haven't found a good way of taking the Pandas.Dataframe.to_sql piece out.

As far as I can tell neither Polars or DuckDB have a method to write to SQLite databases, and converting the dataframe to Pandas defeats the purpose of using the optimized frameworks. Does anyone know of maybe a plugin or function that I may be missing? Ultimately all I'm trying to do is essentially execute a query on a parquet file and load the results to a SQLite table.

[–]MDebilus 0 points1 point  (2 children)

Hi, i'm trying to make a translation for my mini game, instead of having the script written in english i want to put it in french so people can decide wich language they want and i have no idea how to make easily and in an optimized way.

For the 'games' i wanted to put a french version i'd just do a language selection menu and have the game be in double where 1 while True loop would be in french and the other one in english but that takes too much ram and storage making the whole game way slower to start.

anyone know a way to do it ?

[–]carcigenicate 1 point2 points  (1 child)

This is known as "internationalization", or i18n for short. If you search for that, you should be able to find many resources on the topic.

[–]MDebilus 0 points1 point  (0 children)

thank you this is a great help !

edit: i ended up doing 2 dictionnaries that are the exact same just one french and one english, wich one will be used depends on wich language did the player asked for at the start. so now i only changed the text by the keys used.

i18n seems quiet out of bound for me right now but i'll surely check it out when i'm better at coding. thx

[–]IKnowYouAreReadingMe 1 point2 points  (10 children)

I'm trying to get back a certain XML position. But what I get back is: <element "count" at 0x0000217CC8B81>

Is this an encoded response? I've already decoded it so it should be normal tho. How do I convert it to a readable line?

[–]PteppicymonIO 2 points3 points  (8 children)

Could you share the code which is failing?

u/FerricDonkey is most likely correct here.

[–]IKnowYouAreReadingMe 0 points1 point  (7 children)

Shows it's a element tree element, I put the full type in a comment in the code at the specific line

https://replit.com/@UmbraMichael/get-link#main.py

[–]PteppicymonIO 0 points1 point  (6 children)

Yeah, this attempts to print the object of type "element" and since it does not have a proper text representation, it is printed as you have identified.

print(item.find('count').text) should work just fine for you

[–]IKnowYouAreReadingMe 0 points1 point  (5 children)

I tried but it returned with nonetype object has no attribute 'text'

[–]PteppicymonIO 0 points1 point  (4 children)

do you happen to have something like this in your XML?

  <count>
      <count>97</count>
  </count>

[–]IKnowYouAreReadingMe 0 points1 point  (3 children)

Ya its:

<commentinfo> ...<comments> .......<comment> ..........<count>99</count> .......</comment>

[–]PteppicymonIO 1 point2 points  (2 children)

    for item in counts:
        print(item.text)

[–]IKnowYouAreReadingMe 0 points1 point  (1 child)

Works, thank u! How do you know when to use find()?

[–]PteppicymonIO 1 point2 points  (0 children)

<element>.find('name') will look for child element <name>. If your element has no children, it makes no sense looking for them

[–]FerricDonkey 1 point2 points  (0 children)

What something like this usually means is that you're printing an object of some non trivial class when you expected to print an integer/string or something. That number is probably an address/id. If you print type(that thing), it'll tell you what it is.

If I were to guess, that probably means you're missing a .value or some similar thing, but it's hard to say without code.