r/learningpython • u/Jhohn83 • Jun 01 '20
How to declare a list on different lines?
I'm trying to declare a list like this:
ListofItems=[["1", "2"],
["0", "1"],
["1", "2"],
["a", "b"]]But I get errors.
r/learningpython • u/Jhohn83 • Jun 01 '20
I'm trying to declare a list like this:
ListofItems=[["1", "2"],
["0", "1"],
["1", "2"],
["a", "b"]]But I get errors.
r/learningpython • u/patrickfizban • May 16 '20
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 • u/silly_frog_lf • May 08 '20
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 • u/horstjens • May 07 '20
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 • u/[deleted] • Apr 29 '20
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 • u/Mrs_Ruk • Apr 22 '20
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 • u/Wide-Currency • Apr 17 '20
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 • u/Lostwhispers05 • Apr 03 '20
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 • u/morepootis • Apr 02 '20
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 • u/CatLadyLostInLibrary • Mar 30 '20
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 +1r/learningpython • u/beepbeep_researcher • Mar 12 '20
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 • u/largelcd • Mar 08 '20
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 countsr/learningpython • u/Chance1441 • Dec 06 '19
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 • u/not_apyramidscheme • Nov 07 '19
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!
Thanks!
r/learningpython • u/chere68 • Oct 22 '19
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 0the 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 • u/ApprehensiveSong5 • Sep 23 '19
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 • u/fenchai • Sep 15 '19
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 listbut 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 chatI 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 • u/weihong95 • Jul 30 '19
Hi guys, for beginner on web scraping can visit this two blog post:
https://towardsdatascience.com/get-rid-of-boring-stuff-using-python-part-2-b84d1e9ea595
Hope it helps!
r/learningpython • u/Volskoi • Jul 18 '19
(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 • u/Bendecidayafortunada • Jul 18 '19
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 • u/brickforbrick32 • Jun 13 '19
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:
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 • u/freshprinceofuk • Apr 30 '19
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 • u/wftwe • Mar 20 '19
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 • u/dumayi • Mar 11 '19
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’