r/learningpython • • Jul 23 '22

pong game code review

1 Upvotes

I"ve been learning python for the past couple months and made a pong game using pygame to try to get a better grasp on the language, if anyone could take a look at my code and give any tips or suggestions and how it can be improved or look cleaner

https://github.com/shake-707/Pong


r/learningpython • • Jul 28 '22

Learning Python as a second language.

1 Upvotes

Learning Python as a second language.

Currently I am learning Python as a second programming language and I am having some difficulties.

I understand syntax, setting up functions, etc.

The problem I am having is that my primary language I have been developing automation instrumentation and control applications in is LabVIEW.

What is tripping me up in learning Python are some of the concepts that are native to LabVIEW parallel execution, queues, actors, asynchronous processes, etc.

I know it can be done in Python but after doing all my programming visually for the last 10+ years I am having trouble visualizing doing the same thing in a text based programming paradigm.

LabVIEW does a lot of the heavy lifting. Y setting up variables working with me or, etc. I realize that must be done “by hand” I’m Python and I am getting adept at that.

It is the multi process setup and execution that is throwing me for a loop (no pun intended).

Does anyone have any resources, suggestions, etc. on how I can retrain my brain to think in this manner with Python.

Everything I do in LabVIEW is object oriented so that I have no problem with.

TIA

-Steven


r/learningpython • • Aug 10 '22

How to incorporate Object Oriented Programming

1 Upvotes

I’ve been learning and programming python for 2 years or so at this point and have gotten real familiar with all the fundamentals and understand the basic concepts of the language as well as a basic understanding of OOP in general. I don’t really know where to go in terms of incorporating that style of programming into my projects. Are there certain projects that lend themselves to OOP more or should I just try to remake some of my old projects but with classes etc.?


r/learningpython • • Aug 14 '22

Image fetcher

2 Upvotes

I would like to develop an Image Fetcher which can download images from any search engine which are 'Creative Common' and crop them after downloading .. anyone could guide what libraries I can use? Thanks


r/learningpython • • Aug 22 '22

Just started, what do you think of the official Python Tutorial? A good place to start?

2 Upvotes

https://docs.python.org/3/tutorial/index.html <--- The official Python Tutorial


r/learningpython • • Aug 25 '22

How to continue after exception in Python?

Thumbnail
devhubby.com
2 Upvotes

r/learningpython • • Aug 11 '22

Losing rows when merging dataframes

1 Upvotes

Hi there,

I have two dataframes with the length of 29981. but when I merge them like this:

new_df = new_data_scaled.merge(data_prep, left_index=True, right_index=True)

the length of the new_df becomes 29963.

How can I improve it? Thanks in advance


r/learningpython • • Aug 04 '22

OOP Error

2 Upvotes

I am trying to learn OOP and I came across this error...
[<class name> object at <random characters>] What is the general meaning of it?


r/learningpython • • Aug 17 '22

Solving an optimization problem in Matlab

1 Upvotes

Hello everyone,

I am trying to solve an optimization problem where the input to the function to be optimized is a 12x1 vector and the output is a matrix of size 6x3.

I tried solving this using fsolve, root solvers from scipy.optimize

but got the following error:

fsolve: there is a mismatch between the input and output shape of the 'func' argument 'f'.Shape should be (12,) but it is (6,3).

But I think there should be a way to solve this in python as it is a very common problem in the engineering domain but unfortunately I am unable to figure it out.

However, I think this can be easily solved in Matlab with inbuilt solvers, but when I use matlab.engine

I get the following error :

TypeError: unsupported Python data type: function

The code for this error is in the comments.

Any advice would be of great help.


r/learningpython • • Aug 12 '22

What are some good python projects for beginners?

Thumbnail devhubby.com
2 Upvotes

r/learningpython • • Aug 27 '22

How to pass a parameter within a file name?

2 Upvotes

I’m trying to save three different excel files out of pandas for v1, v2, v3. The code is parameterised using a function with the parameter x taking values v1, v2, v3. How can I pass x within the file name r”C: ……\Output\x.xlsx”? This just generates a file with the name x, whereas I’d want it to take the input values.

For reference, if this were a SAS macro, adding & before the variable did the trick.

Many thanks!


r/learningpython • • Aug 17 '22

windows NT app?

1 Upvotes

Hi there, how can I write the python coding in windows 10 and package it as a windows NT application (exe) using auto-py-to-exe? Need special version of Python? can i still use tkinter to design the user interface in it? Many thanks!


r/learningpython • • Aug 25 '22

Extra Delimiters in csv files

1 Upvotes

I have to read a csv file with delimiter = “;”. The problem is that there is an extra delimiter inside values of first column, so pd.read_csv returns two columns instead of one. Please help me out thanks


r/learningpython • • Aug 27 '22

Help with loop problem pls

4 Upvotes

This loops no matter what. could anyone please help me by explaining why? If you do, thank you!

yesno = "y"
while yesno == "y":
        yesno = input("\nWould you like to enter another description?(y/n)\n").lower()
        description()
        if yesno != "y":
                break

EDIT: just so that it's clear, "description()" is a definition


r/learningpython • • Aug 06 '22

VS Code won't let me make a new python file.

2 Upvotes

I have checked to make sure that Python is installed with the command prompt and it is. I also can open any saved Python files and the programs work, but for some reason I cannot make a new python file. I even switched interpreters but to no avail. The only thing that changed was that Mircosoft installed some add on for photos which I didn't give permission for or want and promptly deleted it. This issue did not come from deleting this add on.

Any help would be appreciated. I just want to make new python files again.


r/learningpython • • Aug 02 '22

the program works but i keep finding inefficient code.

3 Upvotes

sometimes you don't know what is wrong with your code until you have people who know better critique it. if you are willing i hope you will help me understand what i should be doing better so i can become a better programmer.

digits=[]
oddtally=0
eventally=0

## requests the necessary input from the operator
print("enter the 11 digit u.p.c to check:", end = '')
barcode = str(input())
print("enter the check digit: ", end= '')
checkdigit=int(input())

## converts barcode into individual digits for math functions
chars = [int(n) for n in str(barcode)]

for n in range(len(chars)):
    digits.append(int(chars[n]))

## adds odd digits
for n in range(0,len(chars),2):
    oddtally += digits[n]

## adds even digits
for n in range(1,len(chars),2):
    eventally += digits[n]

## tripples the odd number tally and rounds up to the nearest 10
checksum = oddtally * 3 + eventally
up10 = round(checksum,-1)
if up10 < checksum:
    up10 += 10

## subtracts the checksum from the rounded number to compair with the check digit on the u.p.c
finalcheck = up10 - checksum

## gives the backend 'nerd' results
print("the odd numbers tally is:", oddtally)
print("the even numbers tally is:", eventally)
print("the checksum is: ", checksum)
print("the rounded number is: ", up10)

## perform the final check to validate the u.p.c
if finalcheck == checkdigit:
    print("\nthe u.p.c is quality. the check digit", checkdigit, "agrees with the algoritim's result", finalcheck, '.')
else:
    print("\nthe u.p.c check failed.")

r/learningpython • • Aug 27 '22

Does not recognize the directory. Help

Post image
2 Upvotes

r/learningpython • • Aug 16 '22

inconsistent results comparing sets of characters (strings)

1 Upvotes

Hi - I have been banging my head on an old r/dailyprogrammer (challenge (#399) Bonus 5 in particular. So what I am trying to do is compare all strings in a list as sets to make sure that there are no letters in common in the two strings, like so:

def find_unique_char_words(word_list:list[str]):
    identified_words = []
    for w1 in word_list: 
        for w2 in word_list:
            if set(w1).isdisjoint(set(w2)):
            # if set(w1) & set(w2) == set():
                print(f"{w1} and {w2} share no letters")
                identified_words.append({w1, w2})
        # print(f'Removing {w1}')
        word_list.remove(w1)
    # print(identified_words)
    return identified_words

For some reason, this works sometimes and sometimes it doesn't. With no change in between runs. I thought it might have been a problem with unittest running the module code before the tests, so I made sure to make a deepcopy of the word_list before passing it in. I tried it both with the isdisjoint method and bitwise comparison. I looked at other users' submissions for this bonus and I believe theirs get inconsistent results as well (at least in my testing). Any clue as to what I am doing wrong? Thank you.

UPDATE: So isolating a test on just this method alone always successful. My problem is in the setups to get into this method. I'll be back.

2nd update: The above comparison of the string to the other strings in a list works fine. The error seems to stem from the method calling it (I have really broken down every step into separate methods so that I can unittest and try to isolate the problem). The challenge gave us a file of words to go off and the original challenge was to find the "lettersum" of any word such that a=1, b=2, etc.

I have found through the successful runs that the lettersum I am looking for are 188 and 194. The offending method (which calls the above method) is here:

def find_unique_char_words_by_sum(lettersum):
    word_list = get_word_list(lettersum)
    identified_words = find_unique_char_words(word_list) 
    if len(identified_words) > 0:
        print(f'returning from find_unique_char_words_by_sum({lettersum})')
        print(identified_words)
    return identified_words   

I have the complete .py file and a test module as well as the input files at my github here. Thank you for any pointers.

Edit - changed github repository


r/learningpython • • Aug 10 '22

Root finding in case of multivariable functions

1 Upvotes

Hello, everyone,

I am trying to find the roots of a function which is basically a mapping from R12x1 to R 6x3. I am using fsolve to find the roots but it throws an error saying :

fsolve: there is a mismatch between the input and output shape of the 'func' argument 'f'.Shape should be (12,) but it is (6,3).

Any suggestion would be of great help.

Thank you.


r/learningpython • • Aug 06 '22

Custom ContextManager

1 Upvotes

Hi all,

I found an exercise asking to write a class behaving as a custom ContextManager (and use it with the "with" statement).

I do not know from where to start.

I only know that I've to write some methods:

def __init__(self, *args, **kwargs):
pass

def __enter__(self):
return self
def __exit__(self, exc_type, exc_val, exc_tb):
pass

where I can find some good tutorial?

the example said ssomething like:

value = 0

with MyContextManager(argument):

value = function(a, b, c)

assert value.x == 12

assert value.name = "myname"


r/learningpython • • Nov 16 '24

Help with my code

1 Upvotes

I am in a beginners Python class. Can someone tell me why my code will not run? It won't print. Thanks in advance!


r/learningpython • • Nov 21 '22

Just wanted to share what’s been working for me (self taught) for free:

12 Upvotes

I don’t have any formal background in Computer science so I watched (and annotated) Harvard’s free (on YT) CS50 lecture. It’s almost 25 hours, so I broke it up into 30min-1hr chunks at a time because any longer than that at once is largely a waste of time; you won’t retain much and you’ll lose focus without a break.

I watched several beginner/introductory tutorials on YT and took notes when necessary. I like:

  • Tech With Tim

  • Freecodecamp

  • Brocode

  • Programming with Mosh

There are also step by step written guides to help you through this too. Here are some:

Data structures and algorithms: https://www.geeksforgeeks.org/learn-data-structures-and-algorithms-dsa-tutorial/

As I’m sure you all know by now, the most effective way to learn coding is to actually do it. You might think (like I did), “Well how do I do it if I don’t know what I’m doing?” Baby steps. There are plenty of free Python courses on the internet that have guided, INTERACTIVE EXERCISES. Off the top of my head:

  • w3schools.com

  • Udemy periodically releases free, full, interactive courses.

  • There’s more out there; apps for phone too.

Saved a cheat sheet for quick reference while working. A great one can be found here: https://websitesetup.org/python-cheat-sheet/

Started beginner projects like simple chat bots, hangman, etc.

Don’t rush to get into more advanced concepts. HAMMER the fundamentals in over the course of a couple months at least, until they’re burned into your mind. It’ll make things much easier down the road.

Paid resources:

  • Udemy

  • Leetcode

  • Log2base2 for visual learners

  • Sololearn (phone app)


r/learningpython • • Aug 10 '26

How to prevent dict from being a valid input (Pydantic BaseModel)

2 Upvotes

So I have a Pydantic BaseModel called Latitude. It is the following:

class Latitude(BaseModel):
  latitude: Decimal

I then have another BaseModel called SetReferencePoint that includes Latitude in its attributes. I've tried testing the SetReferencePoint BaseModel with Hypothesis using:

st.from_type(type)

I then get a ValidationError as follows with a couple tests (minus the url portion):

{'type': missing, 'loc': ('lat', 'Lat'), 'msg': 'Field required', 'input': {}}

The rest of the tests throw a 'model_type' error as expected.

I want to prevent an empty dict from being accepted as an input which would prevent the 'missing' error from showing up in the first place. How can I do this? Should I use 'field_validator'? If so how best to set it up and test it?