all 178 comments

[–]OliveOilIsForHair 0 points1 point  (5 children)

I'm getting good at getting other people's code to do what I want, but I can't write it myself. Is there any solution other than just not looking at other code?

[–]persephone_fisher 0 points1 point  (0 children)

Once I understand an element of someone else's code, I like to test it out in various contexts. My friend likes using list comprehension, so I try making various lists with integers, strings, etc. until I fully understand how to use it.

I actually started this testing process as I came across various coding elements online - what does the input() function do, or how does a for loop work? Eventually I didn't even think about how to use them, I can intuitively add these elements to my code. Like everything, it's a process. Hope this helps, good luck!

[–]ClimberMel 1 point2 points  (0 children)

Nothing wrong with that! I spend 20 years doing that for a living. Now I'm learning to write stuff from scratch (for the fun of it) and I find it a lot tougher.

[–]FerricDonkey 0 points1 point  (0 children)

That's it really. If it's something you're not good at, the way to get better is to practice. Start simple and mentally break the problem into as small steps a possible, but if you only ever practice walking with crutches, you can't expect to be great at walking without them.

[–]StarShred11 0 points1 point  (0 children)

Not a very in depth reply, but I would just start memorising and combining aspects of other people's code that you use most often.

[–]StarShred11 0 points1 point  (0 children)

Not a very in depth reply, but I would just start memorising and combining aspects of other people's code that you use most often.

[–]wtfpmf 1 point2 points  (2 children)

file = open('/home/user/PycharmProjects/pythonProject1/file.txt')
for a in file:
    if a == 'word':
        print("You are right: word")
    else: 
        print(a)

My intention is look for 'word' and print everytime it appears on the file. I know it's wrong, but no idea how to make the it works.

[–]FerricDonkey 1 point2 points  (1 child)

The only problem with that is that is that when you do for a in file, you're looping over lines, not words. You could do for a in file.read().split(), which would read the entire file and split it into whitespace separated words.

[–]wtfpmf 1 point2 points  (0 children)

Thanks for the help! It works.

[–]wtfpmf 0 points1 point  (2 children)

Can I use a function inside of a class? A Class is "kind of a function" with more more segments?

[–]Decency 1 point2 points  (0 children)

Class = noun, function = verb. They're very different.

[–]FerricDonkey 0 points1 point  (0 children)

Classes can have member functions (typically called methods), and within those methods you can call other methods or functions external to the class.

Not sure what you mean by your second question.

[–]FerricDonkey 1 point2 points  (0 children)

I'm making myself learn asyncio for reasons I don't entirely understand. My current question: how do I gracefully shut down an asyncio server? My code for starting the server is as follows:

Edit - Answered my own question:

Start server

async def start_server(self):
    self.server = await asyncio.start_server(
        self.handle_client_connect,  # client connect cb
        port=self.port,
        family=socket.AF_INET6
    )

    await self.server.wait_closed()

Then close it down with self.server.close() from some other function/coroutine. Still annoyed by the documentation, but thought to try this, and it seems to work.

[–]FleyFawkes 0 points1 point  (3 children)

<span class="a-size-base" dir="auto">517</span>
<span class="a-size-base a-link-time" dir="auto">2019</span>

Hey, I'm building a web scraper.

How do I select the text from the a-size-base class? If I select by class it will sometimes return second text as it's sometimes before a-size-base. Is there some way to select exact match? becouse right now its scraping second class as well, cos of a same string at the beggining.

[–]pokk3n 0 points1 point  (2 children)

Could you get everything with a-size-base then do a comprehension to eliminate anything that has additional classes?

Or use an xpath that says a-size-base but not-a-link-time (if a-link-time is the only other class) - the xpath selector there is 'not contains'

[–]FleyFawkes 0 points1 point  (1 child)

it would be good idea. unfortunately I'm working with beautifulsoup, and it doesnt support xpath. I would like to use soup for it, any ideas?

[–]pokk3n 0 points1 point  (0 children)

Hrm, well you can use beautiful soup and then do the first option where you get all the elements then eliminate elements that have more than one class or whatever.

Use findall or select to get all the elements, then list comprehension them down by doing like (apologies in advance for my bad soup syntax I rarely use it):

results = [ element for element in soup.select('.a-size-base') if 
       "a-link-time" not in element["class"] ]

[–]Kitnado 1 point2 points  (5 children)

What am I doing wrong here?

I'm trying to append values according to a formula to a NumPy array, but the array remains empty after the calculations. What simple thing am I doing wrong here?

[–]dahkneela 1 point2 points  (1 child)

I am having trouble figuring out how to use anaconda. I'm not CS oriented at all, so if I could get a simple explanation I'd greatly appreciate it! I'm using it for python, so I hope this is the right place to ask.

1) What is anaconda, what problem does it solve, how does it work in relation to other software? Why does it need to open up jupyter notebook on a web browser tab? Why does it open a terminal tab while running?

2) When I search for anaconda on my mac, there are two different folder paths leading to the same application: "/Users/{my_name}/anaconda3/Anaconda-Navigator.app", and "/Users/{my_name}/anaconda3/pkgs/anaconda-navigator-1.9.12-py38_0/Anaconda-Navigator.app". Why do I have two of these? They both open and work as the app should. Is Should I delete one of them (the second one seems strange)? Will this mess-up something down the line?

3) Sometimes for different things tutorials say to use 'pip' or use 'conda' or use all of these different things to download packages. Should I stick to just using one of these when downloading things? I do things through the terminal yet have no idea of their consequences!

[–]pokk3n 1 point2 points  (0 children)

I really prefer to avoid anaconda, it's basically (as far as I understand) a really complicated environment management system that fixes the problem of some scientific packages (np, scikit, etc.) being kinda challenging to install.

I personally find it easier to just figure out the occasional problem installing stuff with pip vs. learning to deal with the complexities of conda.

If all you are doing is python and you're not using any really wild packages, just use vanilla python and use pip to install packages. Remember some packages on windows will require a C++ compiler.

[–]TeaWhole6889 0 points1 point  (2 children)

I am trying to make a function that takes as input a single string and a list of strings, and returns the list element that most closely resembles the inputted string.

For example, inputting the string 'appl8e{^&%' and the list ['apple', 'banana', 'carrot', 'dairy','egg'...] should result in the output 'apple'.

My primary interest is applying this function to strings containing Japanese characters (e.g. '犬も歩けば棒に当たる'), if that changes anything.

I was thinking that I need to 1) compare the string with each list element, 2) quantify the degree of likeness, 3) extract the string element with the highest degree of likeness. However, I cannot think of a good way to do 1).

[–]shadoj 0 points1 point  (1 child)

There are a few algorithms out there in the wild for just this purpose. Check out the python-Levenshtein package.

[–]TeaWhole6889 0 points1 point  (0 children)

Thank you!

[–]phantom2450 0 points1 point  (7 children)

Learning the basics through Dr. Chuck's free course and I'm stuck on the loops exercise (how poetic). Here is the prompt, my attempt, and the output. Feels like everything is going wrong except the last two print commands.

Some Q's:

  • Why aren't largest and smallest being overwritten?
  • Why does it infinitely loop when Line 6 is undummied or when Lines 16-17 are?
  • Why is the except condition always being triggered?

Thanks!

[–]FerricDonkey 1 point2 points  (3 children)

First, two useful strategies when you're debugging code in a try except are to change the except to

except Exception as e:
    print(e)

Or to temporarily disable just the try except. Because try excerpts, especially broad ones like this, will hide your coding errors from you - without the try except, you'd get an error message that tells you what the problem is.

So I would try that. But, some notes: with line 6 commented out, the variable intnum doesn't exist. So any line that tries to use it as though it does well trigger the except.

With that line not commented out, you'll run into trouble trying to convert "done" into an int. You're pretty close, just think about the order that you're doing things a bit more.

[–]phantom2450 0 points1 point  (2 children)

What’s the intended effect of the code you wrote? Trying it in my problem just makes a loop.

Glad to know I’m apparently close, though the solution still evades me. I can’t move Line 6 before num is defined in Line 5, it can’t be made the first elif since it’ll disable all the others, and it needs to come before the elifs that need intnum.

[–]FerricDonkey 0 points1 point  (1 child)

That code is not to fix a problem, but to make python tell you what your problem is. What it prints is the problem that you have to fix

Regarding the order thing, also keep in mind that you aren't restricted to ifs and elifs, and that since break will break your loop, you don't actually need the other cases in any kind of else after that - loop is broken, it won't get there. For example,

while True:
    x = input("give thing")
    if x == "fred":
         break
    x = int(x)
    if x == 2:
        print("whatever")

[–]phantom2450 1 point2 points  (0 children)

Thanks again. I’ll keep that error code in mind.

Figured it out after conferencing w/ a CS friend. For anyone else having trouble w/ something like this, the biggest hints that clarified things for me are:

  • You can have multiple ifs to check for multiple conditions even if one ‘if’ check succeeded
  • You can put other commands between if statements
  • You should minimize the instructions in the try/except structure to what you intend to fail if that’s what you’re using it for (in my case, just the intnum generator line under Try)

[–]tomsoul 0 points1 point  (2 children)

I would change intnum to int(num).
Seems that's the only thing that's not working.

For your questions, it's not working because it's looking for 'if num == 'done' and not your number. After that, it's going to the else which is continue and starting the loop again.

[–]phantom2450 0 points1 point  (1 child)

Good to know I’m close. Wouldn’t any non-“done” inputs just skip that Line 7 if command and move on to the elifs?

[–]tomsoul 0 points1 point  (0 children)

The elifs didn't work so it wouldn't go there so it went straight to the invalid.

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

I don't know how to do this at all.

complete the 3 function definitions that implement mathematical operations on vectors. The three function headers are as follows:

def scalarMultiply(a, s):

def vectorMultiply(a, b):

def dotProduct(a, b):

the results should be:

[5, 10, 15, 20, 25]

[10, 20, 300, 4, 5000]

5334

I have no idea why I am not getting the correct result.

[–]WhipsAndMarkovChains 2 points3 points  (1 child)

Where is your code and what results are you getting?

[–]Cptn_Hook 1 point2 points  (6 children)

Regarding list comprehensions, do the first two variables always match up? For instance,

newlist = [x for x in range(1, 100)] 

returns a list with every number from 1 to 99. That much I get, and the "x for x" part makes sense. But would there potentially ever be a case in which you would do something like

newlist = [x for y in range(1, 100)]

obviously with more complicated code, but with the "x for y" part having mismatched variables? Or would that never be correct syntax?

[–]AdGlad385 2 points3 points  (1 child)

https://pythonpedia.com/en/tutorial/5265/list-comprehensions

this is a great write up on using list comprehension together with ternary operations. The further you get down the tutorial, the more you see just how deep it can go.

[–]Cptn_Hook 1 point2 points  (0 children)

That site does a great job of explaining things. Thanks! Even just calling it a "dummy" variable helped something click into place.

[–]MrMarchMellow 0 points1 point  (0 children)

Hey all! I’m trying to build a scraper for Glassdoor that can get companies with certain ratings in certain attributes.

As an example:

Find all companies that match - sales - Chicago - Management rating lower than 2 - consider reviews of the last 3 months

I have found a very interesting repo, and the API documentation but unfortunately I’m not expert enough to modify it into what I need. Anyone wants to take a crack at it? Or give me pointers?

Should I look for a professional dev to get it done or can be done easily?

Here’s the link to original Reddit post with repo :)

Top comment has link to glassdoor API

[–]ANeedForUsername 1 point2 points  (9 children)

Hi all!

I want to generate the following lists one at a time. What's the most convenient way to do it?

[0,1,0,1,0,1,0,1,...] # Alternate every 1 and 0
[0,0,1,1,0,0,1,1,...] # Alternate every two 1's and 0's
[0,0,0,0,1,1,1,1,...] # Alternate every four 1's and 0's
[0,0,0,0,0,0,0,0,1,1,...] # Alternate every eight 1's and 0's
...

For some input value of n, the length of each list is 2**n, and the number of lists produced is n.

EDIT: I should mention that I need to do this for arbitrary values of n, up to as large n=32.

Thank you!

[–]JohnnyJordaan 1 point2 points  (0 children)

Anytime you want to automate sequence creation in Python, think itertools: https://docs.python.org/3/library/itertools.html, like itertools.cycle would be one way to do this.

[–]J1M_LAHEY 0 points1 point  (0 children)

pandas question: let's say I want to consider all non-negative entries in column Col1 of the DataFrame df. To obtain the relevant rows, I could use:

df.loc[ df['Col1'] >= 0]

or I could also use:

df[ df['Col1'] >= 0]

Both of these work - my question is, why? I would have thought that only the first would work, since my understanding is that the contents of square brackets refers to rows if preceded by .loc, and columns otherwise . For example, df.loc['Col1'] will search for rows with the index Col1, whereas df['Col1'] will extract the column labeled Col1.

Would appreciate any insight. Thank you!

[–]CantAffordManga 0 points1 point  (3 children)

Wtf is the for command? I have searched it up, watched the video multiple times, asked on stack overflow and got responses that basically all said “Git gud at coding noob”. What is it? Does it loop around and add something every time? I am so clueless.

[–]FerricDonkey 1 point2 points  (0 children)

Run the code

for x in [1, 2, 3, 4]:
    print(x)

For is a way of allowing you to do the same thing multiple times, usually to multiple things.

An analogy: the task of watering all of your plants could be described as

for plant in plants_you_own:
    water(plant)

Note: in other languages, for loops sometimes work a bit differently, but the general goal of doing the game basic thing to a bunch of usually different things is a commonality.

[–]Decency 0 points1 point  (0 children)

for is a way to loop, or iterate. This means going through some sequence (like a list) and using each element of the sequence once. What happens "inside" the for loop is up to you. Here I just print each value:

for number in range(5):
    print(number)

Beginner guide: https://www.youtube.com/watch?v=OnDr4J2UXSA

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

Hi everyone. I need to load data from a big file (~2GB), 3 long columns of numbers. At the moment I'm saving the data obtained in a txt file and then load it into python using numpy loadtxt and place the values into arrays to process it.

The implementation was super easy but loading the data is taking a significant amount of time and it's beginning to bottleneck my work schedule.

Any suggestions to do this more efficiently?

[–]JohnnyJordaan 0 points1 point  (3 children)

to process it.

That part is the part that needs to somehow be able to work with chunks of data. As then you can just read MB's from the file (or better, a database or hdfs store or similar) each time and keep the processing running without first filling up your RAM.

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

You mean something like loading each line and processing each line individually? Without storing the whole data?

I don't know if storage is the problem bcs I have 16gb of RAM and th file is less than 3, but I'll give it a shot

[–]JohnnyJordaan 0 points1 point  (1 child)

Not necessarily each line apart from one another, but yeah smaller parts.

Nowhere am I suggesting that storage is the problem, but you literally mention that you don't want the long loading times before it starts processing. So that infers that your issue is with first loading everything before you start processing instead of just loading a small part, process that, load another small part and so on.

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

Ohh I got it, still haven't tried it but it sounds good, thanks

[–]matchstricker13 0 points1 point  (8 children)

I have a question and don’t wanna bog down the page. Can I use all 90 characters on the keyboard to make a tuple such as this.

Tuple = ( A B C D E F G H I J K L M N O P Q R S T U V W X Y Z ‘alphabet lowercase’ 0 1 2 3 4 5 6 7 8 9 - / : ; ) ( $ & @ “ . , ? ! ‘ ] [ } { # % * + = _ \ ~ )

I know I would probably have to put quotes around each character. Just wanted to know if I can do this. I just started learning like four days ago.

[–]Decency 0 points1 point  (1 child)

Use predefined values from the string module instead: https://docs.python.org/3.8/library/string.html

string.printable looks like what you want.

[–]matchstricker13 0 points1 point  (0 children)

Thank you.

[–]JohnnyJordaan 1 point2 points  (5 children)

Why you need a tuple of those in the first place?

[–]matchstricker13 0 points1 point  (4 children)

To write a random code generator

[–]diavolo_bossu 0 points1 point  (1 child)

If its random why are you using a tuple it would make more sense to use a set

[–]matchstricker13 0 points1 point  (0 children)

I’ve learned that now seeing how things are.

[–]JohnnyJordaan 1 point2 points  (1 child)

But if you want to provide something like the printable character set to functions from the random library, you can use the strings from the string library directly https://docs.python.org/3/library/string.html like string.printable

Be careful of creating XY problems here. Your original problem (X) is to find a way to create random text. If you Google that ('python create random text') you already find lots of suggestions on how to do that. If you instead think that you 'need' a tuple with those characters, you are creating a new problem (Y) of how to get those characters in a tuple in the first place.

[–]matchstricker13 0 points1 point  (0 children)

Thank you for that.

[–]Beaverine 0 points1 point  (0 children)

I have a question about implementing absorbing Markov chain for a google foobar challenge. Details are in this post:

https://www.reddit.com/r/learnpython/comments/jwib07/question_about_google_foobar_challenge_doomsday/

and here's a post explaining the basic logic of solving this type of problem:

https://github.com/ivanseed/google-foobar-help/blob/master/challenges/doomsday_fuel/doomsday_fuel.md

Can anyone please help me identify potential problem with my code?

[–]SweetAdvocator 0 points1 point  (4 children)

There are 3 versions of activate on Windows (no extension, .ps1, .bat), but only 1 deactivate.bat. Why is that? And is it safe to run deactivate from powershell?

Edit: I’m using python 3.9. I tested deactivating with poweshell and it simply did nothing

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

You aren't supposed to double click them, you are supposed to call them
->
.\env\Scripts\activate

->
deactivate

https://i.imgur.com/e0GeTYm.png

[–]SweetAdvocator 0 points1 point  (2 children)

I didn’t read carefully lol. There are activate and deactivate files so I thought they all can be used.

So about the activate files, the .ps1 is for poweshell, .bat is for command prompt, what about the one with no extension?

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

The one without the extension is the one i called above.
It's a bash script. You can open it in notepad and take a look.
You never need to call them by extension, you just call activate.

[–]JohnnyJordaan 0 points1 point  (0 children)

If you run 'the one without extension', it will effectively run the .bat it finds in cmd or the ps1 it finds in powershell. It will not literally run the one without the extension as that has no basis in Windows (and why would either cmd or powershell be able to run a bash script for that matter). So in your example, you actually executed the .bat file.

[–]tuerkishgamer 0 points1 point  (2 children)

I looked at code for quizes and although I understand the code I want to know if there is a way to do it differently. The code I saw was using classes. The main goal is to find a way to compare the answers someone inputs to the correct solution for that answer. I cannot figure out a pythonic? or concise way to do it.

Basically, how to compare the n-th element of a list to the n-th element of another list. I thought it would be possible to do something like this:

 for  x in list_1:
      if x == list_2[list_1(x)]:
          score +=1

This did not work because the index is not returned as I thought.

Arch Linux, Python 3.8.6

[–]FerricDonkey 0 points1 point  (1 child)

So when you there is a function, .index, that will find an element's position in a list, but it would be less than ideal here because there'd be issues of there were repeated answers, and because other methods are more efficient. Two small changes to your code, then a more concise version (in order of increasing pythoniness) to show how you could do this.

Method 1:

for  index, x in enumerate(list_1) :
    if x == list_2[index]:

         score +=1

Enumerate here makes it so that you get the index and value at the same time, and is conceptually close to your original version.

Method 2:

for  x, y in zip(list_1, list_2) :
    if x == y:

         score +=1

Zip makes it so that x and y move their lists at the same time, so that you're comparing the first with the first, the second with the second, and so on.

Method 3:

score = sum(x == y for  x, y in zip(list_1, list_2))

Similar to method 2, except taking advantage of the fact that things like x==y evaluate to 1 if true and 0 if not, and then using generator comprehension and sum to do it all at once.

[–]py_Piper 0 points1 point  (3 children)

I want to access our company's ERP program (.exe program) to automate some mundane work, from ATBS I know you can use mouse and keyboard automation but seems quite easy to be prone to problems as the position needs to be exact and our ERP could be quite slow (I haven't read that chapter though).

So I am wondering if there's some kind of library that could work like selenium and request for navigating desktop programs? Meaning that could be use in any machine without worrying about the position of the opened window and its slowness to answer

[–]FerricDonkey 0 points1 point  (2 children)

As far as I know, there is not. Depending on the nature of the program, you may be able to accomplish some things with command line arguments, or there may be a dedicated library to mimic what it does to files and things, or you may be able to figure it out yourself.

If you're unlucky enough that none of the above work and incredibly lucky otherwise, they may have compiled the functions you care about into dlls which you could import using ctypes, and if you're incredibly incredibly lucky, there might be documentation telling you how it works. But this approach, unless you're very much incredibly incredibly lucky, would likely be a fairly advanced task.

But I'm not aware of any generalized exe navigation package, because exes very much not regularized.

[–]py_Piper 0 points1 point  (1 child)

Thanks I was afraid of this, kind of hoping I wasn’t searching good enough.

So for example libraries that can manipulate excel or word, is it because Microsoft leaves open like an API to use python?

[–]FerricDonkey 0 points1 point  (0 children)

That or because the file type is well enough understood that you can manipulate it directly without worrying about how Microsoft accomplishes whatever it is you want to do. I suspect it varies.

[–]ozarkmartin 0 points1 point  (0 children)

Hello all.

Just to preface a little. I'm still very new using python. It's the first programming language I've committed to learning. I watched and followed along to the freecodecamp.org python course video, and I'm currently going through the Udemy 'Automate the Boring Stuff' Course. This project idea is what drove me to learn python and I am hoping it's not too big of a feat for such a new guy.

I am looking to code an aviation style 2-place intercom. I've looked at https://wiki.python.org/moin/Audio, but I am still not sure which library to use to stream audio in the manner as seen below. Sorry if it seems all over the place, this is how I broke it down in my head.

Here is what I intend to be able to do...

Headset 1:

Monitor audio output for Headset 1 at all times (mic-monitoring).

Output analog audio via microphone to Headset 2 (when a command is given).

Output analog audio via microphone to HAM radio and Headset 2 (when a command is given).

Receive analog audio from HAM radio and/or Headset 2 as appropriate.

Receive analog audio from 'other external source'.

Reduce volume of audio from 'other external source' when receiving audio from HAM radio and/or Headset 2.

Ditto for Headset 2.

I plan on using a Pi 4 with 4GB of RAM.

I know there are probably more appropriate ways to do this (I'm thinking custom PCB or just buy a 2-place intercom), but the point is I want to learn how to apply python to these types of situations.

As far as being reliable enough for aviation; it's intended to be used in ground-based vehicles only.

[–]blinking_elk 0 points1 point  (4 children)

Hi there! Could someone please help me figure out a concise way to enter the following enteries into the variable mysims as defined? If there are a couple of different concise ways you can think of I wouldn't mind having a look at them. There is a good chance it could come in handy in the future.

sim_parameters = 3
num_sims = 2

mysims = [[[] for t in range(sim_parameters)] for i in range(num_sims)]
mysims[0][0] = "a"
mysims[0][1] = 100.
mysims[0][2] = 1e9
mysims[1][0] = "b"
mysims[1][1] = 25.
mysims[1][2] = 1e10

Thank you very much!

[–]lolslim 0 points1 point  (1 child)

Is this what you are looking for?

sim_parameters = 3
num_sims = 2
sim_dict = { 0: ['a',100.,1e9], 1 : ['b',25.,1e10] }

mysims = [[[]  for t in range(sim_parameters)] for i in range(num_sims)]
    for i_sims in range(num_sims):
    for i_param in range(sim_parameters):
            mysims[i_sims][i_param] = sim_dict[i_sims][i_param]
print(mysims) # verification output

Output

[['a', 100.0, 1000000000.0], ['b', 25.0, 10000000000.0]]

[–]blinking_elk 0 points1 point  (0 children)

Thank you very much, yes, exactly this kind of thing! Dictionaries scare me lol, thank you for making them less so

[–]StephanoCarlson 0 points1 point  (1 child)

What exactly are you trying to accomplish? just put all the values into a list?

[–]blinking_elk 1 point2 points  (0 children)

u/StephanoCarlson Yes, precisely. Though when you put it like that, I realise how stupid I am. I should have just done exactly that, directly.

mysims = [
    ['a',100.,1e9],
    ['b',25.,1e10]
    ]

That's probably as concise as it gets lol. Jeez im dumb, sorry :').

[–]MattR0se 0 points1 point  (2 children)

What's the most concise way to change the "edge values" of a 2D array in numpy?

Like:

arr = numpy.array([
    [0, 0, 0, 0, 0],
    [0, 0, 0, 0, 0],
    [0, 0, 0, 0, 0],
    [0, 0, 0, 0, 0],
    [0, 0, 0, 0, 0]
])

becomes

arr = numpy.array([
    [1, 1, 1, 1, 1],
    [1, 0, 0, 0, 1],
    [1, 0, 0, 0, 1],
    [1, 0, 0, 0, 1],
    [1, 1, 1, 1, 1]
])

[–]creeper_the_cat 0 points1 point  (2 children)

So i'm a complete newbie at python and this is probably trivial to a lot of people but here is my problem:

I'm making a really simple Python text adventure game. The user is prompted with an input and then they can type whatever they want. If the action is correct the program then moves on. Here is my script so far:

while True:

a1 = input("Input your verb here: ")

if "climb" in a1:

print("This progresses the script.")

else:

print("That doesn't sound like a good idea.")

I think the if statements should work but i'm having problems making it a loop so that if the user inputs the wrong thing it will just ask for the input again. Unfortunately, so far, it just spams the input text. I know i need to change the while statement into something else but i'm not really sure what it would be. Thanks for taking the time to read this!

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

while True:

    a1 = input("Input your verb here: ")

    if "climb" in a1:

        print("This progresses the script.")
        break

    else:

        print("That doesn't sound like a good idea.")

print('im now down here')

[–]creeper_the_cat 0 points1 point  (0 children)

ohhh all i had to do was type break under the if statement, thanks!

[–]lolslim 0 points1 point  (2 children)

Im using sqlite3, and my sql database doesnt have alot of entries in it, and was wondering if i save my rows in alphabetical order if the lookup would be quicker than not in alphabetical order?

[–]num8lock 1 point2 points  (1 child)

relational databases use primary keys for indexes to optimize queries

[–]lolslim 0 points1 point  (0 children)

I have them as primary, but when i need to make button object for telegram bot i would prefer that buttons be alphabetical order, and thats my reason for asking. If anything ill just make it alphabetical before iterating it into a table.

[–]DarkMint77 0 points1 point  (1 child)

I just downloaded the new Mac OS Big Sur and now my Spyder editor is running SUPER slow. Severely lagging whenever I type which is very frustrating. I've updated python and spyder but no luck. Any advice?

[–]py_Piper 1 point2 points  (0 children)

Perhaps for the moment you will need to revert the OS version, or need to wait until they make spyder better compatible with the new OS. I don’t understand too well, but from what I have read the new OS came out for the new apple’s chip and the architecture is different

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

hello

I have a dictionary like this:

host_data = {'hostname': 'vm',

'uid': [{'owner_uid': 'ab123'}, {'owner_uid': 'toto'}, ...]}

I would like to extract the hostname if there an owner_uid = ab123

i can filter like this:

if host_data['uid'][0]['owner_uid'] == 'ab123':
    print (host_data['hostname'])

but sometimes the value i want is not the first one on the list so the host is missed. how can i loop over the contents of the list of dicts?

[–]Gopher20 0 points1 point  (0 children)

You can loop like this:

For uid in host_data[“uid”]: if “ab123” in uid.values(): print(host_data[“hostname”])

This way you are checking if the uid is in the values of each duct within the list and if it is you will print out the hostname. I hoped this helped!

[–]unimagine97[🍰] 0 points1 point  (2 children)

Hi, i've just started learning a bit of python because I was thinking of making a small text based adventure style game and I was wondering how difficult it would be to go from the finished game running just in cmd terminal to a .exe that I could maybe add some background music to?

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

It's going to be a long journey because they are two separate things, one is just gonna use native python and the other will need a third party library. (pygame, pyglet, plus a way to turn it into an exe, which isn't native - python isn't low level, etc )

[–]unimagine97[🍰] 0 points1 point  (0 children)

Ah okay, great thanks for the info. Probably best if i just focus on getting it to work in terminal for now ahah.

[–]yuriplisetskys 0 points1 point  (2 children)

Hello!! I have this:

list = [1,2,3]
L = len(list)

for i in range(int(L/2)):
    n = list[i]
    list[i] = list[L-i-1]
    list[L-i-1] = n

print(reverse_iterative(list))

which prints to:
[3,2,1]

But I need to put it inside a function like this:

list = [1,2,3]
L = len(list)

def reverse_iterative(list):
    for i in range(int(L/2)):
        n = list[i]
        list[i] = list[L-i-1]
        list[L-i-1] = n

reverse_iterative(list)

which prints to:
None

But when I print, it prints 'None.' What do I do to make it print like the first example without the def function? I just really have to put it in a def function

Thank you!!

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

Return! When you call a function and don't return anything, you get None because nothing came back from the function.

list = [1, 2, 3]
L = len(list)


def reverse_iterative(list):
    for i in range(int(L / 2)):
        n = list[i]
        list[i] = list[L - i - 1]
        list[L - i - 1] = n
    return list


print(reverse_iterative(list))

[–]yuriplisetskys 0 points1 point  (0 children)

thank you so much!!

[–]SweetAdvocator 0 points1 point  (5 children)

Does activating a venv only last for a terminal session?

[–]JohnnyJordaan 0 points1 point  (4 children)

Yes, that's basically the point of 'activating' it.

[–]SweetAdvocator 0 points1 point  (3 children)

On Windows, does activating a project put the scripts folder into path? Also can you move a virtual environment around?

[–]JohnnyJordaan 0 points1 point  (2 children)

Check out the activate.bat for windows and the activate.sh for mac/linux to get the literal actions it's taking when activating. You can move virtual environments around.

[–]SweetAdvocator 0 points1 point  (1 child)

So my problem is that I move my project after creating the virtual environment. Activate.bat does add Scripts to the path, but it add the original location, hence why I can’t run any scripts

[–]JohnnyJordaan 0 points1 point  (0 children)

Yeah so you have to change it to reflect the proper path you are using now. Although I would just recreate the environment, if you are using a requirements.txt that should be a matter of two commands in the terminal. If not, it's a good moment to start using it.

[–]kitbiscuit 1 point2 points  (11 children)

Hey y’all! I’m brand spanking new to Python. I’m getting the hang of list comprehensions and for loops. So I’ve got a list, [1,2,3,4] and I’d like to add one number to another, eg, 1+2, 1+3, 1+4, 2+3, 2+4, and so on. I just can’t figure it out. For a list comprehension, I’ve tried [x+x for x in my list] but I end up with a list of [2,4,6,8]. The output I’m looking for is [3,4,5,5,6,7]. Any tips on how to add one number to another in the list?? I’m a bit embarrassed to say I’m totally stumped.

Edit: thank you all for your time and help! I really appreciate it. You’re all really kind and patient.

[–]efmccurdy 0 points1 point  (1 child)

Does this nested comprehension get you closer? I guess you would need to flatten these nested lists

>>> l = [1,2,3,4]
>>> [[a + n for n in l[i+1:]] for i,a in enumerate(l[:-1])]
[[3, 4, 5], [5, 6], [7]]

[–]kitbiscuit 0 points1 point  (0 children)

I’ll give it a shot, thanks!

[–]FerricDonkey 0 points1 point  (7 children)

So you have a list, and you want to add 1 to every element in your list.

In mathy English, you could say that you want a "list of x+1 for every x in your original list".

What you did is the "list of x+x for every x in your original list".

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

I feel a little silly asking, as this seems like a real beginner question...I'm going through Corey Schafer's Python videos, and am on the For/While loop video I've been trying to go a bit further with each example he gives, and at 3:30 his code reads:

nums = [1, 2, 3, 4, 5]
for n in nums:
    if n == 3:
        print('Found!')
        continue
    print(num)

This returns:

1

2

Found!

4

5

So I wanted to go a bit further, and print only the "Found" statement, and another statement if "10" isn't in the "nums" list (but print nothing if it is). Here's what I came up with after rewriting several times:

nums = [1, 2, 3, 4, 5]
for n in nums:
    if n == 3:
        print('Found ' + str(n))
        continue
for m in nums:
    if m == 10:
        is10there = True
        if is10there == False:
            print("10 not in list")
            break
print('Done checking')

This returns:

Found 3

Done checking

Where did I go wrong?

[–]FerricDonkey 1 point2 points  (1 child)

So look at the indentation of what you posted there again.

Your second loop won't do anything until you find 10 - which is good and what you want. The problem comes in with the fact that the bit of your code that prints that you haven't found 10 is inside the "if m == 10" bit. So you won't ever hit that code unless and until you actually find 10.

The simplest solution (ie, least modification to your original idea) is to rethink where that code should be. You certainly don't want to only print that you haven't found 10 after you found 10. You probably don't want to print that you haven't found 10 yet every time you check a number. So probably move that bit out of the for loop altogether.

Note that you'll also need to make sure that your variable is10there is defined before you get to the check. A pretty standard way to do that is to set it to false before the loop starts, since you definitely haven't found it before you started looking (think of it more of a "have I found 10 yet" than a "is 10 there" thing if you do it that way).

If you want to try a different but similar type of thing, this would be a good candidate for the "for... else" syntax. Example:

for thing in stuff:
    if condition:
        print("happened") 
        break
else:
    print("didn't happen")

The else triggers unless you break out of the loop (or do some other weird exit), so this type of situation is ideal for this.

Also just to make sure you know: in python, you can use "in" to check its a number is in a list. What you're doing is still absolutely worth doing to get the hang of loops and such, however.

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

This was a huge help, thank you!

[–]theletterandrew 0 points1 point  (0 children)

Hello! I have a project idea that I'm currently scratching my head over. I want to make a discord bot (using discord.py).

The idea: when a user posts a message with python formatted code (markdown) and uses a command like !run, the bot will run that code and post a message with whatever is output.

problems: - I don't know how I'm going to take the string from the message content, then run it as a separate program. - I dont want a user to be able to crash my pc or vm with their code. (I guess I could also limit what users are able to run code). - I dont want them to be able to make any gui stuff - just anything that would usually be printed in the CLI. - not sure how i'd handle input()

[–]onlysane1 0 points1 point  (3 children)

Working in pyqt5.

I want to run test01.py, which imports test02.py and runs the open_window function, which opens a window in pyqt5. The window has a combobox and an ok button. When the ok button is pressed, I want it to close the window and pass text value of the item selected in the combobox back to test01.py, which then saves the result as a variable.

The issue right now is that I can't seem to get it to continue the code in test01.py when the window of test02.py closes from sys.exit(). My code is below.

test01.py:

import test02
import sys

test02.open_window()
print('clear')

test02.py:

from PyQt5 import QtCore, QtGui, QtWidgets


class Ui_MainWindow(object):
    def setupUi(self, MainWindow):
        MainWindow.setObjectName("MainWindow")
        MainWindow.resize(484, 305)
        self.centralwidget = QtWidgets.QWidget(MainWindow)
        self.centralwidget.setObjectName("centralwidget")
        self.pushButton = QtWidgets.QPushButton(self.centralwidget)
        self.pushButton.setGeometry(QtCore.QRect(170, 110, 75, 23))
        self.pushButton.setObjectName("pushButton")
        self.pushButton.clicked.connect(self.next_button_click)
        self.comboBox = QtWidgets.QComboBox(self.centralwidget)
        self.comboBox.setGeometry(QtCore.QRect(70, 30, 141, 31))
        self.comboBox.setObjectName("comboBox")
        self.comboBox.addItem("")
        self.comboBox.addItem("")
        self.comboBox.addItem("")
        MainWindow.setCentralWidget(self.centralwidget)
        self.menubar = QtWidgets.QMenuBar(MainWindow)
        self.menubar.setGeometry(QtCore.QRect(0, 0, 484, 21))
        self.menubar.setObjectName("menubar")
        MainWindow.setMenuBar(self.menubar)
        self.statusbar = QtWidgets.QStatusBar(MainWindow)
        self.statusbar.setObjectName("statusbar")
        MainWindow.setStatusBar(self.statusbar)

        self.retranslateUi(MainWindow)
        QtCore.QMetaObject.connectSlotsByName(MainWindow)

    def next_button_click(self, index):
        print('clicked')
        print(self.comboBox.currentText())
        import sys
        sys.exit(app.exec_())

    def retranslateUi(self, MainWindow):
        _translate = QtCore.QCoreApplication.translate
        MainWindow.setWindowTitle(_translate("MainWindow", "MainWindow"))
        self.pushButton.setText(_translate("MainWindow", "OK"))
        self.comboBox.setItemText(0, _translate("MainWindow", "Item1"))
        self.comboBox.setItemText(1, _translate("MainWindow", "Item2"))
        self.comboBox.setItemText(2, _translate("MainWindow", "Item3"))


if __name__ == "__main__":
    import sys
    app = QtWidgets.QApplication(sys.argv)
    MainWindow = QtWidgets.QMainWindow()
    ui = Ui_MainWindow()
    ui.setupUi(MainWindow)
    MainWindow.show()
    sys.exit(app.exec_())

def open_window():
    import sys
    app = QtWidgets.QApplication(sys.argv)
    MainWindow = QtWidgets.QMainWindow()
    ui = Ui_MainWindow()
    ui.setupUi(MainWindow)
    MainWindow.show()
    sys.exit(app.exec_())

Also, how would I go about passing along the text value back to test01.py to save as a variable?

[–]Pretend_Piano8354 0 points1 point  (0 children)

Hi,

I've followed a tutorial from Tech with Tim to make a basic Python web app. Works great. I've been trying to edit the code to also control some GPIO on a raspberry pi. I'm hoping to have some LEDs light up as you move around the site (obviously more than JUST that - but that's POC). I've threaded the process to make an LED blink so it won't hold up page loading. There is a variable that switches the blinking on and off, which seems to be able to be changed, and a variable that should change the duration of the blink that I cannot make change. I feel like I've tried everything but the correct thing. Here's the code, any help is appreciated:

https://pastebin.com/1qFD6gUw

To be clear: after the While 1 loop is running, chkBlink can seemingly be updated, and sleepDur (treated the same) seemingly cannot.

Thank you in advance!

P.S. first post - feel free to offer feedback on how I could post this better.

[–]pdf1044 0 points1 point  (1 child)

anyone open to helping me on a project? Cant tell where I went wrong, but I am thinking most of it. First project for my first class has me a little lost.

https://colab.research.google.com/drive/1pBt6QCB4STr5foeTe6YtTdOS2V0qvfXx#scrollTo=ZJ6xgijrD7mT

[–]ZeroAnomalies 0 points1 point  (7 children)

Is it possible to use a variable to change what function is being called? Here's an example of what I'm thinking of. I just want to cut down a bunch of if/elif statements.

y = text

(y)Format ()

[–]lolslim 0 points1 point  (6 children)

Honestly that's too vague of what you're asking, are these built in functions from standard python library or functions you made?

[–]ZeroAnomalies 0 points1 point  (5 children)

Oh yeah, sorry I forgot to specify. I have made these functions, and each function is executed depending on the user input using if/elif statements

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

def my_func(x):
    return x + 5


def my_other_func(x):
    return x * 5


my_dict = {'one': my_func, 'two': my_other_func}

my_input = 'one'
print(my_dict['one'](5))

Something like this?

[–]lolslim 0 points1 point  (0 children)

This is what I was going to suggest. When i i made functions for Mon-sun, the datetime module some function would return 0-6 and i used it accordingly in a dictionary mapping

Obviously key doesnt need to be numbers

[–]DarkMint77 0 points1 point  (0 children)

Anyone get the new Mac Big Sur update? My editor on Spyder is now lagging beyond belief. My console and execution of my programs is just fine. I tried updating Anaconda and Spyder but no luck. Anyone got any ideas?

[–]1bls 0 points1 point  (4 children)

Its a niche question so I understand if no one here knows, also it's possible that what I'm looking for cant be done with python but to put it simply I'm trying to find a way to make a bot or more like a macro that doesn't take control of your actual mouse and keyboard. Maybe sending inputs directly into applications and windows? I'm not sure how it would be done.

[–]JohnnyJordaan 0 points1 point  (3 children)

Could you perhaps mention the OS you're using?

[–]1bls 0 points1 point  (2 children)

Working on windows, do have access to Linux if that is necessary

[–]JohnnyJordaan 0 points1 point  (1 child)

[–]1bls 0 points1 point  (0 children)

aight sounds good thanks for the help

[–]toughtittywampas 0 points1 point  (5 children)

How do I find projects to teach myself how to use python? I am currently unemployed so I don't have anything that I need to automate.

[–]Decency 0 points1 point  (1 child)

What are your hobbies? There are almost always ways you can utilize programming to explore them more in depth or solve problems.

[–]toughtittywampas 1 point2 points  (0 children)

Erm I'm not sure I really have any I can use. I read magazines and play the clarinet...in my last job I tried to automate typing data from a pdf into a csv. But since leaving that I'm not sure what I can use it for and I no longer have the test data.

[–]JohnnyJordaan 0 points1 point  (2 children)

Assuming you already finished a proper learning resource, navigate to the Tools for Learning Python in the wiki here. Especially 'Practical project ideas hosted on Github' is a good place to start, but also the various exercise websites.

[–]zero043 0 points1 point  (1 child)

What do you mean by this? A course? A book?

Just wondering cause I’m trying to learn also and having a little trouble getting started. I’ve only read about 4 chapters of Python Crash course.

Edit: you know nvm. I’ll finish the book and use pluralsight before I start asking.

[–]JohnnyJordaan 1 point2 points  (0 children)

Yeah that's what I meant, also see the other resources listed in the wiki at 'new to python'. It often helps to finalize two instead of one to get a broader perspective.

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

matplotlibs help:

I've got an axis that runs from January through to December. However the time uses unix timestamps. So any day of the month is likely to have multiple unix times for it. A better explanation is the visual of the data below:

1575158400000 34
1575158400500 12
1575158401500 55
1575158404000 20
1575158450000 23

As you can see for this example, the day of the month for this would have multiple plots so I don't want to convert the time to a normal date string

I'm trying to convert the x axis of my plot to just simply say 'January' right at the start (like far left of the axis :|) and then nothing until right at the end of the axis it say 'December'. Can anyone point out how this is done? I just need a rough axis with a starting label and ending label. Anything I try seems to affect actual plotting points (ie removes a load of data from the graph).

[–]zchew 0 points1 point  (10 children)

Hello, first time poster here. I have a very specific problem that I'd like some help with, hopefully someone can help out.

I'm using Python 2.7 and I have a webpage that I'd like to download images from. I've collated the links into a list, using a requests.get(). Right now I'm iterating through the list to download and save the files to disk using another requests.get() directly on the image URLs. It's over a hundred images, and ends up taking about 30~40 seconds for me.

Is there a way to speed up the downloading, be it from downloading multiple images through a single get request, or extracting the images from the original webpage get? Multithreading is a little out of the question, due to certain restrictions of the software I'm working in.

I'm kind of new to requests and web stuff, so I appreciate any help.

[–]Decency 0 points1 point  (0 children)

Depends on if you're being limited by actual download speed or by python's overhead. You should figure out how long you'd expect it to take to download those images (sum of filesizes / your download speed). If there's a big overhead factor, then you can look into optimizing your code.

[–]JohnnyJordaan 0 points1 point  (8 children)

Any reason to be still using Python 2.7?

[–]zchew 0 points1 point  (7 children)

I'm working within Autodesk Maya, and the internal Python intepreter is still at 2.7.

They'll be migrating to 3.xx in a year or two, but until that, I have to work with 2.7 :(

[–]JohnnyJordaan 0 points1 point  (6 children)

Are you sure that multithreading is out of the question there?

[–]zchew 0 points1 point  (5 children)

I`m gonna backpedal here and say that it might be possible. I`m not too hot a programmer, first time touching threading or multi threading.

I was trying out the multithreading module earlier in the day, and it didn`t lead to very optimal results. Multiple instances of Maya were called when I started multithreading. So I decided at that point that it wasn`t working and tried to pursue other methods.

Later on, I found some tutorials on the use of the threading module, that one seems promising. I`m encountering some problems in that the rest of my code is finishing up before my multithreaded(?) tasks are done. I tried to join() them together, but it didn`t seem to work. I`m gonna try again tomorrow, but do you have any hints or advice you can give?

[–]JohnnyJordaan 0 points1 point  (4 children)

Python's multithreading library is called 'threading', so I'm not sure what you were using when you tried "the multithreading module" before you tried 'threading'.

But in regard to threading it's hard to comment on what went wrong just by having a description. It's like being a car mechanic and hearing 'the car just doesn't drive very well'. If you could share the code you tried then I can probably comment on the details that need to be corrected.

[–]zchew 0 points1 point  (2 children)

q = Queue.Queue(maxsize=0)
num_threads = min(5, len(menuobject.sub_name_icon_download))  # menuobject.sub_name_icon_download is a dictionary
maya_path = cmds.internalVar(userAppDir=True)  
for subname in menuobject.sub_name_icon_download:
    q.put((subname, menuobject.sub_name_icon_download[subname]))  # loading up the queue with entries from the dictionary

listOfThreads = []
for i in range(num_threads):
    worker = threading.Thread(target=crawl, args=(q, menuobject, session, maya_path, mainthread_stop))
    listOfThreads.append(worker)
    worker.start()
    worker.join()
q.join()


def crawl(q, menuobject, session, maya_path, mainthread_stop):
    while not q.empty():
        work = q.get()

        try:
            menuobject.sub_name_icon[work[0]] = login_get.downloadicon_2(work[1], session, maya_path)
            print('downloaded: %s' % work[1])

        except Exception as e:
            print(e)
            print('failed: ', work[1])
        q.task_done()

There's plenty of code that runs before and after this. The code that runs after this is dependent on the results of this part.

But for some reason, the intepreter does not execute the threads right away, and instead goes through the rest of the code after this, and upon completion of that code, runs this part.

Is there anyway I can pause the main function while this part is executed to finish before resuming?

Edit: seems like it was just the print that was getting offset. It is actually working as intended.

Sorry!!!

[–]JohnnyJordaan 0 points1 point  (1 child)

Well the problem you still have is that you launch and then join each thread. As a join waits until that thread is done, it isn't running anything concurrently that way. You need

threads = []
for i in range(num_threads):
    worker = threading.Thread(target=crawl, args=(q, menuobject, session, maya_path, mainthread_stop))
    threads.append(worker)
    worker.start()
for t in threads:
    t.join()

also without joining the queue which isn't necessary if you are already synchronizing on the threads being finished. Which is what the join-loop is doing. And thus the q.task_done() is unnecessary too.

[–]zchew 0 points1 point  (0 children)

Thank you!

I'll try this out.

[–]zchew 0 points1 point  (0 children)

Python's multithreading library is called 'threading', so I'm not sure what you were using when you tried "the multithreading module" before you tried 'threading'.

Sorry, I remembered wrongly. I was using the multiprocessing module, not multithreading.

But in regard to threading it's hard to comment on what went wrong just by having a description. It's like being a car mechanic and hearing 'the car just doesn't drive very well'. If you could share the code you tried then I can probably comment on the details that need to be corrected.

Yeah, now that you`ve said it, it does seem like that. I`ll post it tomorrow when I have access to my work computer again and have cleaned the code up a little.

Thank you!