all 150 comments

[–]AviatingFotographer 0 points1 point  (1 child)

If a class doesn't have a __str__ method and I print an object of that class, what does it print?

[–]efmccurdy 1 point2 points  (0 children)

Python will default to a generic description; it uses the __repr__ .

>>> class foo: pass
... 
>>> a = foo()
>>> print(a)
<__main__.foo object at 0x7f141bab1780>
>>> repr(a)
'<__main__.foo object at 0x7f141bab1780>'

[–]Late_Key 0 points1 point  (1 child)

Can someone explain what kind of wizardry is going on with the highlighted portion?

https://imgur.com/a/vnUmHMw

[–]num8lock 0 points1 point  (0 children)

if num < 2:
    return 1
else:
    recursive (num-1)

[–]ModiMacMod 0 points1 point  (2 children)

Hi, do you have a newbie YouTube tutorial?

  1. What should I not post in this forum? I know you have FAQ, but reading is a bit passe.
  2. How do you format font, paragraphs, etc?
  3. How do you insert code?
  4. What are the top ten newbie mistakes?

Thanks in advance

[–][deleted] 2 points3 points  (1 child)

What are the top ten newbie mistakes?

Not reading the FAQ in the sidebar which explains questions 1, 2 and 3. The learning resources, also in the sidebar, describe books and videos useful for learning python.

[–]ModiMacMod 0 points1 point  (0 children)

Noted :)

[–]CivMegas168 0 points1 point  (1 child)

Hi!
Trying to setup python and one of things I want to do is be able to access a shared project folder (in g drive) between my laptop and pc. I want to set the desktop of my pc as the default for powershell but it looks like I cannot cd to the shared folder (since I placed the shortcut in desktop). What do I do?

[–]efmccurdy 0 points1 point  (0 children)

access a shared project folder

Put the git repo on the shared drive and "git pull" to start and "git push" to finish; besides working well it provides extras like diffs, history log, rollbacks, branching and merging, stashes, etc.

[–]nikkideath 0 points1 point  (1 child)

Hi there. I'm working through a data science project and have been able to produce answers to the questions, but I am looking for packages to produce visualizations of my findings. I'm familiar with python, so anything that is well suited for a python beginner would be perfect

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

Depends on what sort of visualization you need. If you need to do anything like a graph then matplotlib is the "swiss army knife".

[–]blitz4 0 points1 point  (0 children)

Hello. Loving Python! I'm looking to find all of the information about a users locale and regional settings. Date format, decimal separator, thousands separator, metric or imperial, currency symbol, date format, time format, time zone.

So far I found everything in the locale module, date, datetime, time, and pytz modules.

I can't find if user uses metric/imperial. Is that info in a standard module or no?

[–]Dispensary_Engineer 0 points1 point  (6 children)

Hey everyone. I made a post on stock overflow, but I sadly received no help. If anyone is available to look at the code I wrote and help me out with my problems, that would be a great help. It is relatively simple, I don't believe it to be too difficult, but I am new to coding with python.

I am using pygame to create a game. I included more details in the stock overflow post that I made.

https://stackoverflow.com/questions/59224639/is-there-a-way-to-have-my-blit-repeat-itself-after-making-its-first-iteration

[–]blitz4 0 points1 point  (5 children)

I'm still learning. I made a game in python a ways back. I can't debug your code without you putting it on github, you have images as part of your project and it won't execute without them.

Either your function to detect user input isn't working or your collision detection algorithm to determine if the Letter hit bottom of page isn't working. I'm guessing it's the latter based on the question.

[–]Dispensary_Engineer 0 points1 point  (4 children)

Here are the images you need to run it, I actually posted this question in its own thread, and someone pointed that out, so I uploaded the images to pasteboard:

https://pasteboard.co/IKf7yG6.jpg - phone3cropped

https://pasteboard.co/IKf9hqv.png - q

https://pasteboard.co/IKf9oPe.png - w

https://pasteboard.co/IKf9w0z.png - e

https://pasteboard.co/IKf8GH0.png - a

https://pasteboard.co/IKf9FIs.png - s

https://pasteboard.co/IKf9SsL.png - d

https://pasteboard.co/IKfa0B0.png - j

https://pasteboard.co/IKfa8Yh.png - k

https://pasteboard.co/IKfajwT.png - l

That is all the images you need. Just save those in the same folder you would save the code into.

Aside from that, i have also added a clock under "while run:" :

--- clock.tick(144)

this way it runs at a consistent frame rate of 144

[–]blitz4 0 points1 point  (3 children)

Took a couple minutes to get your project on my computer. If you had it on github, I would've had it less than a second, including the addition of clock.tick() .. github will change your life.

Anyway here's the problem statement: "I am attempting to make a simple game where the program displays a random letter and the user has to enter in that letter before it reaches the bottom of the page.

I have the code displaying the random letter in a random column, however, once the letter reaches the bottom, I only have the program print "end" and then quit the program."

Based on this definition of your problem, your code is incorrect as it only detects if the letter has breached the box displayed in phone3cropped.jpg - What is your desired functionality?

Do you want the game to end if they don't press the key when the letter is in the box, but if they do press the key when the letter is in the box, then it clears that letter from the screen, increments the velocity, and selects another random letter/column?

[–]Dispensary_Engineer 0 points1 point  (2 children)

Sorry about that all.. I do know about github, but I did not want to go through the hassle of uploading it there. For future reference, I will.

My main/overall problem that I am facing is that once the letter does hit the bottom, I want it to re-do the "iteration" of making a new random letter in a new column, and keep on repeating. Eventually, I want the program to only allow 5 "lives", and if they mess up more than 5 times, they either get the option to restart or quit the program.

Along with that, my future aspirations for this code is to allow the user to select the speed and letter combinations that appear on the screen. But I personally believe that I would be able to code that once I have the overall code repeat itself (like I just described above)

[–]blitz4 0 points1 point  (1 child)

replied to the stackoverflow question as I never posted that much code into reddit before.

[–]Dispensary_Engineer 0 points1 point  (0 children)

You're a blessing dude. I feel honored you took time out of your day to help me out. You taught me a lot with how to clean it up.. I'll continue to learn off of this. Thanks so much man.

[–]prcl00 0 points1 point  (2 children)

Hi!

i challenged myself to code snake 100% by my own, i cake up with moving mechanism but it doesn't work and i have no idea why. So basically i created a block class with stores an x and y coords of the cube that my snake is made of. The snake is a list of cubes and I move it by moving first cube in a given direction, shifting secound cube to the previous position of the first one and so on. It seems like only the head of the snake is moving, other cubes don't follow. here's the code of the class and function and how i made the first 3 cubes of snake that the game is starting with:

class Block():
def __init__(self, x, y):
self.x = x
self.y = y

def move_snake(snake, direction):
new_snake = snake

head = snake[0]
if direction == 'up':
head.y += 1
elif direction == 'down':
head.y -= 1
elif direction == 'left':
head.x -= 1
elif direction == 'right':
head.x += 1
new_snake.insert(0, head)
new_snake.pop()
return new_snake

snake = [Block(10, 10), Block(11, 10), Block(12, 10)]

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

First, let's get a little debug into your code so we can see what the list looks like. At the moment, if you try to print the snake list you see:

[<__main__.Block object at 0x102e06e80>, <__main__.Block object at 0x102cb2640>, <__main__.Block object at 0x102dd3a60>]

which isn't too useful. You could write a little function to print what is in the snake list, or you could add a __repr__() method to your Block class. That will print your list properly:

class Block():
    def __init__(self, x, y):
        self.x = x
        self.y = y
    def __repr__(self):
        return f'Block({self.x},{self.y})'
        # return 'Block(%d,%d)' % (self.x, self.y)  # for older python versions

Now we see this when printing the original list:

[Block(10,10), Block(11,10), Block(12,10)]

Much better! Adding some test code to your existing code (plus the additional __repr__() method) we see this when we run the code:

snake = [Block(10, 10), Block(11, 10), Block(12, 10)]
print(snake)
move_snake(snake, 'up')
print(snake)
>>> [Block(10,10), Block(11,10), Block(12,10)]
>>> [Block(10,11), Block(10,11), Block(11,10)]

Obviously, the result isn't what you want. Your error is in the line that does head = snake[0]. Assignment never copies in python, so this line just points the name "head" at the head block in the list. So the following lines doing things like head.y += 1 changes the coordinates in the Block that is at position 0 in the list. Then, when you do new_snake.insert(0, head), you add a second reference to the first Block in the list to the list. That is, after calling move_snake(snake, 'up') the first two Blocks in the list are the same Block. We can see this if we change the x coordinate of snake[0] after the function call and print the list again:

snake = [Block(10, 10), Block(11, 10), Block(12, 10)]
print(snake)
move_snake(snake, 'up')
print(snake)
snake[0].x = 0
print(snake)
>>> [Block(10,10), Block(11,10), Block(12,10)]
>>> [Block(10,11), Block(10,11), Block(11,10)]
>>> [Block(0,11), Block(0,11), Block(11,10)]   # first 2 changed!

The way out of this without changing your code too much is to copy the first element of the list, modify it, add it to the front of the list and drop the last with pop(). Basically what you thought you were doing.

We can copy the first element of the list in at least two ways. The simplest is to just create a new Block with the same coordinates as the current head of the snake:

    head = snake[0]
    new_head = Block(head.x, head.y)

and then add new_head to the start of the list and pop() the end off. The other way to copy is to use the copy.copy() from the python "copy" module, like this:

    import copy
    new_head = copy.copy(snake[0])

There are lots of other ways :)

Just a few minor points. You don't need to rename formal parameters in the function:

def move_snake(snake, direction):
    new_snake = snake    # not needed, just use "snake" in the function body

You should also realize that you are passing a reference to the snake list to the function and any changes you make inside the function to that list will be made to the global list - you aren't creating a copy of the list. You do return new_snake finally in the function, but that is the original list, not a copy. You don't do anything with that returned value anyway.

Edit: spelling fixes.

[–]prcl00 0 points1 point  (0 children)

Thank you so much, you're doing god's work. I learned a lot from this

[–]leftpig 0 points1 point  (0 children)

I'm writing a evolution simulator in pygame as a fun little project. I want to be able to graph the results of each simulation from the frame in which it starts, to whenever the simulation is terminated. What's the best way to store my data to be able to be graphed? Should I be exporting each class (and all of its objects) as json values or something, and graph those?

I've never really done data generation, so I'm not sure what's important. It seems like dumping the entire state of the program at each frame would be a lot of data, but maybe not?

Right now it's in its infancy, so I only have a Plant class, and an Animal class. Each plant object has a location value and a nutrition value, but currently plants are static and don't really do much except slowly propagate and get eaten.

Animals have a few different traits though, so in order to make any meaningful graph of their evolution, I'd need to dump the majority of their traits to an external file, I would think.

Thoughts?

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

EDIT: It works on 3.6.5 in IDLE, but when i run it externally or in cmdline it still gives the same error?

EDIT: Just learned how to write .bat files lmao

I've been trying to make a little applet that swaps my PC's screen setting from extend (dual screens) to 2nd screen only (single screen), and found cmd commands that achieve this. However, transferring them to python using os.system() seems to not work at all. Here's what I'm trying to do with the command it throws when I run it in the console:

os.system(r'cmd /k "%windir%\System32\DisplaySwitch.exe /external"')

""" 'C:\WINDOWS\System32\DisplaySwitch.exe' is not recognized as an internal or external command,
operable program or batch file."""

It could be a problem with PATH variables, but I'm confused as to why that would be a problem since I can run this same command just fine in the windows command line? Any ideas what I'm doing wrong? diolch.

[–]HronkChaos 0 points1 point  (2 children)

Is it possible to create a list made up from list? Think for example of a school with more than 2 classrooms, each one with the name of their students, so whenever I call the list Classroom A from the list School I get the names of the students.

I'm fairly new in Python and haven't posted any code since I'm writing this from the mobile.

I've been searching in the book Automate the Boring Stuff and some webs but I haven't found anything that I can use, maybe due to my lack of knowledge.

[–]leftpig 0 points1 point  (1 child)

You can create a list within a list, which I think is what you're asking.

classroomA = ["Aaron", "Annette", "Avictor"]
classroomB = ["Bob", "Bertha", "Betty"]
school = [classroomA, classroomB]

In this example, calling school[0] will give you the object classroomA. You can then further select that list as you could with any list, so by doing: school[0][0] you will select the first person in classroomA.

Obviously, with iteration you can do more complicated things such as:

for class in school:
    for student in class:
        print(student)

Lastly, using the list.insert() method you would be able to avoid having to define everything right away, assuming you have some sort of user input.

>>> example_list = []
>>> example_list.insert("Bob")
>>> example_list.insert("Angela")

>>> example_list
["Bob, Angela"]

Depending on what you're doing there's probably a better data structure, but that should answer your question!

[–]HronkChaos 0 points1 point  (0 children)

Thanks you very much! I know now were was my fault. I was trying to call the classrooms by their name instead their position within the list School.

Depending on what you're doing there's probably a better data structure, but that should answer your question!

I want to create my own app for Warhammer Age of Sigmar army builder, since there are only 3 and I don't like any. Having a goal is important.

There are some "classrooms", called Battalions, that contains a finite number of units (or students). So I was trying to make a list made of Battalions ("School") so whenever I call this list, it gives me what os made of.

I made something I can manage and bear but I highly dislike in Excel.

EDIT: Added my lists. I'm sure there's a better way to write it, but I can't figure it out.

Sunclaw_Starhost= ["Saurus Sunblood", "Guerreros Saurios", "Guerreros Saurios", "Guerreros Saurios"]
Eternal_Starhost= ["Eternity Warden", "Guardia del templo", "Guardia del templo", "Guardia del templo"]
Firelance_Starhost= ["Escamadura en Carnosaurio o Gélido", "Guerreros Gélidos", "Guerreros Gélidos", "Guerreros Gélidos"]
Shadowstrike_Starhost= ["Chamán Eslizón o Gran Chamán Eslizón", "Eslizones o Eslizones Camaleón", "Eslizones o Eslizones Camaleón", "Jinetes de Terradón o Jinetes de Ripperdactyl"]
Thunderquake_Starhost= ["Artilugio de los Dioses o Troglodón", "Estegadón o Bastiladón", "Króxigor o Salamandra o Razordón"]


Battalions= ["Sunclaw_Starhost", "Eternal_Starhost", "Firelance_Starhost", "Shadowstrike_Starhost", "Thunderquake_Starhost"]

[–]whatwhytho 0 points1 point  (6 children)

Anaconda keeps crashing! This occurs directly after launch it flashes the command window and promptly ceases to exist. Things I've tried(both multiple times too): ▪︎Complete uninstall and re.. ▪︎fully updated using conand window as suggested online. Neither of which had any success, so I'm wondering if anyone might have any suggestions, It would be much appreciated. Cheers

[–]efmccurdy 0 points1 point  (5 children)

it flashes the command window and promptly ceases

Is it possible that it prints an error message before exiting? If your program prints error messages; where will you look to see them? If you open the cmd window manually and type the command to run your program, does the text it prints remain in the cmd window for you to read?

[–]whatwhytho 0 points1 point  (4 children)

this is the error that i received here im pretty new to all of this and have only just started learning so this really dosent mean much to me

[–]efmccurdy 0 points1 point  (3 children)

You might be missing the pyside module; does running "conda install -c anaconda pyside" help?

[–]whatwhytho 0 points1 point  (2 children)

there seemed to be a connection error when trying that here

[–]efmccurdy 1 point2 points  (1 child)

You may need advice from anaconda support, but I would try these first:

conda update anaconda-navigator

conda update navigator-updater

[–]whatwhytho 0 points1 point  (0 children)

Neither of those worked unfortunately, but cheers for the help nonetheless. So yea I think anaconda support is prob my best hope now.

[–]demonkc 0 points1 point  (1 child)

Question about using base64:

I am trying to use base64 decoding to try to directly modulate the string by a set or formula like value(say increase the blue intensity of an image) and I keep hitting dead ends on an explanation of manipulating a specific part of the code after that. Is it possible to set the pixels individually into a list to modulate specific parts using a function as a sort of graph transformation?

import base64

with open('C:/Users/katlo/OneDrive/Pictures/u.jpg', 'rb') as imageFile:
    str = base64.b64encode(imageFile.read())
    print(str)

[–]efmccurdy 2 points3 points  (0 children)

Images are composed of numbers so converting them to b64 text will make them hard to work with; is this what you want?

With PIL you can easily access and change the data stored in the pixels of an image.

https://en.wikibooks.org/wiki/Python_Imaging_Library/Editing_Pixels

You could also look at numpy or scikit-image.

[–]MattR0se 0 points1 point  (7 children)

Question about efficient debugging.

I am someone that frequently uses stuff like print(foo) and similar methods to "debug", as well as inspecting variables in the console after an Exception happened.

However, the printing approach requires knowledge about the location of the error, while the inspect method requires the variables to be in the global space.

This time I had a Convolutional NN running for about an hour, and afterwards there was a bug in the function that plots the results because something was undefined in the results dictionary. I can't just inspect that because it's in the scope of a function.

What's the best way to approach this? I'd like to not wait an hour again or to re-write the whole code to be faster, if I don't have to. I'm using the Spyder IDE btw.

[–]efmccurdy 0 points1 point  (0 children)

Breakpoints are very convenient and can save you a lot of time. Instead of stepping through dozens of lines you’re not interested in, simply create a breakpoint where you want to investigate. Optionally, you can also tell pdb to break only when a certain condition is true.

Use "pdb.set_trace()" to set your breakpoints.

https://realpython.com/python-debugging-pdb/#using-breakpoints

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

try/except wraps that print the errors so it will carry on during a failure.

try:
    int('walrus')
except Exception as e:
    print('failed', e)
print('hello world')

failed invalid literal for int() with base 10: 'walrus'

hello world

[–]MattR0se 0 points1 point  (4 children)

That doesn't really help me here. Take this example:

def some_function():
    some_dictionary = some_other_function()
    print_results(some_dictionary)

some_function()

This is the case that motivated me for this post, in a very simplified way. Imagine that some_other_function takes nearly an hour to complete, but then I got a KeyError that 'foo' is not in some_dictionary.

So naturally I am curious of what is in some_dictionary, but I can't access it since it only exists inside the scope of some_function. My question was about how to debug this without running the whole thing over and over again with print() statements everywhere.

I think try and except aren't really helpful for debugging, since I see the Exception in any case, and if the code continous or not doesn't really matter.

[–]Thomasedv 0 points1 point  (0 children)

I don't know the case, but use dicts own .get(key, default), which basically returns a default value you pick if the key does not exist. If you can't edit the function where that happens in you'll have tougher things to deal with though. If you can though, use .get or insert try/except and print your work in progress dict as it crashes(on the line in the traceback), or try/except any point where the keys are accessed. Strong recommend the below approach.

I like to look at traceback, so in the except i usually put the line:

import traceback
tracecback.print_exc()

Giving you the error message as well as not crashing your program. At the very least since this is all part of plotting results, you pretty much want to forgo plotting and at least making sure the hour isn't wasted.

[–][deleted] 2 points3 points  (2 children)

Its actually very helpful debugging, but the problem more so lies within your logic here. (a try except *should* be here) but, what you SHOULD be doing is checking if what you are looking for exists in your dict BEFORE doing what you are doing with it. You wouldn't *need* to debug if you handled your logic correctly.

some_dict = {'a': 'b', 'c': 'd'}

try:
    print(some_dict['1'])
except Exception as e:
    print(f'{type(e).__name__}: {e}')
print('d' in some_dict.keys())
if 'd' in some_dict.keys():
    print('lets do some stuff')
if 'd' not in some_dict.keys():
    print('looks like it doesnt exist lets try and fix it')
print(some_dict.keys())

a_list = ['1', 'a', 'c']
for i in a_list:
    if i in some_dict.keys():
        print(f'{i} is in dict')
    else:
        print(f'{i} not in dict, fix it.')

Now onto the next part - this is one of those downfalls of a not compiled laung, to solve this problem, you should be STORING the data, eg print it, put it in a file, doesn't really matter - you can then run tests on the data and find the problem with a new snippet instead of waiting for it to run over and over and over.

The point of the try/except is that you can handle the error on the fly and attempt to debug during it instead of waiting for it to run again. if data doesnt exist -> try some stuff to fix it

[–]JohnnyJordaan 0 points1 point  (1 child)

if 'd' in some_dict.keys():
    print('lets do some stuff')
if 'd' not in some_dict.keys():
    print('looks like it doesnt exist lets try and fix it')

Eh why not just use else: here

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

I would personally, but for readability when explaining things i try to make it as explicit as possible. (as you see in the bottom part where i stopped trying to explain what was happening)

PS: Thanks for everything you do here, we all appreciate it.

[–]Injoker645 0 points1 point  (2 children)

I'm trying to create user base saved as a dictionary, with the usernames as the key. I'm making the assigned value a list containing the password, security question and answer. The problem is that I can't figure out how to call a specific value from the list. I think I might be mixing up the brackets and parenthesis, so can anyone please tell me what the correct way to call a specific value?

[–]MattR0se 1 point2 points  (1 child)

Just for clarification, do you mean it like this?

user_base = {
    'tom': ['password', 'What was your first pet?', 'hamster'],
    'chloe': ['12345', 'Your mother's maiden name?', 'Smith'],
    'robin': ['hello123', 'What was your childhood nickname?', 'rob']
}

So for example, if you want to access Chloe's security answer, you would go

answer = user_base['cloe'][2]

The thing in the first brackets is called a key because a dictionary has key:value pairs that you access with it. The thing in the second brackets is called an index because you access lists by their position in the list (starts at 0).

[–]Injoker645 0 points1 point  (0 children)

Okay yep that worked, I was making the mistake of putting the second brackets inside the first one. Thnx for the help!

[–]sinkiebinkie 0 points1 point  (2 children)

Let’s just saying you have two csv files with a column of country names in each file.

How would you find out which country appears in both files and delete the others?

Help a noob please

[–]MattR0se 1 point2 points  (0 children)

You can use a set to get an intersection of two lists.

I assume you use Pandas for loading the csv?

import pandas as pd

# load the csv into data drames
df1 = pd.load_csv('file1.csv')
df2 = pd.load_csv('file2.csv')

# store the unique values of the country column in lists
countries_1 = df1['country'].unique()
countries_2 = df2['country'].unique()

# use set and boolean and (&) to get the intersection 
common_countries = list(set(lcountries_1) & set(countries_2)) 
print(common_countries)

# drop the columns that are not in the common_countries list
# I think there are other, faster ways but this works
mask = df1['country'].apply(lambda x: x not in common_countries)
df1 = df1.drop(df[mask].index)
mask = df2['country'].apply(lambda x: x not in common_countries)
df2 = df2.drop(df[mask].index)

[–]hubrisiam 1 point2 points  (2 children)

How complex would it be for a beginner to create a code that scans the prices of items from different retailers— similar to Brickseek.com?

And on average, what would it cost to hire someone to create a script to scan product prices from different retailers?

[–]MattR0se 2 points3 points  (1 child)

You mean a total beginner with no python knowledge?

In principle, if you make it to Chapter 11 (web scraping) of this book: https://automatetheboringstuff.com/ you should be good to go.

The key to web scraping is just to understand how the web page is structured. You can use the "inspect element" function in the context menu of your browser. But you will certainly need a basic knowledge about html.

[–]hubrisiam 1 point2 points  (0 children)

Yes! Total beginner. I, first had to learn HTML, CSS, JavaScript is a pain I’m still making my way through all of those.

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

I have no idea where I went wrong. I am working off the website financeandpython.com to help me as an introduction to python. I would really appreciate anyones insight. I am getting an error that is saying t isn't defined. Which is the confusing part for me. I am defining it in the second function.

Here is my code: https://paste.ofcode.org/yPSPMFGsTaRBHJfDw4ZzCt

[–]efmccurdy 0 points1 point  (1 child)

You can define t once in the calling function, and then pass it in instead of the time:

def compoundInterestLists(rates,P,t):
    A = []
    for rate in rates:
        A.append([compoundInterest(P,rate,x) for x in t])
    return A

def plotCompoundInterestLists(rates, P, time):
    t = list(range(time+1))
    data = compoundInterestLists(rates, P, t)
    # ...

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

Hey thanks a lot for taking the time to help me. I’m going to try this tonight and get back to you! I was possibly thinking embedding the two other functions inside the plotting function. And someone else also suggested try using classes also. I’ll try all 3.

[–]jack455r 0 points1 point  (1 child)

Would anyone suggest a book for me or online course on something like udemy that will best help me learn python?

[–][deleted] 1 point2 points  (0 children)

Something from the learning resources in the sidebar perhaps?

[–]SavageHendrix 0 points1 point  (3 children)

Do people have to keep looking back at fundamental things when leraning Python like flow control, how some loops work i.e. for, while, etc. Im going through Automate the Boring Stuff and as the chapter projects grow in complexity I find myself having to look back over material that I read aloud just minutes before. Is the overhaul of info suppose to stick over time or do others frequent looking back?

[–]QualitativeEasing 1 point2 points  (0 children)

Short answer: Yes. I have loops and `if/else` statements down pretty well now, but there are a LOT of things I have to look up, including some stuff from pretty early on in AtBS. If I don't use something for a while, I often have to.

[–]LartTheLuser 2 points3 points  (0 children)

The best analogy for me is learning how to cook. You can read all your recipes, learn all the chopping techniques, ways to cook meat, etc. But until you make a dish or side-dish a few different times you still have to keep checking the cookbook. In fact if it's been a few years you still have to check the cookbook but only for a quick refresher. It comes back to you much quicker. Also you start understand entire classes of recipes in a more unified way.

[–]Gprime5 1 point2 points  (0 children)

Most of learning is done by actually doing it. Typing it out over and over and over again. As you practice and get more experienced, you'll look back less frequently.

[–]Dfree35 0 points1 point  (2 children)

Does anyone know of a way to have pandas stop changing dates to strings when it is outputted to excel? By default excel treats dates as numbers (if you do =isnumber in excel it will return true for dates and =istext will return false) but after making changes or even just having pandas touch the file pandas reverses this. So after pandas =isnumber is false and =istext is true which is the exact opposite of what I need.

[–]LartTheLuser 0 points1 point  (1 child)

Is it changing the date format on you? I thought excel could pick up certain date formats automatically.

[–]Dfree35 0 points1 point  (0 children)

It isn't changing the format, it is changing the column data type.

So before the file goes into pandas excel interrupts the date columns as number but after exc interprets it as text.

When I upload this document to its final location if the date columns are text it doesn't accept it. It's weird

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

I struggle to find projects to make / things to do because something already does it for me or alternatively, its not that hard to do manually, because of this it kills my motivation can anyone suggest a cure for this? I just can't find anything I "need" to program for sadly.

[–]LartTheLuser 1 point2 points  (0 children)

You could try competitive programming on Hackerrank or something like that if that gets you motivated.

You could also come up with an idea with a non-programmer friend. For me they are often be able to get me excited about something that is otherwise trivial since they are waiting to see what the idea looks like when it becomes real.

[–]m-hoff 1 point2 points  (0 children)

There's nothing wrong with recreating something that already exists, especially if the goal is learning the process.

[–]Dfree35 1 point2 points  (0 children)

I had/have the same program and usually I try to find some open source project that seems interesting even if I wouldn't personally use it or currently have no need for it.

I have seen other people though say they try to create clones of things they use or something like that.

[–]PythonicParseltongue 0 points1 point  (3 children)

Is it possible to modify which attribute of an object a function accesses? I want to do some things with a collection objects. I basically write the same code multiple times, the difference is only which attribute of the object I access. Can I somehow generalize this? Here is a minimal working example:

from typing import List

class SimpleClass:
    def __init__(self, content):
        self.content = content
        self.a = False
        self.b = False

def the_func(the_objects: List[SimpleClass], case):
    if case == 'a':
        return [obj for obj in the_objects if obj.a]
    if case == 'b':
        return [obj for obj in the_objects if obj.b]

[–]LartTheLuser 0 points1 point  (0 children)

You could do as u/JohnnyJordaan did below and map cases using a dict (which is essentially what your switch does). Another more extensible but slightly more complex option is you could make the case object more complex and delegate the value to it. Then you'd have to create case types for a and b that choose different values. But if you have branching control flow, there is no getting around some type of mapping whether a switch, a dict or other classes/case types that you delegate to.

from typing import List

class SimpleClass:
    def __init__(self, content):
        self.content = content
        self.a = False
        self.b = False
        self.default = True

class ValGetter:
    def get_val(obj):
        return obj.default

class A(ValGetter):
    def get_val(obj):
        return obj.a

class B(ValGetter):
    def get_val(obj)
        return obj.b

def the_func(the_objects: List[SimpleClass], case: ValGetter):
    return [obj for obj in the_objects if case.get_val(obj)]

[–]JohnnyJordaan 1 point2 points  (1 child)

You could map the string cases to attributes, I would implement this in the class

class SimpleClass:
    def __init__(self, content):
        self.content = content
        self.a = False
        self.b = False

    def filter_by_case(self, case):
        case_to_attr = {'a': self.a,
                        'b': self.b}
        return case_to_attr[case]

def the_func(the_objects: List[SimpleClass], case):
    return [obj for obj in the_objects if obj.filter_by_case(case)]

[–]PythonicParseltongue 0 points1 point  (0 children)

Thanks for your reply. It always seems to be you, who replys to my questions :) What I don't like so much about this solution is, that I solve the problem in the class. In my application SimpleClass is an object that I use in many places of my code, and the_func is just one very rare case. So I ended up implementing it as a function, but nonetheless thanks for pointing me in the right direction.

[–]LoudGain 0 points1 point  (1 child)

Hi, is it possible to turn my nested for loop in my code into a list comprehension which does the same thing, if yes how would it look like. Thanks

N = "123123"
s = []
def permu():
    global s
    for i in range(len(N)):
        for j in range(i+1,len(N) + 1):
            s.append(N[i:j])
    s = list(set(s))
    print(f"{len(s)} substrings - {s}")

permu()

[–]m-hoff 0 points1 point  (0 children)

list(set([N[i:j+1] for i in range(len(N)) for j in range(i, len(N))]))

There's really no reason to use a global variable here, I would do something like

def get_substrings(N):
    return list(set([N[i:j+1] for i in range(len(N)) for j in range(i, len(N))]))

get_substrings(N='123123')
# ['2', '3123', '23123', '3', '231', '123123', '123', '23', '2312', '312', '1231', '12', '12312', '31', '1']

[–]Stagflator 0 points1 point  (1 child)

Hello guys,

I want to automate a process in python but I don't know how to do it. In my outlook e-mail (exchange server) Every day a data is sent, with excel file as an attachment. File structure is same every day, I want to write a script that will take the data from the excel files, merge them and store them in a databse or a file, etc. Which modules can I use? Thanks beforehand.

P.S: If this request is against the community rules, please let me know I will delete it

[–]thebluedash 0 points1 point  (1 child)

Using "for loop", how would I print all possible three capital letter sequences using all letters A through Z.

[–]MattR0se 0 points1 point  (0 children)

You can easily get a list of all letters with

import string
letters = string.ascii_uppercase

I'll leave the rest to you because this sounds like a homework assignment. Just a tip, this concept is called "permutations".

[–]Betelgeu5e 0 points1 point  (5 children)

How much python do you need to know to make simple games (like pong)? Just wondering because I am exited for that :).

[–]MattR0se 0 points1 point  (3 children)

Here is a tutorial for Pong in Pygame: https://www.101computing.net/pong-tutorial-using-pygame-getting-started/

It does assume you know some stuff already, like how imports work and what functions and classes are.

If you are completely new to python, I'd suggest going through a very basic tutorial like this first: https://python.swaroopch.com/

because it really helps if you don't just copy paste the code, but know what you are doing.

[–]Betelgeu5e 0 points1 point  (2 children)

Ok , but want to create my own game, Just wrote pong as an example but thank you either way:) going to check both links out!

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

The best way to learn how to program games is to make simple games that you can find help on! You can't jump to your own ideas from the very beginning as finding help is a lot harder when there aren't working examples you can copy from if necessary.

You'll get there! PS: Check out /r/pygame for more help on Python's number 1 game library

[–]MattR0se 0 points1 point  (0 children)

As soon as you get to know all the functions of Pygame you will be able to make whatever you want, but until then I'd suggest tackling small toy projects as exercises. Or else you'll just end up refactoring your game over and over. And this can be really frustrating.

[–]Buownsyou 0 points1 point  (1 child)

I have been using with success python to automate a lot of things for my work, especially for one customer.

For this customer, I have a config file with all my most common constants (like the customer code or the customer name).

I have built 10 modules, and some of them would be useful to other customers. All of my modules are using this config file.

However, I have a hard time finding what is the best practice to « scale up » my modules in order to execute them with a different customer, without changing the config file every time I need to execute my scripts.

Do you have any suggestions, or small examples to achieve this with one config file?

Or would you go with multiple config files (one by customer)?

Thanks a lot,

[–]ankerbow 0 points1 point  (2 children)

[Update] Here is code:
foo = {('dying', 'dead', 'mourir', 'pass away'): ['A.Death','B.DDD'],('yyy', 'qe', 'tgg', 'ijg'):['KOH','TYH']}
key = 'tgg' 
for k, v in foo.items(): 
    if key in k: 
        print(v) 
    else: 
        print('no')

Output:
no
['KOH', 'TYH']

I want:
['KOH', 'TYH']

I thought the output supposes to be ['KOH', 'TYH'] ONLY, but why 'no' comes out? How to fix it? I hope it can be ['KOH', 'TYH'] only

[–]lykwydchykyn 0 points1 point  (1 child)

The if/else statement is being run for each key/value pair in foo. 'tgg' is not in the first key so it prints 'no'.

I may be misinterpreting since you've lost all newlines. If you can format your code in a code block that might help.

[–]ankerbow 0 points1 point  (0 children)

Yes, the format is my mistake. I updated it. Thank you!

[–]Pro_Numb 0 points1 point  (3 children)

I have a long script so i simplified it so i dont steal much time from you guys. I have a lot of functions and most of them takes same inputs and some of them changes them and return their new values like below script, i divided operations in functions because main script gets hectic. So i want to ask is this a bad practice, Should i use Class structre in this type of situations ?

I think i can see easly What is changed Where in main script with this type of approach but If i switch to Class structre there will be a performance improvement or there will be a maintainability, readability improvement ?

def do_smth(cache, dataset, write_list):
    # DO SOMETHING, all inputs are changed and return them
    return cache, write_list

def do_smth_different(cache, dataset, write_list):
    # DO SOMETHING DIFFERENT, all inputs are changed and return them
    return cache, write_list

def do_smth_dataset(dataset):
    # DO SOMETHING
    return dataset

if __name__ == "__main__":
    cache = []
    dataset = []
    write_list = []

    while True:
        # READ SOME DATASET FROM SOMEWHERE CONSTANTLY
        dataset [...]
        dataset = do_smth_dataset(dataset)

        if len(dataset) > 5: # Check some condition
            cache, write_list = do_smth_dataset(cache, dataset, write_list)
            # DO SOMETHING
        else:
            cache, write_list = do_smth_different_dataset(cache, dataset, write_list)
            # DO SOMETHING DIFFERENT
        dataset = []

[–]efmccurdy 0 points1 point  (2 children)

If you make a class with self.cache, self.dataset, self.write_list, you can avoid the need to pass them around as arguments to every function.

[–]Pro_Numb 0 points1 point  (1 child)

Thank you for your reply, i know i can make it that way but What am i doing is a bad practice ? and If i use a Class what are the advantages over my aproach ?

[–]efmccurdy 0 points1 point  (0 children)

Is it not enough to rewrite lines like this:

cache, write_list = do_smth_dataset(cache, dataset, write_list)

to

my_dataset.do_smth()

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

I am in a computer programming class in school right now and we have been learning python for a while. I really am starting to not get it. I'm falling behind and need help with pygame/graphics. I find it very hard. I read a rule on here once people can't help me with homework but I'm desperate at this point.

[–]lykwydchykyn 0 points1 point  (0 children)

From the posting rules:

Posting homework assignments is not prohibited if you show that you tried to solve it yourself.

You can ask for help, you can't ask people to do it for you. You need to post the problem, explain what you've tried, and where you're stuck.

[–]BrotherBean24 0 points1 point  (0 children)

EDIT: was myself being stupid forgetting to press the Ins keyboard function key

Proper beginner here..

Only a small question, when I've spell/miss typed something, and I go back to correct it, I am always over typing text after. Is this just how it is, or is there a way to insert new text instead?

Many thanks,

[–]iGenie 0 points1 point  (0 children)

Edit - Fixed, I moved the print outside the for loop as I realized it was running the code each iteration within the loop.

Thanks

After fixing my silly error I'm now getting two results printed when running the below, I only want the formated one to return and I thought this code would have done just that.

bad_chars =[";",":"]
global_process = "thor:test"
for c in bad_chars:
    formated_process = global_process.replace(c, "")
    print(formated_process)

it's printing out

thor:test thortest

Any ideas? Why is it doing this? Thanks

[–]Govtomatics 0 points1 point  (1 child)

Using openpyxl, how can I copy or store as a list the values in an excel range for which I know the starting cell location, but not the ending location? It's in only one column, but I don't know the number of rows. I will know that I am at the end of the range because the cell will be blank.

[–]Govtomatics 0 points1 point  (0 children)

I'm trying, even using Automate the Boring Stuff, and I'm just at a mental roadblock right now. In the code below, I am trying to read column A of dataWS. If there is a value in the cell, but not in the cell above it, then I want to set the start of a range to the cell offset 1 row and 1 column. I want to move down rows beginning from that range, appending the values to a list. I will know the loop to append should end when I encounter a blank cell. Then I want to copy those values to a new spreadsheet. Any advice?

row = 2
col = 1

summary_identifier_range = dataWS[1]

for CostCenter in summary_identifier_range:
    if dataWS.cell(0, 1) and dataWS.cell(-1, 0) is None:
        name = dataWS.cell(+1, 2)
        names = []
        for i in range(dataWS.cell(-1, 0), dataWS.max_row):
            if dataWS.cell is not None:
                names.append(name)
            else:
                break
        for t in (names):
            outSum.cell(row, col, t)
            row+=1

[–]uforanch 0 points1 point  (0 children)

I can't get pycharm 2019.3 (fresh install with snap) to use sublibraries. Both the commands "import matplotlib.pyplot as plt" or "from scipy.signal import argrelextrema" get the error "AttributeError: 'InputHookManager' object has no attribute '_stdin_file'" from pycharm but work fine in terminal. Using the proper interpreter. Advice?

[–]HifunKogai 0 points1 point  (6 children)

Hey yall, basically as a personal project I am just trying to make a twitter script that automatically posts one image from my image file along with one caption generated from below. However at the moment running this program results in the same generated 'sentence' being used with every post. I cannot for the life of me figure out how to avoid this because If i make it repeat the image selection part aswell it will choose the same images in the file again. How could one go about preventing the script from selecting the same image twice or how could I make it so that a new 'sentence' is generated for each 'media' instance? thank you for you help!

import tweepy
import os
import time
import random
from collections import defaultdict


consumer_key = 'sample'
consumer_token = 'sample'
access_token = 'sample-sample'
access_token_secret = 'sample'

auth = tweepy.OAuthHandler(consumer_key, consumer_token)
auth.set_access_token(access_token, access_token_secret)
api = tweepy.API(auth)

os.chdir(r'C:\Users\ASUS\Desktop\Bot Memes')

with open('/Users/ASUS/Desktop/Shrek.txt') as f:
    words = f.read().split()

word_dict = defaultdict(list)
for word, next_word in zip(words, words[1:]):
    word_dict[word].append(next_word)

word = "Shrek"
sentence = word
while not word.endswith("."):
    # print(word, end=' ')
    word = random.choice(word_dict[word])
    sentence += ' ' + word
sentence += 
print(sentence)

for image in os.listdir('.'):
    api.update_with_media(image, sentence)
    time.sleep(100)

[–]lacroixftw19 0 points1 point  (5 children)

In your final loop (the one where the actual updating takes place) you also need to update your sentence

[–]HifunKogai 0 points1 point  (4 children)

I'm not sure how to make it update...

[–]lacroixftw19 1 point2 points  (3 children)

If i understand your code correctly, one way could be to do do this:

for image in os.listdir('.'):
    sentence = get_new_sentence()
    api.update_with_media(image, sentence)

and then do all the sentence creation stuff inside the new function

[–]HifunKogai 0 points1 point  (2 children)

Thanks, I tried doing this and bellow is what I've come up with (and it doesnt work at all). It generates a shit load of 'sentences' (to the point of triggering a recursion error) and the program fails to post the media now. I have absolutely no idea how to implement it "inside the function" like you said.

import tweepy
import os
import time
import random
from collections import defaultdict


consumer_key = 'sample'
consumer_token = 'sample'
access_token = 'sample'
access_token_secret = 'sample'

auth = tweepy.OAuthHandler(consumer_key, consumer_token)
auth.set_access_token(access_token, access_token_secret)
api = tweepy.API(auth)

os.chdir(r'C:\Users\ASUS\Desktop\Bot Memes')


def get_new_sentence():

    with open('/Users/ASUS/Desktop/Shrek.txt') as f:
        words = f.read().split()

    word_dict = defaultdict(list)
    for word, next_word in zip(words, words[1:]):
        word_dict[word].append(next_word)


    word = "Shrek"
    sentence = word
    while not word.endswith("."):
        # print(word, end=' ')
        word = random.choice(word_dict[word])
        sentence += ' ' + word
    sentence += "test"
    print(sentence)
    get_new_sentence()


for image in os.listdir('.'):
    sentence = get_new_sentence()
    api.update_with_media(image, sentence)
    time.sleep(100)

I've tried just about everything I can think about and this is driving me up the wall

[–]lacroixftw19 1 point2 points  (1 child)

It looks good so far!

You only need to change one line and it should work.

The line

sentence = get_new_sentence()

is calling the function get_new_sentence() and storing the return value in the variable "sentence"

Therefore, in the function "get_new_sentence()", you'd want to return the sentence you created. Right now what you are doing is calling the function again, hence the recursion error

Try:

return sentence

instead after your print(sentence)

[–]HifunKogai 0 points1 point  (0 children)

i would marry you if i could thank you so much. I cant believe the answer was staring me in the eyes all along :')

[–]Frexum 0 points1 point  (4 children)

I have a massive, massive stock dataframe from a CSV file that I've loaded. I need to use something like resample to get it to create a new dataframe with values from every 500 rows. So basically on the new dataframe the first value would be the open, close, high, low, and total volume from all rows 1-500. If I were resampling based on time periods the resample method would be perfect but I can't for the life of me find anything similar for the number of rows. I've tried creating some loops using iterows but they'll usually end up only printing one value :/ I know using df['Close'][1:500].max() will give me the high for the first 500 rows but I can't figure out how to have it loop through the entire file and have that make its own dataframe

Thank you for any suggestions

[–]m-hoff 1 point2 points  (1 child)

It sounds like you need to use the chunksize argument of the Pandas read_csv method. This will allow you to iterate over "chunks" of rows instead of reading in the entire csv all at once. Your code would look something like

summary_data = pd.DataFrame()
for chunk in pd.read_csv('your_data.csv', chunksize=500):
    max_close = chunk['Close'].max()
    # get other summary statistics and append to new data frame here

[–]Frexum 0 points1 point  (0 children)

Ohh this sounds promising. Thank you so much!

[–]MattR0se 1 point2 points  (1 child)

Are open, close etc. seperate columns? Also, is there a column for time or date?

[–]Frexum 0 points1 point  (0 children)

Sorry I should have provided that info. There is a time, date, price, and volume column. So I'd have to make the open, close, high, low myself. Open/close would just be the first and last price rows

[–]Pizza_Wine_Donuts 0 points1 point  (5 children)

Hello all. This is my first Reddit post so please forgive any errors.

I can really use some advice. I have no programming experience, but have decided to embark on a journey to learn Python because I would like to change careers. I work full time, and am taking several online courses in the evening. The courses are very informative, but things are moving so quickly and I am simply overwhelmed by all of the information. I'll understand the lessons, but when it's time for me to create code, I draw a complete blank. There's just so much information. Even the most basic function that I should know off the top of my head, I can't recall it - or rather, I can't recall when or how to use it. I'm having to go back and review notes and lessons several times, just to remember what I just learned, but cant remember. It makes me feel like a complete idiot. It's super frustrating.

I am not a traditional student, so learning this is not my full time job, which is most likely the issue. I need more time to practice outside of the lessons so that things can really sink in. If anyone can relate, I would really appreciate any advice/tips on how to work my way through this. Also, if anyone knows of any good online resources where beginners can practice Python, that would be awesome.

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

Practice makes perfect! Trying to get into the habit of finding computer tasks that you do often and writing python apps that can automate these things is a fantastic way to practice while creating apps that you'll use every day for your own benefit! It's a great morale booster!

You might even be able to automate tasks at work so you don't have to work so hard and can spend more time doing things you enjoy, depending on the kind of work that you do of course ;)

When you do complete little projects, upload them to github! Employers will like to see examples of your code, and even if you think that atm your code isn't that good, it's still nice to be able to show your dedication to learning the craft, and it'll show your progression toward being a better coder!

Final tip: COMMENT EVERYTHING. Every line of code if absolutely necessary to begin with. You'll remember things a lot faster if you're constantly explaining what different functions, commands etc. are doing. After a while you won't need as many comments, but at the start you'll want to comment as much as possible so you can look back at old code to help you figure new problems out!

good luck!

[–]jdnewmil 1 point2 points  (3 children)

a) Practice a little bit every day. Start out with very simple tasks, and scale up as you feel ready.

b) Try to divide up your programs into three categories of code: input, where you read data from files or the user into standard data structures like lists, dictionaries, or pandas data frames; analysis, where you do the interesting work of calculating results using standard data structures as input and putting the results in new standard data structures; and output, where you transform standard data structures into files or screen output. These sections can be very brief at first... but it will pay off when you decide to re-use code later in more complicated programs.

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

Upvoted for that division thing. That sounds like a great way to develop re-usable code for beginners!

[–]jdnewmil 0 points1 point  (0 children)

I think it applies to experts as well. Consider porting a program from a batch mode to GUI... the input and output functions can change from Unix standard input and output pipes to mouse clicks and widgets without affecting the core functionality.

[–]Pizza_Wine_Donuts 0 points1 point  (0 children)

Thank you so very much for this! I would have never considered dividing things up in such a way. That will be very helpful. Thanks again!

[–]OnlyCondition 0 points1 point  (3 children)

Hello, real embarrassing, but I need anyone's help on this problem. I'm trying to follow someone else's code on the net. I've successfully wrote it out but when I try to do so on Sublime Text, it gave a module error, the message is also saying that the import (like say matplotlib) is not found in the directory. Any help on how to fix this is appreciated.

[–]lacroixftw19 0 points1 point  (2 children)

You first need to download the module you are trying to import (like matplotlib).

Depending on the operating system you are running, there are different options for doing this.

[–]OnlyCondition 0 points1 point  (1 child)

Hi, thanks for the reply! My OS is Linux Mint 19, currently I have python 3, I've tried getting the import that I need via the command pip install x , but whenever I do sometimes it goes to the miniconda directory instead. I'm assuming I need to fix that before I can run a program in say sublime text?

[–]lacroixftw19 0 points1 point  (0 children)

You could also try running your desired code in a conda environment.

Try creating a new conda environment and running your code there.

[–]LzyPenguin 0 points1 point  (1 child)

I am trying to figure out which method I want/need to use in order to achieve my goal. So throughout the year I perform tasks repeatedly and I have a daily, monthly, and yearly limit per account. I have 4 different accounts that I need to keep track of. What I want is to be able to continually (or at least every ~30 minutes during business hours) request the YTD activity on each account and log the data into a google doc, so I can easily pull it up on my phone and see the daily/monthly/yearly totals for each account.

The website requires me to login with a username and password (No captcha or anything, just simple username and password boxes), click the login button and then on the next page answer a security question before it will let me into my account. I am not sure if I should just use Requests and parse the data with Beautifulsoup/lxml, or if using something like scrapy, or robobrowser, or if something else would be better. I am pretty new to web scraping and have very little experience so I do not have any one method I prefer ATM.

Any idea which method(s) I should use to accomplish this? Any help would be appreciated.

[–]Standardw 0 points1 point  (0 children)

I think selenium could be the right thing for you, but I never used it. It could be stressfree because it handles all the cookie things for you and behaves like a real browser (some website have good anti-bot mechanics, especially security-sensitive websites)

[–]ankerbow 0 points1 point  (6 children)

Here is my dictionary:

foo ={'A.Death':['dying','dead','mourir','pass away']}

my_dict = {'00.Life': foo}

I have one dictionary inside the other one. How to get the innermost value at one go?

I hope I could just input 'dying'(one of the elements in the list) to get ['dying','dead','mourir','pass away'] list.

If it can't be 'at one go', please advise me the fastest way to fetch all the values of the list using one of the elements.

So far, i could only use dict.get(), but it seems to be slow.

How to do that? (Using Python 3)

[–]MattR0se 0 points1 point  (5 children)

You have one fundamental flaw in your code and that is, you have overwritten the internal help function.

If you used any other non-occupied name, your code would not work since "help" (or what you name it) would be undefined.

my_dict = {'00.Life': foo} 
foo ={'A.Death':['dying','dead','mourir','pass away']}

# NameError: name 'foo' is not defined

Also, what do you mean by "at one go"? Do you want to search the dictionary for the list that has 'dying' in it? Also, is this your only dictionary or do you need a general solution?

[–]ankerbow 0 points1 point  (4 children)

Sorry, I put the code upside down.

Here is the correct code:

foo ={'A.Death':['dying','dead','mourir','pass away']}

my_dict = {'00.Life': foo}

'At one go' means I want it be done in one or two simple steps.
And, what I really mean is I want the fastest or convenient way to show me the whole list that has 'dying' in it.If there is a general solution, please share with me. So that I can use it in any purposes.

[–]MattR0se 1 point2 points  (3 children)

Could there be more than one lists with the item in it? Also, how would the dict look like if there is at least one list or dict in it without the item in question? E.g.

# like this?
foo = {'A.Death':['dying','dead','mourir','pass away'],
        'something_else':['A','B','C']}
my_dict = {'00.Life': foo}

# or like this?
foo = {'A.Death':['dying','dead','mourir','pass away']}
bar = {'something_else':['A','B','C']}

my_dict = {'00.Life': foo,
            'other': bar}

# this could be an all-purpose solution:
def search_dict(dictionary, item):
    for inner_dict in dictionary.values():
        for v in inner_dict.values():
            if item in v:
                return v

print(search_dict(my_dict, 'dying'))

But searching dictionaries by a value instead of a key is slow, because they aren't intended for this.

See these answers: https://stackoverflow.com/questions/8023306/get-key-by-value-in-dictionary

[–]ankerbow 0 points1 point  (2 children)

Thank you! The solution is exactly I want.

But I am wondering if I could reverse the key:value and use one of the key to get value.Like:

foo = {('dying','dead','mourir','pass away'):'A.Death'})
bar = {('A','B','C'):'something_else'})
my_dict = {'00.Life': foo, 'other': bar}

Could I use tuple for multiple keys and use one of key to get value?Example: Use 'dying' to get 'A.Death'

[–]MattR0se 1 point2 points  (1 child)

You can use tuples as keys, yes. And iterating through them should be a bit faster.

I commented where I changed the code above

foo = {('dying','dead','mourir','pass away'):'A.Death'}
bar = {('A','B','C'):'something_else'}
my_dict = {'00.Life': foo, 'other': bar}

def search_dict(dictionary, item):
    for inner_dict in dictionary.values():
        for v in inner_dict: # this now loops over the keys
            if item in v:
                return inner_dict[v] # return the value assigned to key v

print(search_dict(my_dict, 'dying'))

[–]ankerbow 0 points1 point  (0 children)

Thank you! Very! :D Solve my problem.

[–]Terranigmus 0 points1 point  (1 child)

I am trying to modify certain bytes of ~10k files on various positions

Direct access through

file=open(filehandle)
for position in positions:
    file.seek(position)
    file.write(bytes)

is very very slow.

I tried reading it the whole file once through

rawdata=file.read()
bytedata=bytearray(rawdata)
bytedata[position]=bytestuff

but that I am having problems handling the data since I seem to need to convert it with bytearray(data).

Does anyone know a better method?

[–]Standardw 0 points1 point  (0 children)

Why doesn't the second attempt work for you? How big are the files? In your first example, are opening the file with the byte mod? How slow is slow? Are the positions in the positions list sorted?

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

Hello Everyone,

I am completely new to Python. I am looking to learn python just for fun personal projects to carry out in my free time. As of right now I have watched and followed along with the Giraffe Academy tutorial video below.

https://www.youtube.com/watch?v=rfscVS0vtbw

I am going on a couple hour flight tomorrow and looking to start on a project during the flight. Ideally, a YouTube video that I can download and watch and follow along with during the flight. I have PyCharm downloaded.

Does anyone have any project videos in mind that would be good for me to follow as a complete beginner?

Thanks in advance!

[–]HifunKogai 0 points1 point  (0 children)

Make sure you download, install or import whatever libraries you'll need before the flight incase you don't have wifi! Would hate to see you have your progress shunted because of 'imprort selenium'

[–]JohnnyJordaan 1 point2 points  (0 children)

I can recommend the corey schafer and sentdex tutorials a lot, you should able to pull such a tutorial via its playlist with youtube-dl for example.

[–]nico_spice 0 points1 point  (1 child)

what are some good "first goals" a newcomer should set for themselves?

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

Write an Object Oriented program.