r/learningpython • • Nov 26 '20

Official/Recommended method for managing multiple versions of python and packages

1 Upvotes

Maybe it's me, I did just have some minor surgery today, but I'm lost of where to begin with multiple versions of python. I've read about and digested a bunch of info online but I'm curious what the official recommendations are or where to kind of begin.

I've been getting more serious into writing small applications in python and playing with some data science stuff but mostly, it's application stuff with tkinter and kivy. I've started running into some things needing different versions of libraries or different versions of python entirely.

Thanks in advance


r/learningpython • • Nov 18 '20

How do I create objects in pygame using classes?

1 Upvotes

I have an assignment for comp sci that says to

  1. Create a class for each shape

  2. Each item X,Y draws into the area it belongs. It's (X,Y) point cannot originate outside of the area BUT it can draw over the line.

  3. Each object has a [ def randomize(self): ] that will randomly redraw the shape within its area.

  4. run a menu in a 'while True' loop that will ask which item to redraw.

We have only briefly gone over classes at the beginning of the year so I am a bit lost in how to draw something from it. I understand that you have to create a new py file, but how do you call that in the main.py?

We are using Repl.it for the assignment.


r/learningpython • • Nov 05 '20

[Python + OpenCV + Buildozer] Camera won't launch due to "(-2:Unspecified error)"

1 Upvotes

I'm testing app which uses OpenCV 4.4 on Android and in the moment when the app supposed to launch the camera the camera won't launch and in logs I get:

cv2.error: OpenCV(4.0.1) /home/mark/frontend_android/.buildozer/android/platform/build-armeabi-v7a/build/other_builds/opencv/armeabi-v7a__ndk_target_21/opencv/modules/highgui/src/window.cpp:610: error: (-2:Unspecified error) The function is not implemented. Rebuild the library with Windows, GTK+ 2.x or Cocoa support. If you are on Ubuntu or Debian, install libgtk2.0-dev and pkg-config, then re-run cmake or configure script in function 'cvNamedWindow' 

I installed libgtk2.0-dev and pkg-config was already present.

I'm using pip packages:

opencv-python 4.4 
opencv-contrib-python 4.4 

P4A recipes I'm using:

opencv 
opencv_extras

I've found this on the web but I'm not sure if it's relevant to my problem:

MacOS and Linux wheels have currently some limitations:

video related functionality is not supported (not compiled with FFmpeg)

for example cv2.imshow()

will not work (not compiled with GTK+ 2.x or Carbon support)

I'm not using imshow() attribute but I do use VideoCapture(0).

Any help much appreciated.


r/learningpython • • Oct 28 '20

How do I find the inserted elements in two list ?

1 Upvotes

I wrote following code to check where elements were inserted in a list:

(list a and list b always have the same length)

a=[1,2,3,4,5,6,7,8,9,10,11] 
b=[1,2,3,3,3,4,5,6,6,6,6,7] 

def getindexinserted(lista1,listb1):
     index=None 
     for i in range(len(a)):
         if lista1[i]!=listb1[i]:
             index=i
             break
     return index 
def getinserted(lista,listb):
     returnliste=[]
     start=0
     for l in range(2):
         if getindexinserted(lista,listb)!=None:                                            
            returnliste.append(getindexinserted(lista,listb)+start)             
        start=getindexinserted(lista,listb)+1 
      if len(returnliste)>0:
         for i in range(len(returnliste)):                                                         
            numberofinsertedelements=1
            for j in range(returnliste[i],len(lista)):
                 if lista[returnliste[i]]!=listb[j+1]:                                 
                    numberofinsertedelements=numberofinsertedelements+1 
                else:
                     break
            if i==0:
                 returnliste[i]=[returnliste[i],numberofinsertedelements]             
            else:
                 returnliste[i]=[returnliste[i],numberofinsertedelements-            returnliste[i-1][1]]         
    return returnliste 
getinserted(a,b)

Output:[[3, 2], [7, 3]],

because two 3s were inserted starting at index 3 and three 6s were inserted starting at index 7, relative to the inserted list.

Is there a better way to find the inserted elements?


r/learningpython • • Sep 22 '20

Toggle a loop

1 Upvotes

https://prnt.sc/ulwzvo this is my code I want to make it so if i press right control it stops but if i press it again it starts the loop


r/learningpython • • Sep 21 '20

Learning Python (Beginner)- Classes

1 Upvotes

Hi guys,

I'm still learning about the Python programming language and started since July 2020. The screen I attached where I stuck for days. I was trying to rectify errors but it didn't work and cannot able to run as the output error resulted to this:

Then I tried imitating the original code from the book and I think it's fixed(--init-- not -init-). But I dunno if the output below is right? Or I feel like it's missing a lot of code. This is the output:

I was following the book instructions and its an outdated book so the languages might change that's why it didn't work. This is the code I was trying to follow:

I'm using Pycharm. Please reply if you have any suggestion that might gonna solve this problem. Thank you very much in advance guys :)


r/learningpython • • Sep 20 '20

Getting results in tuple that I do not want. Can someone help with this?

1 Upvotes

I am working on a BFS for a larger program assignment. This is part of my test to see if my search is working and I keep getting a node that isn't supposed to be being added (0,'l').

The purpose of this is to search down and find the possible routes the program can take. It will start at index[0] and move the number of spaces of the number at that node(IE if number is a 2 it moves 2 spaces in the determined direction). However, the input is a in string form(2322443122G22124131321422), the reality is that the computer should see it as a 5x5 grid:

2 3 2 2 4

4 3 1 2 2

G 2 2 1 2

4 1 3 13

2 1 4 2 2

Rules for movement: If in column 1 it cannot move "left", column 5 cannot move "right". Top row cannot move up, bottom row cannot move down. Stop when "G" is found.

There are a few other issues with the code, but I am trying to focus on things one at a time and this one is quite annoying lol

Here is my code:

pond = "2322443122G22124131321422"
i=0 #counter
pos = int(pond[i])
routes = []
new_pos = 0
##direction = ""

while new_pos not in routes:
    pos = int(pond[i])

    # moves to right 
    new_pos = i+pos
    if i//5 == new_pos // 5:
##        new_pos = i+pos
    ##    i+=new_pos
        routes.append((new_pos,"r"))
##        routes.append((new_pos))
##        routes.append(("r"))
        routes.pop
    else:
        pass
    #moves to left
    new_pos = i-pos
    if new_pos >= 0 and i//5 == new_pos // 5:
##        new_pos = i-pos
        
    #    i+=new_pos
        routes.append((new_pos,"l"))
        #outes.append(("l"))
    else:
        pass
    if new_pos == "G":
        pass  
    #move down
    new_pos = i + pos*5
    if i <= 24:
    #    i+=new_pos
        routes.append((new_pos,"d"))
    ##
    ###move up - commented out bc testing of down,left,right is incomplete
    ##new_pos = i - pos*5
    ##if i >= 0:
    ##    routes.append((new_pos,"u"))
##    if new_pos == "G":
        pass
    i+=pos

    
    #print(i)
    #print(new_pos)
    print(routes)

r/learningpython • • Sep 14 '20

Why isn't this code working properly?

1 Upvotes

https://github.com/anarchypigeon/Wolfbane/commit/8f8c6eb96e4c10d8bfd4812ff8d237edffb02c86

^^ that's the code. It's basically supposed to be an RNG timer.

It uses RNG to count to 3, with each new number warning the player that it's closer to 3.

The intended purpose is to have it randomly warn the player that the monster chasing them is getting closer to them, so they need to hurry up and complete their task before they die. This function is supposed to run in the background while the player interacts with the main function.

The issue:

The main issue I've had with the code is that it prints out the warning messages every single iteration of the while loop. I don't want it to do that. I want it to print out each warning message one single time, and then wait until the data value of 'ww_sightings' changes before printing the next warning message.

I've tried putting each warning sign in it's own while loop, didn't work. I've tried keeping the sleep timer in it's own while loop so it wouldn't interact with the other functions, didn't work. I'm very new to coding (like, started learning python 7 days ago new) and I would LOVE for someone to read my code and tell me how stupid I am and how obvious the solution is and how I should have seen it. Please and thank you.

So, the intended functionality of the code is this: every 3 seconds, I want the code to generate a random number, either 1, 2, or 3. Whenever that number is 2, it prints out the first warning message and adds 1 to the total number of sightings. Next time the number is 2, it prints out the SECOND warning message, and adds 1 to the total sightings again. The third time it's the number 2, it prints out the final "You died" message and quits the program.

For some reason I cannot get it to do that.

Edit: I'm sure that my code is extremely unorganized and my explanation probably didn't do it justice so if you guys have any questions about what anything is for or what it's supposed to do, please ask and I'll answer promptly.


r/learningpython • • Sep 04 '20

Trying to get a list of tuples from a list of dictionaries, some values separated with commas and single quotes and some without

1 Upvotes

I have a list of dictionaries, each dictionary contains:

  • First name

  • Middle name

  • Last name

  • Title

  • Address

  • Email address

  • Loyalty program For one client. Some of this information may be missing

segment = [{'first-name': 'Elsa', 'last-name': 'Frost', 'title': 'Princess', 'address': '33 Castle Street, London', 'loyalty-program': 'Gold'}, {'first-name': 'Anna', 'last-name': 'Frost', 'title': 'Princess', 'loyalty-program': 'Platinum'}, {'first-name': 'Harry', 'middle-name': 'Harold', 'last-name': 'Hare', 'title': 'Mr', 'email-address': '[email protected]', 'loyalty-program': 'Silver'}]

For clients who have a physical address, I need to extract a list of tuples. Each tuple represents one client and contains their title, first name, middle name, and last name in that order if defined, and the mailing address.

My code appears to be working.

However, within each tuple, there needs to be single quotation marks around the whole and not individual parts of a clients name. There also needs to be quotation marks around the address. A comma needs to separate the address and the full name.

('Princess Elsa Frost', '33 Castle Street, London')

My code is returning the right information, but the elements of a patients name are separated by commas and single quotation marks

def process_clients(segment): 
#Creating a list to contain tuples with client full name and mailing address.      
updated = [] 
#Interacting through each dictionary, which represents each client 
for dic in segment:         
    newclient=[] 
#Adding clients with a mailing address 
    try:             
        add = dic["address"] 
    except: 
        continue 
    #Adding, in order, the "title", "first-name", "middle-name", "last-name" and "address" of each client 
    for data in ["title", "first-name", "middle-name", "last-name", "address"]: 
        try:                 
            value = dic[data]                 
            newclient.append(value) 
     #If "title", "first-name", "middle-name" or "last-name" is not present in a clients data, no action is taken 
        except: 
            pass 
     #Additing the tuples with extracted client data to the created list                                          updated.append(tuple(newclient)) 
return updated   

process_clients(segment)

r/learningpython • • Jul 30 '20

live pitch shift/ voice emulator?

1 Upvotes

I have no idea where to start with this project. I want to make a program that changes my voice live but i don't have any idea on how to do that. Any ideas?


r/learningpython • • Jul 20 '20

In Visual Studio Code, how do you get Terminal to stop displaying the file path you're in when running the code?

1 Upvotes

r/learningpython • • May 01 '20

phone app checker

1 Upvotes

Hi all,

I would like to create python program which will check which app is installed on my phone and when ıs installed ... etc .is it possible to do it with python? Is there any document I can refer to


r/learningpython • • Apr 05 '20

Question about looping

1 Upvotes

Hello, I'm trying to scrape some stuff from a website using python. The i, ranges from 0 to 1500. Any example of how I can write a loop for it? I would highly appreciate it.

root[i]['ACTION_TYPE']


r/learningpython • • Mar 14 '20

Methods for calculating best fit for N preferences, weighted in importance

Thumbnail self.askmath
1 Upvotes

r/learningpython • • Feb 10 '20

New at coding

1 Upvotes

I’m basically new at coding and wanted to know good resources to start getting more into python. I’ve done basic coding on Java, so I understand basics of coding but never actually written my own code. I’ve done puzzles where I look over documentation and finish the code but never actually written my own code. Also I’m pretty interested in data science and analytics. Any help is appreciated, thank you!


r/learningpython • • Jan 28 '20

Is there a list anywhere or community comments on best VSC Extensions to install for beginners with Python 3.x?

1 Upvotes

I am using Visual Studio Code, and wondering if there are any especially helpful extensions for newbies to download for Python to assist learning, or if using it basically "raw" from extensions is best?

I did install couple recommended extensions that plays the script within VSC, and another for indentation, however I'm wondering if there are any that people would recommend to assist with syntax or anything that might help the learning process?

Thanks!


r/learningpython • • Jan 22 '20

Tried to downgrade from Python 3.8 and installed 2.7, but command prompt "python -V" not showing any python program is detected? And I can bring 2.7 up in IDLE?

1 Upvotes

I have a screen snip here showing what I am talking about:

https://linx.li/hjte3hlu.png

I completely uninstalled 3.8 and its launcher, visual studio, reinstalled both, and despite launching this in IDLE and its obviously there working the PC won't recognize it even after a reboot.

This is so frustrating, what is happening here?

Any input please.


r/learningpython • • Dec 14 '19

HW Issues with creating classes

1 Upvotes

I wanted to know, how do you produce an error message to the user if they did not enter information, within a class.


r/learningpython • • Nov 25 '19

Poker game help

1 Upvotes

Hi there!

I'm looking to create a poker game using python.

What's a good place to start?


r/learningpython • • Nov 03 '19

Question about decorator

1 Upvotes

Having a hard time understanding decorator. Why use a def inside a def for the decorator?

What's the difference between

def dec_foo(func):
    print ("Need help!")
    func()

def foo():
    print("What is a decorator?")

dec_foo(foo)

and

def dec_foo(func):
    def wrapper():
        print ("Need help!")
        return func()
    return wrapper

def foo():
    print("What is a decorator?")

foo = dec_foo(foo)
foo()

?

Thanks is advanced.


r/learningpython • • Oct 25 '19

How can I split artist name and song name from one variable into individual variables?

1 Upvotes

I have a list of variables that are titled like “Artist - SongName” and I wanna split artist name and song name in their own individual variables. How can I do this?


r/learningpython • • Oct 04 '19

Passing a path to a function

1 Upvotes

Hi

Trying to pass a path to a function, so that python searches and replaces a string in all files in that directory:

#my_folder is in the same location as my python file  
from pathlib import Path  
    def set_tags(trans_path, text_to_replace_with):
            for currentFile in trans_path.iterdir():
                tranFile = open(currentFile, "wt")
                tranData = tranFile.read()
                tranData = tranData.replace('yyy', text_to_replace_with)
                tranFile.write(tranData)
                tranFile.close()
        
        
       
     set_tags(str("my_folder", 'xxx')

Fails with: AttributeError: 'str' object has no attribute 'iterdir'

Any help is appreaciated.


r/learningpython • • Aug 07 '19

How to use value of one function in another?

1 Upvotes

Hi,

complete Newbie here. I'm just trying to create a simple calculator for Pivot Points(Trading thing) and please someone help how can I use value of one function in another?

Here is what I'm doing:

# Pivot points calculator

H = 3

L = 2

C = 2.5

def pivot(H, L, C):

print("PIVOT POINT =", result)

return (H + L + C) / 3

result = pivot(H, L, C)

def r1(pivot, L):

print(result2)

return (pivot * 2) - L

result2 = r1(pivot, L)

How to put result of first function to the second one, to use it in another calculation?

Thanks


r/learningpython • • Jul 30 '19

Anyway to stop ffmpeg from popping up? (pydub)

1 Upvotes

I'm trying to normalize a list of audio files in pydub and whenever I use file.dBFS, ffmpeg pops up. Is there any way to prevent ffmpeg from popping up?


r/learningpython • • Jun 03 '19

Pastebin + requests, invalid api_option?

1 Upvotes

Hello all,

trying to learn more about python and specifically how to make api get and post requests. I have a decent understanding of get requests, but I'm not very good at post requests. Trying just a simple pastebin post with python. Every time I try to paste something via the API I get "Bad API request, invalid api_option".

Below is my code for this:

import requests

## Pastebin API endpoint
api_endpoint = "http://pastebin.com/api/api_post.php"

## API Key for Pastebin endpoint
api_key = "xx"

## text to appear in pastebin
text_code = ''' 
print("Hello, world!") 
a = 1 
b = 2 
print(a + b) 
'''

# data to send to the api
data = {'api_dev_key': api_key,
        'api_option': 'paste',
        'api_paste_code': text_code
        }

# send post request
r = requests.post(url=api_endpoint, data=text_code)

# extract response
pastebin_url = r.text
print("Pastebin URL is:%s" % pastebin_url)

Any suggestions would be helpful. I'm pretty new to python and I'm at a loss on where to go from here. Everything from the pastebin api documentation says this is the proper way to use the api_option parameter. Is there something fundamental that I'm missing here?