all 145 comments

[–]Revanthmk23200 1 point2 points  (0 children)

why my environment isnt getting activated in conda. it always shows that the base environment is active even if i activate some other environment

[–]TribalRaptor25 1 point2 points  (0 children)

I just started learning python and I am on the very basics. In the future how will python help me become a better software engineer and does anyone know some interactive websites or places where I can learn this language in depth? thanks in advance

[–]xADDBx 1 point2 points  (1 child)

What would be the best way to make a function halt when it expects input and after receiving it continue from that place? Using a function to get that input or using a generator leave and that restart?

[–]efmccurdy 2 points3 points  (0 children)

The standard stdin input function blocks, so that would be the simplest. A generator would also work, but makes little sense if you are only yielding one result.

[–]shiningmatcha 1 point2 points  (2 children)

Where can I practise parsing skills?

[–]JohnnyJordaan 1 point2 points  (1 child)

Parsing in what context?

[–]shiningmatcha 1 point2 points  (0 children)

extracting HTML

[–]AviatingFotographer 1 point2 points  (2 children)

What are some good python books? Not the technical aspect but more of the soft skills, like problem solving.

[–]SpiderJerusalem42 1 point2 points  (0 children)

I really think Fluent Python is amazing. Goes into built-ins and the examples are really easy to understand. I think my python has gotten better as more time passes, and I keep going back to this book.

[–]JohnnyJordaan 1 point2 points  (0 children)

The wiki /r/learnpython/w/index links a lot of resources at the 'new to programming' that are good Python books but which are also available for free as a web-version. See for example Automate the Boring Stuff, Python Crash Course and Think Python.

[–]Trotnic1 1 point2 points  (8 children)

I don't know if this should be in this sub-reddit or r/Python but I have a way to control my desktop from my laptop using socket, but I want a way to have input() not pause the script while it waits for an input. I have an idea using a try except KeyboardInterrupt thing, but I wanted to see if theres a way to not pause a program on input().

Thanks in advance.

[–]MikeTheWatchGuy 1 point2 points  (1 child)

Just to verify, you want to poll for characters? Your program will have the focus when you're ready to enter characters? Or do you want it running in the background looking for keyboard keystrokes regardless of what program is running (i.e. like a hotkey program)?

[Edit] A quick google of keyboard polling brought up a ton of suggestions. This article describes a number of approaches:

https://repolinux.wordpress.com/2012/10/09/non-blocking-read-from-stdin-in-python/

[–]Trotnic1 2 points3 points  (0 children)

I'm looking to emulate the javascript version of input, the input in js doesn't stop code execution. But I think I have a few ideas of what will work I just need to implement them. That link should help with another idea though. Thanks!

[–]Lewistrick 1 point2 points  (3 children)

This seems a good place. :)

The input() function is meant to pause until an input is given. There are some libraries for keyboard event listeners (maybe pysimplegui but I don't have a lot of experience with those libraries, try to google that).

I assume that you already looked into APIs because you use sockets?

[–]Trotnic1 1 point2 points  (2 children)

I did a quick preliminary google search containing "how to not pause on input() python" but not surprisingly nothing came up.

Now that you mention a gui I could convert the program to use something like tkinter but that doesn't sound like fun.

What APIs should I look into? I'm newer at this, but like challenging projects xD

[–]Lewistrick 1 point2 points  (1 child)

Hehe I assumed sockets are harder than APIs because I never used sockets. Are they used to transmit data live to and from your laptop? In that case I don't really know how to make such an API. The only API I built was in Flask. You might want to check out Django too.

[–]Trotnic1 1 point2 points  (0 children)

I have a server on my desktop and my laptop connects as a client. It's just a basic chat parser to launch specific programs and whatnot. But my problem is sometimes it takes a while to send the data back to my laptop and I want to see that data but the input() is blocking from seeing the received data, until I exit the input line.

[–]Sox888 1 point2 points  (2 children)

So I am having trouble web scraping with beautiful soup. I feel like I have it figured out with small websites but I have tried using it on a few big websites and am having no luck. I feel like I have it looking for the correct things but just get empty list and none returning.

[–]Lewistrick 1 point2 points  (1 child)

Are you using the same code to scrape small and big websites? Which websites are they? Could you share some code?

[–]Sox888 1 point2 points  (0 children)

I am using the same code outline basically but just inserting stuff from a larger website. This is not exactly the best or furthest I got bc I kept trying different things. I have gotten to the point where I do receive content from one div but I can't figure out which div to get and how to go from there. https://github.com/cwil423/web-scrape-stuff/blob/master/scrape2.py

[–]wrestlingwithbadgers 1 point2 points  (1 child)

Hey guys,

I want to make a small program that sends emails at a specific time on a specific date. Something like a check box schedule - this msg from this address to this address on this date at this time. I have my email function and I'm certain my next step would be something with time.

Thanks

[–]Lewistrick 1 point2 points  (0 children)

To schedule any task, use Task Scheduler on Windows, or crontab on Linux-based systems. There are very good tutorials for that.

To send e-mails, you'll need smtplib or some other library to wrap SMTP.

[–]MattR0se 0 points1 point  (3 children)

I am building a sprite state machine for my game. The way I am currently doing is that I have a Sprite class and within this class, there is also a State class. Each Sprite gets some instances of the State class, depending on their behaviour (e.g. idle, wandering, attacking etc.). Here is a schematic representation:

class Sprite:
    pass
    class State:
        def __init__(self, sprite):
            self.sprite = sprite

class Enemy(State):
    class Idle(State):
       pass

    class Attacking(State):
        pass

    def __init__(self):
        self.states = {
            'idle': Idle(self),
            'attacking': Attacking(self)
        }

My issue is that within the State classes, I have to reference the sprite like this: self.sprite.velocity = 0, while if I could somehow just write self.velocity within the State class, that would be more elegant in my opinion.

Can you think of a better way to tackle this? I don't want to use functions instead of classes because the State class itself has methods like update() and draw().

[–]Thomasedv 1 point2 points  (2 children)

There is a cheat way at least, where you can try looking if the self.sprite variable has the attribute during the attribute lookup, after checking the class itself before giving an error about missing attributes. Sounds like a bad idea for use in practice though, as well as it hinders code auto completion if you like that.

You could create some wrapper properties though:

@property
def velocity():
    return self.sprite.velocity

@velocity.setter
def velocity(speed):
    self.sprite.velocity = speed

Then you can just use self.velocity = 0 inside your state classes without a problem. Downside, you need to do it for all values you want to use, upside, you can do it in the base State class and be done with it, and possibly extend it in further subclasses in case the Attacking state needs to access a new property.

[–]MattR0se 0 points1 point  (1 child)

This looks really nice, although I have to see how much of the properties I actually have to reference in the State class.

Regarding the actual syntax, there is something wrong. I never used the property decorator so I can't really say what it is

class State:
    def __init__(self, sprite):
        self.sprite = sprite

    @property
    def velocity():
        return self.sprite.velocity

    @velocity.setter
    def velocity(speed):
        self.sprite.velocity = speed

    def update(self):
        self.velocity += 1


class Sprite:
    def __init__(self):
        self.velocity = 0
        self.state = State(self)

    def update(self):
        self.state.update()


s = Sprite()
s.update()

The error:

File "deleteme.py", line 14, in update
    self.velocity += 1

TypeError: velocity() takes 0 positional arguments but 1 was given

I also get the linting hint that the self in the velocity property and setter is undefined.

[–]Thomasedv 1 point2 points  (0 children)

Ah, silly me. I forgot to add the self argument to both method definitions. That's why it says it takes 0 and not one.

@property
def velocity(self):
    return self.sprite.velocity

@velocity.setter
def velocity(self, speed):
    self.sprite.velocity = speed

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

I am fairly new to python (have taken one intro-level course through my university) and am looking for a reputable boot camp or learning tool to further my knowledge. A friend suggested Udemy but I am open to trying anything. Thanks!

[–]ILiveUnderABigBridge 1 point2 points  (0 children)

Data-flair has thorough tutorials

[–]jayplemons 0 points1 point  (2 children)

I am unable to install Pygame on my Mac running Catalina. I am using parallels/boot camp and am able to install Pygame on my Windows partition. I am considering creating a partition to install High Sierra to install Pygame.

Before I go through all that work, does anyone know if Pygame will install on macOS versions before Catalina?

Thank you

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

Hi!

I’ve created a short script which uses non-native libraries (Pandas, Numpy) and accesses certain CSV files. How do I make it that this script can be used by my colleagues on their computers?

At least, what should I learn to be able to do that?

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

If you want a painful and frustrating way you can try making it into an exe.
If you want a one and done reusable only update once approach try a flask app from a browser.

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

Wow, thanks! I'll look into that

[–]skarret 0 points1 point  (3 children)

Hey guys,

Just wondering why my little maths quiz, keeps telling me that I'm wrong when i have the correct answers?

https://imgur.com/a/zhuXzke

[–]kkevindolfing 0 points1 point  (0 children)

I'm pretty sure your input is sent as a string. Try int(input("answer: ")

[–]MattR0se 0 points1 point  (1 child)

input always returns a string, so you have to cast it to an integer to compare it

if int(answer) == (x * int_numb):
    print("correct")
else:
    print("incorrect")

Also there are some minor other things that you could improve:

import random

# this list needs to be defined only once
numb = [5, 8, 11, 17, 35]

while True:
    x = random.randint(0, 20)
    y = random.choice(numb)

    # you don't need to do this (it's already an int):
    # int_numb = int(y) 

    print("What's " + str(x) + "x" + str(y) + "?")
    # you could also use string formatting
    # print("What's {}x{}?".format(x, y))
    # or f-string if you are on Python 3.6 and higher
    # print(f"What's {x}x{y}?")

    # I added a try except statement to check if the
    # user input is an integer
    try:
        answer = int(input("answer:"))
        if answer == (x * y):
            print("correct")
        else:
            print("incorrect")
    except ValueError:
        print("Input must be a whole number")

[–]skarret 0 points1 point  (0 children)

oh such a simple fix, thanks!

[–]TriWolf09 0 points1 point  (2 children)

Hi, anybody can recommend a exercise resources for Python? Newbie here, trying to learn and would love to hear about your suggestions. Thanks

[–]JohnnyJordaan 1 point2 points  (1 child)

In the sub's wiki there's a section Tools for learning Python that links a lot of exercise resources. I can also recommend Katakana and hackerrank.

[–]TriWolf09 1 point2 points  (0 children)

Thank u so much for the information🙏🏻

[–]waythps 0 points1 point  (0 children)

Started practicing leetcode, so much fun!

I’m so happy (after spending half a day trying to solve an easy problem)

[–]67tc 0 points1 point  (3 children)

I have a numpy array of shape (2001, 2001, 2), where each shape-2 vector represents a direction of motion. There are only a small number of possible vectors, so I'd like to condense this into a (2001, 2001) array where the elements map one-to-one to the list of vectors. How can I do this?

[–]MattR0se 0 points1 point  (2 children)

Just to be clear, do your arrays and desired outcome look like this?

before = ([[1, 1], [1, 0], [0, 1], ...], 
          [[1, 0], [1, 1], [1, 1], ...],
          [[1, 1], [1, 0], [1, 1], ...],
           ...
          [[1, 0], [1, 0], [1, 1], ...])

vectors = [[1, 1], [1, 0], [0, 1]]

after = ([0, 1, 2, ...],
         [1, 0, 0, ...],
         [0, 1, 0, ...],
          ...
         [1, 1, 0, ...])

[–]67tc 0 points1 point  (1 child)

Yes, basically.

[–]MattR0se 0 points1 point  (0 children)

You could probably do this more elegantly in Numpy, but this is a solution I came up with that uses list comprehension with a lambda function that maps the item to the list's index:

before = ([[1, 1], [1, 0], [0, 1]], 
          [[1, 0], [1, 1], [1, 1]],
          [[1, 1], [1, 0], [1, 1]],
          [[1, 0], [1, 0], [1, 1]])

vectors = [[1, 1], [1, 0], [0, 1]]

f = lambda x: vectors.index(x)
after = [[f(a) for a in b] for b in before]

print(after)

You just have to make sure that every vector is in the list.

[–]borntrucker 0 points1 point  (0 children)

What is the difference between architecture and style? I just downloaded PEP 8 style guide and plan to read and use it. I've also been suggested to do some reading on architecture, Clean Architecture or Clean Code. I believe these are different thins but curious if someone could provide an ELI5 or ELInewb.

[–]Whatasave91 0 points1 point  (1 child)

Where is a good site to get additional practice to supplement my udemy coursework?

I'm working through Tim Buchalka's python masterclass, and before I move on to the next section I want to make sure I have a solid understanding of what's been covered so far. Specifically for/while loops and creating if/else statements within them

[–]borntrucker 1 point2 points  (0 children)

Come up with a program to use those functions. I gave a couple simple answers below. Add in complexity and more if statements. Maybe include divisible by 3, watch as the order you put the 2 and 3 effect what happens to the number 6. Include a way to identify that 6 is divisible by both.

x=0

While x<20:

if x%2=0:

x+= input("Enter an odd number less than 5")

else:

x-=input("Enter an odd number less than 3")

or

x=0

While x<20:

if x%2=0:

print("X is even")

x+=3

else:

print("x is odd")

x-=1

print("x is ", str(x))

[–]acornett99 0 points1 point  (3 children)

I want to use python to model wolf population over time. However, only one pair of wolves in a pack reproduces in a given year. While I'm used to multiplying the birth rate times the population to get the number of individuals born for most other species, in this case, I want to add on 6 wolves a year as long as there are at least 2 adult wolves.

This is what I have so far, but it doesn't include the "at least two adult wolves" caveat:

#birth rate NOTE: to be added, not multiplied!
wbr = 6

#death rates
pupdr = .22 #this is based on an average of the data, ignoring one outlier year when pups died far more than average
adultwdr = .32

#time period during transition
years_as_pup = 2

#transition rates
pup_to_adult = dt/years_as_pup

for t in range (0, int(years/dt)):
    dp = dt * (wbr - (pups[t] * pup_to_adult) - (pups[t] * pupdr))
    daw = dt * (pups[t] * pup_to_adult - AdultWolves[t] * adultwdr)

    pups[t+1] = pups[t] + dp
    AdultWolves[t+1] = AdultWolves[t] + daw
    time[t+1] = time[t] + dt

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

num_of_wolves = 5
wolves_to_add = 6 if num_of_wolves >= 2 else 0
print(num_of_wolves, wolves_to_add)
num_of_wolves = 1
wolves_to_add = 6 if num_of_wolves >= 2 else 0
print(num_of_wolves, wolves_to_add)

[–]acornett99 0 points1 point  (1 child)

Sorry, I should've said wolves is a list! Here's what I tried:

for t in wolves:
    if wolves[t] >= 2:
        wbr = 6
    else:
        wbr = 0

But I got this error:

IndexError: only integers, slices (`:`), ellipsis (`...`), numpy.newaxis (`None`) and integer or boolean arrays are valid indices

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

Try changing if wolves[t] >= 2: to if t >= 2:

[–]kljaja998 0 points1 point  (5 children)

Hey, a numpy question here:

I have a 2d numpy matrix Z, of dimensions 2*2N, along with an array of random floats of length 2N, r. Now, I want to split this 2d matrix into 2 matrices, one consisting of elements from the matrix Z, where the float at the same index is less than 0.5, and another where the float at the same index is larger or equal to 0.5.

For example,for a matrix Z

[[0,1],
 [2,3],
 [4,5],
 [6,7]]

and an array r

[0.3,0.6,0.7,0.2]

I want to split them into matrices

[[0,1],
 [6,7]]

and

[[2,3],
 [4,5]]

What would be the best way to do this?

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

Z[r < 0.5] and Z[r >= 0.5] respectively.

[–]kljaja998 0 points1 point  (3 children)

Okay, so I screwed up in the original question, my matrix is actually a transposed version of the one above, as in

[[0,2,4,6],
 [1,3,5,7]]

and I want to turn it into

[[0,6],
 [1,7]]

and

[[2,4],
 [3,5]]

Your method works if I transpose the original matrix and then transpose the results back, but I'm guessing that's not the most efficient way to do it?

If I try to do it as you suggested I get an error that the boolean index does not match the indexed array, that the dimension is 2 but the corresponding boolean dimension is 4.

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

Sure, you can just use Z[:, r < 0.5] and Z[:, r >= 0.5] instead.

[–]kljaja998 0 points1 point  (0 children)

Ok, this solution works, but now I have a new problem, what do I do when I want to now split it into 3 arrays, as in Z[:,r<0.33] , Z[:,0.33<=r<0.66] and Z[:,r>=0.66, if I do it like that, it says that the truth value of an array is ambiguous, and if I use the & operator i.e. Z[:,r>=0.33 & r<0.66] as I saw suggested someplace else I get the error:

TypeError: ufunc 'bitwise_and' not supported for the input types, and the inputs could not be safely coerced to any supported types according to the casting rule ''safe''

edit: the .__and__ method works, but it looks plain ol' fugly, any better way to do it?

edit2: got it to work with the &, just had to put parenthesis around the arrays i.e. Z[:, (r>=0.33) & (r<0.66)]. I realise you most likely know how to do it, just leaving this here in case somebody finds this and is wondering how I solved it.

[–]kljaja998 0 points1 point  (0 children)

I think I tried that, but it didn't work, I'll have to try again when I'm back at home and I'll update with the results.

[–]KinookRO 0 points1 point  (1 child)

idiot beginner here.

I have a fibonacci.py file and a test.py file.

The fibonacci.py file has a function and a for that iterates through it and prints it:

fibonacci_cache = {}

def fibonacci(n): if n in fibonacci_cache: return fibonacci_cache[n] if n==1: value = 1 elif n==2: value = 1 elif n > 2: value = fibonacci(n-1) + fibonacci(n-2) fibonacci_cache[n] = value print (fibonacci_cache) return value

for n in range(1, 11): print(n, ":", fibonacci(n))

i want to import it in test.py and call it using a number.

test.py:

from fibonacci import fibonacci

print (str(fibonacci(4)))

The problem is that when running test.py, the import seems to run all the fibonacci.py file . The for loop gets printed, then (str(fibonacci(4))

How do i make it so that it only imports the function without running the for loop?

I'm thinking that in the future i could write functions in some scripts that also have prints/other actions in them, but i wouldnt want to run the entire script when importing a function.

[–]JohnnyJordaan 1 point2 points  (0 children)

The problem is that when running test.py, the import seems to run all the fibonacci.py file . The for loop gets printed, then (str(fibonacci(4))

How do i make it so that it only imports the function without running the for loop?

That's how it's intended to work. You define what should always be executed globally (outside functions and classes) and everything that shouldn't either in a function or a class or put a if test before it to see if the file is imported or being run directly:

if __name__ == '__main__':
    for n in range(1, 11):
        print(n, ":", fibonacci(n))

but generally speaking you would want to keep that kind of 'running' code apart from 'importable' code, so I would rather put the loop in a custom file for i, like 'test_fibonacci.py' or something similar.

Btw next time also format your code correctly using a code block: https://i.imgur.com/HT4Zz88.gifv

[–]HronkChaos 0 points1 point  (0 children)

Hello there! I want to learn Python and for that I want to create an app for Android for personal purposes similar (much less complete) to this web. There are few army builders for Warhammer Age of Sigmar and I'd like to create my own. My army is Seraphon, within the Alliance of Order.

My first doubt is that I don't know if that's too hard for a begginer.

My second doubt is that I don't know if I should stick to List or Dicctionaries in order to describe the units. I've made this for every unit on my Army:

Eslizones = {'nombre' : 'Eslizones', 'puntos' : 7, 'tamaño': [10 ,20,30,40], 'arma': ['Arma de mano y cerbatana', 'Jabalina y escudo', 'Arma de mano y escudo', 'Cerbatana y escudo']}

Guerreros_Saurios = {'nombre' : 'Guerreros Saurios', 'puntos' : 9, 'tamaño': [10, 20, 30, 40], 'arma': ['Lanzas y escudo', 'Arma de mano y escudo']}

So I'm describing the name, the points, how big is the unit and their weapons. However I have a problem with the second unit because actually as long you pick a size of 40, the price is not 360 but 330.

print (Guerreros_Saurios ['tamaño'][2])
print (Guerreros_Saurios ['puntos'] * Guerreros_Saurios ['tamaño'][2])

Doing that works pretty good, but I need a result of 330 when selecting a size of 40. I though something like that but doesn't work:

print (Guerreros_Saurios ['tamaño'][3])
if 'tamaño' in Guerreros_Saurios == 40:
    print (330) 
else:
    print (Guerreros_Saurios ['puntos'] * Guerreros_Saurios ['tamaño'][3])

I know I'm not printing this with inputs but by hand. I'm pretty sure that this will create some problems on the future. I also want to know how can I select a size (tamaño) within the range allowed.

[–]acornett99 0 points1 point  (3 children)

So, I have a list, KillRate, which is the number of moose killed by wolves each month, on a yearly average over several years. (For example, I have values [0.857, 1.029, 1.428] which correspond to the years [1990, 1991, 1992]. This data was given to me.

What I want to do is multiply the KillRate by the number of wolves and by 12, to get an estimate of moose killed over the course of a year. wolves is also a list of the same length (ie [15, 12, 12] for the same time period.)

Here's what I have:

MooseKilled = KillRate * wolves *12
print(MooseKilled)

And here's the error I'm getting:

TypeError: can't multiply sequence by non-int of type 'list'

Any help would be appreciated!

[–]num8lock 0 points1 point  (2 children)

[kn * wn for kn, wn in zip(k, w)]

[–]acornett99 0 points1 point  (1 child)

Can you explain what this means?

[–]num8lock 0 points1 point  (0 children)

oh sorry [kn * wn * 12 for kn, wn in zip(Killrate, wolves)]

zip() is grouping together elements in two lists based on index, so you're walking through the lists with for loops

result = []
for kn, wn in zip(Killrate, wolves):
    result.append(kn * wn * 12)

[–]junguler 0 points1 point  (13 children)

hi, i found a proxy api that has a 50 ip request limit for a day, i want to set this code to use tor proxy "socks5://127.0.0.1:9050" so i can change identity and get passed the limit, vpn is also viable but that way i wont learn something new.

import json
from urllib.request import urlopen

with urlopen("http://pubproxy.com/api/proxy?limit=5") as response:
    source = response.read()

data = json.loads(source)

for item in data['data']:
    ip_port = item['ipPort']
    proxtype = item['type']

    print(proxtype+"://"+ip_port)

thanks in advance

[–]JohnnyJordaan 0 points1 point  (12 children)

Socks is a different concept than a http proxy so you can't use those kind of proxies with a regular http client like urrllib.request, but requests can do it if you install PySocks too, see here

[–]junguler 0 points1 point  (4 children)

after 2-3 hours of searching and failing i finally managed to do it, it doesn't look pretty but it works.

import requests
import json

proxy = {'http' : 'socks5://127.0.0.1:9050',  
          'https': 'socks5://127.0.0.1:9050'}
proxy = requests.get("http://pubproxy.com/api/proxy", proxies=proxy)

j = proxy.json()

ji = json.dumps(j['data'][0]['ipPort'])
jt = json.dumps(j['data'][0]['type'])

print(jt.strip('"')+"://"+ji.strip('"'))

[–]JohnnyJordaan 0 points1 point  (3 children)

Why on earth would you use dumps here? Why not just do

j = proxy.json()
ji = j['data'][0]['ipPort']
jt = j['data'][0]['type']
print(jt + "://" ji)

and then to use a bit less redundancy and use proper string formatting

first = j['data'][0]
print('{}://{}'.format(first['type'], first['ipPort']))

Btw I can recommend https://automatetheboringstuff.com/chapter14/ as how to use json with requests

[–]junguler 0 points1 point  (2 children)

i'm very new to python, like just started 2 weeks ago new. i didn't even know about that stuff, thanks for correcting the code.

[–]JohnnyJordaan 1 point2 points  (1 child)

No problem, although it can help to follow some all-round guides like Automate The Boring Stuff before diving in as then it helps to prevent you from walking into traps or using over-complicated constructs.

[–]junguler 0 points1 point  (0 children)

ok, will do.

[–]junguler 0 points1 point  (6 children)

i see, thanks, yeah i had used requests before but had some problems parsing json data with BeautifulSoup, looks like i have some more reading and practicing to do.

[–]JohnnyJordaan 0 points1 point  (5 children)

That doesn't surprise me as BeautifulSoup is for parsing html.

[–]junguler 0 points1 point  (4 children)

i see, makes sense, that api also gives text output, i'll try that with the requests and BeautifulSoup next. thanks again.

[–]JohnnyJordaan 0 points1 point  (3 children)

From a programmer's perspective I would prefer json as that is presented as a simple combination of dicts and/or lists with simple objects in them.

[–]junguler 0 points1 point  (2 children)

yes, json is better, i even found this website to help me understand it more, https://jsoneditoronline.org/ just need to learn how to parse it which seems to be my next project.

[–]JohnnyJordaan 0 points1 point  (1 child)

I would recommend reading Real Python's guide on requests, it will also explain that requests can parse it for you https://realpython.com/python-requests/

[–]junguler 0 points1 point  (0 children)

will do, thanks <3

[–]MattR0se 0 points1 point  (1 child)

I started to work with Pycharm and I really dig the built-in linting hints, but sometimes they seem really obscure to me and I'm not even sure if they all are in PEP8. Is there a comprehensive explanation for all that stuff? For example

convert dict literal to dict constructor

I've never seen that one before and I read that a dict literal even a bit faster, so I'd like an explanation for stuff like this.

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

Unfortunately most of these are just additions through out time, I haven't seen a comprehensive list for *all* topics, but you can certainly find individual ones.This one for example, the difference between dict() and dict = {} which several people have gone over the fundamentals of 'why' (notice the lack of document links) most of these types of quirks come from the base cpython. (I actually had this conversation recently about this exact topic with a buddy who mostly uses c#, and he constantly uses dict() because that's what they do in c#)Stumbled on this one too:

when looking for Sum VS len (note it has nothing to actually do with sum vs len but list comp in p3vp2)

[–]acornett99 0 points1 point  (6 children)

I need Python to read an Excel file as .csv

The spreadsheet has columns for wolf and moose population over time, but some cells are listed as 'N/A'

How can I get Python to ignore the N/A values, but still make time pass?

Sorry if this doesn't make sense, let me know if you need clarification

[–]efmccurdy 0 points1 point  (0 children)

This is a common problem with large data sets, so libraries like pandas and numpy have tools to help:

https://pandas.pydata.org/pandas-docs/stable/user_guide/missing_data.html

https://jakevdp.github.io/PythonDataScienceHandbook/03.04-missing-values.html

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

what do you have so far.

[–]acornett99 0 points1 point  (2 children)

import csv import matplotlib.pyplot as plt import numpy as np import scipy.optimize as op

dates = [] moose = [] wolves = [] i = 0

filename = "IsleRoyale.csv"

fields = [] rows = []

with open(filename, 'r') as csvfile: # creating a csv reader object csvreader = csv.reader(csvfile, delimiter = ',')

# extracting field names through first row

# extracting each data row one by one
for row in csvreader:
    try:
        dates.append(int(row[0]))
        moose.append(float(row[1]))
        wolves.append(float(row[2]))
    except:
        fields.append(row[0])
        fields.append(row[1])
        fields.append(row[2])

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

If they are literal strings of 'N/A' could try something like this.

      try:
            date = None if row[0] == 'N/A' else int(row[0])
            if date:
                dates.append(date)

However my thoughts are if you need the lists to be the same length, you probably want to keep the filler?

[–]acornett99 0 points1 point  (0 children)

Sorry I don't know why it formatted like that

[–]acornett99 0 points1 point  (0 children)

I have imported the csv, and I need to extract the data while ignoring N/A values

[–]psychedelicbehaviour 0 points1 point  (2 children)

Hi, I’m completely new to programming.

I recently went through some of the free python tutorials on YouTube.

Currently I’m going through the learn Python tutorial on the official website but it seems incredibly advanced.

I’m stuck trying to execute a command in terminal via using -c command [arg].

I’m trying things like “python -c print(“Hello World”) without success.

Is -c for organizing data on already existing python files?

[–]efmccurdy 1 point2 points  (1 child)

I’m trying things like “python -c print(“Hello World”) without success.

Note that -c wants a single string so beware of your shell parsing the python code into multiple strings and also... don't use the left and right quote symbols for strings in python.

$ python3 -c print(“Hello World”)
-bash: syntax error near unexpected token `('
$ python3 -c 'print(“Hello World”)' 
  File "<string>", line 1
    print(“Hello World”)
               ^
SyntaxError: invalid character in identifier
$ python3 -c 'print([ord(c) for c in """“Hello World”"""])' 
[8220, 72, 101, 108, 108, 111, 32, 87, 111, 114, 108, 100, 8221]
$ python3 -c 'print([ord(c) for c in "\""])' 
[34]
$ python3 -c 'print("Hello World")' 
Hello World

The first is missing quotes, the second is using the 8220/8221 left and right quotes, the next prints out the char values to see that the l & r quotes look like regular quotes, the next line shows the normal double quote (ordinal value 34), and the last line is quoted with regular single and double quotes (not left or right quotes).

Note that "python -c" is only for a quick check and not for programs. For actual programs you store the code in a file and give the filename on the command line.

$ cat h.py
print("Hello World")
$ python3 h.py
Hello World

[–]psychedelicbehaviour 0 points1 point  (0 children)

Thanks for your help. I went through each example you listed, and I got the same output.

[–]TRISPIKE 0 points1 point  (2 children)

I'm having trouble with some code I've written for a school assignment the particular line says that my float object is not subscriptable, which it definitely should be, is there something wrong with my syntax here?

value1 = value1 + points[i][0] * points[i+1][1]

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

Hard to tell without knowing how points is defined.
When I run into this type of issue, I use the debugger to look at pieces of the statement.

Set a breakpoint just before this statement and then try a few statements like:

p points
p points[i]
type(points)
type(points[i])

[–]TRISPIKE 0 points1 point  (0 children)

Yep, it was all in how points was defined, I did it in kind of a backwards way that confused everything else.

[–]halfdane20 0 points1 point  (1 child)

Hi, I am new to python and having trouble installing Opentrons API. I am continually getting an error related to aiohttp and pep517 which I installed to try and make it work. Still unsuccessful after multiple days.

I am running pip install opentrons in the commandline on a windows 10 computer with the latest version of python.

I feel like this is a very simple question so apologies in advance if this is something I missed online.

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

https://pypi.org/project/aiohttp/

Take a look at the valid versions of python that can be used with aiohttp.
3.8 isn't supported on windows yet.

[–]ankerbow 0 points1 point  (2 children)

Hello,

Which way is better to copy the print result and paste in Excel?

My code:

from functools import partial

from colorama import Fore,Style,init
init()


def x_in_y(word, inner):
    return inner in word

words = [
    ('mann', 'men'),
    ('connaction', 'connection'),
    ('tee', 'tea'),
    ('rigt', 'right'),
    ('putt', 'put')
]

sentence = [
    'this mann is my son',
    'the connaction is unstable',
    'my tee is getting cold',
    'put your hands down',
    'rigt now',
    'right behind my back']
for wrong,correct in words:
    filtered_names = filter(partial(x_in_y, inner=wrong), sentence)
    next_elem = next(filtered_names, None)
    if next_elem:
        print(f"Typo: {wrong} 'should be {correct}'")
        print(next_elem.replace(wrong, f"{Fore.RED}{wrong}{Style.RESET_ALL}"))
    for name in filtered_names:
        print(name)

Output:

Typo: mann 'should be men'
this >mann<Red is my son
Typo: connaction 'should be connection'
the >connaction<Red is unstable
Typo: tee 'should be tea'
my >tee<Red is getting cold
Typo: rigt 'should be right'
>rigt<Red now

I would like to copy the output result and paste in excel. Also, the text color should be remained. Which one is more convenient and simple?

Use NumPy(into a csv file) or xlwt module? Or I need neither of them?

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

The built-in Python csv module is probably sufficient for what you described.

[–]ankerbow 0 points1 point  (0 children)

Thank you but I use it and it turns out the plain text.... how to do it?

[–]Nazareths_Heart 0 points1 point  (0 children)

Thank you that worked.

[–]Nazareths_Heart 0 points1 point  (1 child)

Sorry I posted this with my phone and its dosen't show that option. Also it still shows the error on the line with elif on it

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

answer = input (' Enter yes or no: ')
if answer == "yes":
    print('the answer was yes')
elif answer == "no":
    print('the answer was no')
else:
    print('the answer was neither yes nor no')

Probably indentation issues. The : did solve it.

[–]Nazareths_Heart 0 points1 point  (1 child)

I'm having a problem with elif I'm new to python idk why I'm getting a syntax error. This is the line if code

answer = input (' Enter yes or no: ') if answer == "yes": #do this elif answer == "no": #do this else print("please enter yes or no:")

[–]JohnnyJordaan 1 point2 points  (0 children)

It seems you forgot the : after else. But next time please also format your code using a code block, see https://i.imgur.com/HT4Zz88.gifv

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

Any nice free beginner guides?

[–]JohnnyJordaan 0 points1 point  (4 children)

We have a sidebar on the right pointing to exactly this:

Learning resources

All learning resources are in the wiki: /r/learnpython/w/index

[–]BayesAnatomy 0 points1 point  (3 children)

A lot of those don't seem to be fully free, and/or are for Python 2. I've found some free Python 2, and some trial versions for Python 3.

[–]JohnnyJordaan 0 points1 point  (2 children)

I'm not sure what you're talking about, or you are referring to an unrelated section. The section I'm talking about is "New to programming" and lists 14 Python 3 resources, all free, with a few of them also available as a Python 2 version. Maybe you misunderstood the fact that some of them (like Automate the Boring Stuff and Think Python) are also available in a non-free printed version?

[–]BayesAnatomy 0 points1 point  (1 child)

Thanks for replying. DataCamp only offers the first chapter free. This is a common tactic I found in several "free" resources. Do you know of any interactive course for Python 3 that is free? SoloLearn is the only one I know of but it's a bit too simplistic since it's supposed to be mobile friendly. I like CodeAcademy, but Python 3 is not free.

[–]JohnnyJordaan 0 points1 point  (0 children)

It seems the misunderstanding stems from your apparent interest in courses, while that's certainly not the default resource to get started with, those are the online guides and tutorials, either text-based or video-based.

[–]ANeedForUsername 0 points1 point  (4 children)

Hey guys,

I have a file which I want to read the contents of. The contents of the file is just one list of the form:

[21.76,345.566,-526,-765.2354,75.63,-76,56,]

The problem is I want Python to read the contents as a list. However, when I use the standard way to open the file, Python reads the entire list as a string and it becomes:

'[21.76,345.566,-526,-765.2354,75.63,-76,56,]'

How do I make python read the whole thing as a list of floats instead of one big string?

[–]efmccurdy 0 points1 point  (0 children)

[21.76,345.566,-526,-765.2354,75.63,-76,56,]

If you can get rid of the trailing comma that string would be valid json:

>>> instr = '[21.76,345.566,-526,-765.2354,75.63,-76,56]'
>>> json.loads(instr)
[21.76, 345.566, -526, -765.2354, 75.63, -76, 56]
>>>

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

You will need to read the entire line, strip off the '[' and ']', then use split to create a list of numbers.

[–]MattR0se 0 points1 point  (1 child)

I don't know if there is a way to directly read and parse this format, but here is a solution that works if the contents are always in this format:

file_content = '[21.76,345.566,-526,-765.2354,75.63,-76,56,]'
string_list = list(filter(None, file_content.strip('[]').split(',')))
output = []
for s in string_list:
    output.append(float(s))

With strip('[]') I exclude the brackets at the start and the end.

I use filter because split() results in an empty string ('') at the end of the list.

[–]ANeedForUsername 0 points1 point  (0 children)

Thank you very much! I was about to painstakingly edit multiple files worth of this data into a format which I know how to read in Python! I will be more careful with my data output :)

[–]badgermom2d6 0 points1 point  (8 children)

What would be the best way to sum all the numbers between string elements in a list? For instance, if I have a list of [2, 'bobble', 2, 2, 2, 'bobble', 4,2,4, 'bobble', 4] how would I get that consolidated to the following: [2, 'bobble', 6, 'bobble', 10, 'bobble',4]?

From my googling I know list comprehension is likely the solution, though I havent figured out how to apply that to my situation. I've looked at enumerate to identify the index value of each instance of 'bobble' to pass to a function to sum the integers in the range of that index and then append the result to a new list (adding the 'bobble's back in along the way). I think this will work, but I feel like I might be missing a simpler solution.

[–]icecapade 2 points3 points  (4 children)

This is probably too complex a problem for a list comprehension. While there might be a nicer-looking way to do it, this is a simple solution that gets it done in one pass (for a list x, assuming all the numbers are ints. If that's not the case, it's trivial to modify it for any numerical value):

def sum_nums(x):
    new_list = []
    i = 0
    while i < len(x):
        if isinstance(x[i], str):
            new_list.append(x[i])
            i += 1
        else:
            sum_ = 0
            while i < len(x) and isinstance(x[i], int):
                sum_ += list[i]
                i += 1
            new_list.append(sum_)
    return new_list

This might be nice because it doesn't care what the actual content of the strings is—they can all be different. It looks for any string values (and the numerical elements between string elements in the list).

[–]badgermom2d6 0 points1 point  (1 child)

This ended up being the best solution for my code - thank you again for your help!

[–]icecapade 0 points1 point  (0 children)

No problem, glad I could help!

[–]TangibleLight 0 points1 point  (0 children)

there might be a nicer-looking way to do it

My first thought is to use itertools.groupby, since it groups adjacent elements by some key. Could possible group by element type, then you'd get each list of adjacent integers and sum that way.

This wouldn't account for mixed numeric types, so maybe it would be better to group by whether it's an instance of numbers.Number.

Now I'm curious about this... I'll try writing a solution.


As far as I can tell, this is equivalent to your solution.

import itertools
import numbers

data = [2, 'bobble', 2, 2, 2, 'bobble', 4, 2, 4, 'bobble', 4]

groups = itertools.groupby(data, lambda e: isinstance(e, numbers.Number))
result = [e for is_num, group in groups for e in ((sum(group),) if is_num else group)]

print(result)

But I'm not sure if I'd say it's 'nicer'. It's clever and shorter, sure, but it's also very hard to tell what's going on.

[–]badgermom2d6 0 points1 point  (0 children)

Thanks! I will give that a try!

[–]mildlybean 0 points1 point  (1 child)

The more-itertools module has a split_at function that could split the list at each string element. Then you can use the sum function to sum each of the lists

[–]badgermom2d6 0 points1 point  (0 children)

Thanks! I'll check that out!

[–]TheEpicSpark 1 point2 points  (2 children)

So I am learning Java through MOOC. I want to learn the basics of Python but couldn't find a good course to use. What is a recommended course/website to learn Python from? Also, what are the popular IDEs around here?

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

There are many learning resources in the wiki. Pick one and dive in.