r/learningpython • • Jun 01 '20

How to declare a list on different lines?

2 Upvotes

I'm trying to declare a list like this:

ListofItems=[["1", "2"],
["0", "1"],
["1", "2"],
["a", "b"]]

But I get errors.


r/learningpython • • May 16 '20

Code written in windows not running on linux.

2 Upvotes

I just started learning to code earlier this week and got my dad interested in learning some. So I made a basic rock paper scissors game and was going to have him look over it. Anywho I wrote the code on windows with VS code and it ran with no issues, when he went to run it with the terminal in ubuntu it ran into error after error to the point he had to change nearly every line of code in some minor way. What would be the major problem here and is there a way we can plan around this so we don't have to worry about it in the future.


r/learningpython • • May 08 '20

Python gotchas when coming from another language

2 Upvotes

I am an experienced Ruby developer. I want to more python. What are the strange edge cases of python that can trip me up?


r/learningpython • • May 07 '20

Why does random.choice( dict ) works sometimes? (returns a value of the dict instead of KeyError)

2 Upvotes

using pyhton3.7, i tried to use a dict as argument for random.choice().I understand that the argument should be a list or a tuple. or a string. Giving random.choice() a dict as argument raises a key error (as exspected), however, sometimes it works and returns me a random value from the dict. Why?

here is my code, from a python shell session:

import random>>> random.choice({1:111,2:222,3:333}) # works, but why?

222

>>> random.choice({1:111,2:222,3:333}) # same line, raises error

Traceback (most recent call last):

File "<pyshell#29>", line 1, in <module>

random.choice({1:111,2:222,3:333})

File "/usr/lib/python3.7/random.py", line 262, in choice

return seq[i]

KeyError: 0

>>> random.choice({1:111,2:222,3:333}) # works again, but why?

111


r/learningpython • • Apr 29 '20

A Python Dictionary decision tree?

2 Upvotes

Hi,

I've made some large dictionaries in Pyhton .JSON, extended the values with tuples for personal use. I want to make a interactive decision tree in Python, am i on the wrong foot with these dictionaries? What would you suggest? Any input is welcome.


r/learningpython • • Apr 22 '20

Creating an executable file without using chmod

2 Upvotes

I am using a Linux box and creating python code via vim editor. Is there a way to make that file an executable when I create the file? I know that you can chmod the file after creating it but I am hoping that I can cut that step out. TIA.


r/learningpython • • Apr 17 '20

Random number generator closes on run.

2 Upvotes

Every time I try to run the number generator, it closes. I have tried using input() and os.system("pause") but it is still not working.

import random

print(random.random())

input()

r/learningpython • • Apr 03 '20

Have to make pretty PDF Reports with graphs superimposed into them - wondering if there's an approach better than making graphs with Matplotlib, and then superimposing the .png output into the PDF manually through PyPDF2 library.

2 Upvotes

The execution really isn't a problem because I've done something like this on a smaller scale before, and I know 100% it can be done.

I'm just wondering if there's a more efficient way I'm not thinking of - perhaps something more suited to this exact kind of use-case.

One issue I also noticed is that when I do plaster the .png into the PDFs, sometimes there's jagged edges at the borders. I'm wondering if this is caused by some quirk in file types I'm not aware of, because this is something that completely blindsided me.


r/learningpython • • Apr 02 '20

Has anyone gotten Tkinter to work on mac?

2 Upvotes

I'm running Catalina 10.15.4 and trying to get Tkinter to work in python3 but get this error.

>>> import tkinter
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/Users/matt/.pyenv/versions/3.8.2/lib/python3.8/tkinter/__init__.py", line 36, in <module>
    import _tkinter # If this fails your Python may not be configured for Tk
ModuleNotFoundError: No module named '_tkinter'

I've tried brew install tcl-tk, it says it's up to date but still won't work. Also I've tried installing it from ActiveState (https://www.activestate.com/products/tcl/downloads/) but again it still doesn't work. Anyone else been able to get it working on mac?


r/learningpython • • Mar 30 '20

Stuck & Frustrated - Last for loop not 100%

2 Upvotes

My program loops through the text of Dracula - the goal is to have individual files of each chapter and each Chapter have the # and the title. My code finally worked and I was so excited but discovered that the text inside the files isn't right (same Chapter one over and over in each). Even a hint of what I should tweak would be very very appreciated.

I've edited it as many different ways as I could think of but it also might be a case of looking at it too long.

infile = open('Dracula.txt', 'r')
text = infile.readlines()
infile.close()

lines = text[74:186]

titles = []
for blood in lines:
    toc_text_lines = blood.rstrip('\n')
    if len(toc_text_lines) > 0:
        divided = toc_text_lines.splitlines()
        for numbers in divided:
            last_item = numbers[-1]
            if last_item.isdigit() == True:
               result = ''.join([i for i in numbers if not i.isdigit()])
               clean = result.strip()
               titles.append(clean)

names = []
for title in titles:
    nospace = title.replace(" ","-")
    nopunc = nospace.replace("'", "")
    names.append(nopunc.splitlines())



infile = open('Dracula.txt', 'r')
text = infile.read()
infile.close()

start = text.find("\n\nCHAPTER I\n\n")
end = text.find("_There's More")

Dracula = text[start:end] #this is the whole text of the book, string
chapters = Dracula.split('CHAPTER')
chapters.pop(0)

count = 1


for name in names:
    x = 0
    preferred_title = name[x]
    file_name= 'Dracula-Chapter-' + str(count) + preferred_title+'.txt'
    outfile = open(file_name, 'w')
    for chapter in chapters:
        print("CHAPTER", chapter, file=outfile)
    outfile.close()
    count = count +1
    x = x +1

r/learningpython • • Mar 12 '20

Any advice, best places to practice, etc.?

2 Upvotes

Hi first post in this sub and honestly fairly new to Reddit in general. I figured this would be a good place to help with learning code and wanted to hear if you all had any advice or places I could check out as I begin this journey. Thank you guys!


r/learningpython • • Mar 08 '20

What does this counting function work?

2 Upvotes

Hi, I am a bit confused about how the following function works. As far as I know, counts is an empty dictionary at the beginning. I don't see any element being added into the dictionary within the function. Am I missing something? Also, since counts is an empty dictionary as defined in line 2, how if x in counts: get executed? Perhaps I misunderstood something?

def counting(sequence):
    counts = {}
    for x in sequence:
       if x in counts:
          counts[x] += 1
      else:
          count[x] = 1
return counts

r/learningpython • • Dec 06 '19

Loading a string into an object

2 Upvotes

I am trying to load information from a file into an object. The file has been opened and the line I am adding is saved as line. Customer is the object in question, and customerData is the array I want to save the object into.

customerData = Customer(line.rsplit(','))

The line looks like this if I print it.

Jane Sweet,314 E. Pie Street,Appleton WI 54911,06/30/1955,cat

What do I need to do to the string so that I can save its individual parts as the 5 arguments the object needs. The object code is:

def __init__(self, Name, Address, CityState, Zip, Birthdate , Pet): #birthday format is (mm/dd/yyyy)

self.__Name = Name

self.__Address = Address

self.__CityState = CityState

self.__Zip = Zip

self.__Birthdate = Birthdate

self.__Pet =Pet


r/learningpython • • Nov 07 '19

[Academic] Data Analysis on Graph Databases (Anyone with data science knowledge)

2 Upvotes

Hi everyone,

I'm a final year student at UCL and my group and I are working on a project involving Machine Learning algorithms for analysis of graph-structured data. We'd love to know more about the potential users of a software that would make those tasks easier. Anyone that works with data, and particularly those that have worked with or are interested in graph databases would be more than welcome to take part in the survey!

https://docs.google.com/forms/d/e/1FAIpQLSfKuUS5xkbl8oDE-EU4Vz4Rr1oyQpXjZfEKbArEvu-nFXG6Gw/viewform?usp=sf_link

Thanks!


r/learningpython • • Oct 22 '19

digital root - codewars

2 Upvotes

Hi all,

I am here again to ask you to explain how this works.
Actually, before having a look on Google i have tried by myself for a couple of hours, but i did not figured out how to solve it without knowing in advance the len (n)

The exercise says, given an integer n, return the one digit number.
Like: 843 -->8+4+3 = 15 --> 5+1=6 --> stop. output is going to be equal to 6.

i found one very clever and short solution on stack overflow that comes out from a mathematical approach on Wiki.

def digital_root(n):
    if n>0:
        return (n-1)%9+1
    else:
        return 0

the if / else is there just in case n<0.

i understand what modulo does, but it's tricky to clearly figuring out why 1)using 10 2) why subtract 1 at the beginning and then add it again.

Cheers,

F.


r/learningpython • • Sep 23 '19

Poker Hand Logic

2 Upvotes

I need help with Texas Hold'em hands. For some reason , I can't get it to determine what type of hand players have.


r/learningpython • • Sep 15 '19

Help with for loop, and possibly pseudo variable?

2 Upvotes

ok, I'm trying to loop a folder then only filter out files created today... kinda (I have already done this part)

folder_path = os.path.expanduser('~/Dropbox/AHK/AutoPrinter/09 - printed')
now = time.time() # get now's time one_day_ago = now - 606024*1 # 1 for the day number
Files_to_send = [] # create / clear list for storage of files
for file in os.listdir(folder_path): 
if os.path.getctime(f"{folder_path}/{file}") >= one_day_ago: # filter files based on creation time 
    Files_to_send.append(f"{folder_path}/{file}") # append files to a list

but the tough part now is how am I going to insert this list into this command?

Below is an example of how to insert 2 pictures into a command.

f1 = open(f"{folder_path}/{path_file1}", 'rb') # open file in binary
f2 = open(f"{folder_path}/{path_file2}", 'rb') # open file in binary 

bot.send_media_group(msg.chat.id, [InputMediaPhoto(f1,'caption1'), InputMediaPhoto(f2,'caption2')]) # send to chat

I was thinking of using pseudo-variables to create f1, f2, f3 etc but I'm not that experienced with python atm.

What do you guys think would be a good solution to this?


r/learningpython • • Jul 30 '19

Web Scraping Made Easy + Automation

2 Upvotes

r/learningpython • • Jul 18 '19

Asynchronous in Computer Vision

2 Upvotes

(repost from r/Python)

Hi everyone,

i developed a people counter. Receives an input feed in real time. Every 30 frame runs a object detection (yolov3) and in rest of the frames performs a centroid tracker.

Each time it detects a person in a region of interest, the program saves some data and makes a POST request to the server in order to save the data for each person.

The problem:

The POST request takes a lot of time, and i drop some important frames to process. I want to do the POSTS request asynchronously but i'm having troubles with asyncio and threading. I'm learning both at the same time in order to choose one.

In asyncio:
My program structure is a main infinit loop that reads the frames from the input feed and then process them. I do not know how to await the POST request and then come back to the infinit loop.

All the asynchronous examples that i've seen, focus on code that just runs once.

Can you shed me some light here. Thanks


r/learningpython • • Jul 18 '19

What does "this object does not support enumeration means"?

2 Upvotes

Hello all, as many here I'm also new to python, I apologize if this is something silly to ask. I'm trying to manipulate data from a table in a word document, but I'm facing some challenges. I'm able to extract the data with the script below:

import win32com.client as win32

def checkwhatewosareneeded ():

word = win32.Dispatch("Word.Application")

word.Visible = False

word.Documents.Open(r"C:\Desktop\Python\test.doc")

doc = word.ActiveDocument

print (doc.Tables.Count)

table = doc.Tables(29)

woneeded1 = table.Cell(Row = 4, Column = 3)

print (woneeded1)

checkwhatewosareneeded ()

the output I get from the script: 29 Y

but it seems like the result variable is not a str, or I don't know how to treat it, because whenever I try to do something with it, for example add it to a for loop:

for letters in (woneeded1):

print (letters)

I receive the error:

for letters in SSRewoneeded:

File "C:\Users\Python\Python37-32\lib\site-packages\win32com\client\dynamic.py", line 257, in __getitem__

raise TypeError("This object does not support enumeration")

I'm not sure what I'm doing wrong, any recommendations/suggestion are welcome


r/learningpython • • Jun 13 '19

Help to convert .sh to python

2 Upvotes

I have a clumsy .sh script I use for copying my dotfiles with rsync to another location and I want to convert it to python.

The idea is to make a python script who can easily include a lot more directories or just expand without too much code.

Is this a stupid way to approach this "problem"?

This is the script:

!/usr/bin/sh

cfg="/home/username/.config" rsc="rsync -avt --delete --exclude=('*.git')" dot="/home/username/Nextcloud/Dotfiles/laptop"

$rsc /etc/pacman.conf $dot/etc $rsc ~/.oh-my-zsh/custom $dot/.oh-my-zsh $rsc ~/.aliases ~/.vimrc ~/Scripts ~/.ssh $dot $rsc $cfg/locale.conf $cfg/i3 $cfg/polybar $cfg/alacritty $dot/.config


r/learningpython • • Apr 30 '19

Multithreading/Multiprocessing (in a Docker container)

2 Upvotes

Hi,

I'm running Python code in a Docker container that executes three image processing functions which I'd like to run concurrently. I have never attempted parallel processing before.

Is multithreading or multiprocessing the correct function to look for (https://www.youtube.com/watch?v=ecKWiaHCEKs&t)? Also if anyone could direct me to code performing a similar function that would be brilliant :)


r/learningpython • • Mar 20 '19

Counting vowels in a string

2 Upvotes

Hello! Me again with another assignment. My assignment this week is to create a program that allows the user to input a string and then counts the vowels in the string. It must include a loop and the len function. Then it displays the string plus the number of vowels. So far I've come up with this

sentence = input ("enter your string: ")

for vowel in sentence:

if vowel in 'aeiou':

print (sentence, len(vowel))

But the output isn't right and I'm not sure where to go from here.

Any help is appreciated.


r/learningpython • • Mar 11 '19

Conditional list trouble

2 Upvotes

I’m trying to learn from the bottom up, and am currently working through the exercises on practice python.

Example they have on conditionals is a grading scale like this:

Grade= input(“enter your age:”) If grade > = 90 : Print(“A”) Elif grade > = 80 : Print (“B”)

Why is it when I try to copy/paste into my python window I get : TypeError: ‘>=‘ not supported between instances of ‘Str’ and ‘int’