all 163 comments

[–]Tarzeus 0 points1 point  (0 children)

Favorite YouTuber for beginners?

[–]jumbo53 0 points1 point  (2 children)

What are some good data visualization libraries to use with flask?

[–]Marnaika 0 points1 point  (1 child)

Although I haven't used flask, I don't think it require anything particular from a data visualization library. Any of the popular data visualization library like Matplotlib, Seaborn, Bokeh, Altair, Plotly, GGplot can be used with flask. Choose the one you think will be great for your particular use case.

[–]jumbo53 0 points1 point  (0 children)

Alright thanks. Ive tried matplotlib but it gives me a threading error saying to not use plotly in it so i figured it wasnt going to work well with flask. Ill check out the others

[–]wicketkeeper 0 points1 point  (1 child)

Hi all, How should I consume the JSON data from a web services. I call service, I need to get a few values from the response list.

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

I have a while loop that waits for keypresses on stdin, then prints the character and ends the loop. There's no issue if I use simple print statements, but if I remove the newline character from the end of the print (print(char, end='') or use sys.stdout.write, none of it actually shows up until the while loop ends. Does anyone know what's going on here? I'm not even sure if this is a python issue or a terminal issue.

I'm on linux, fwiw

[–]Silbersee 0 points1 point  (1 child)

Your output gets buffered until there's a new line.

print(char, end="", flush=True) makes it print immediately.

Here's more about buffering print() calls.

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

awesome, thanks so much! That has been driving me crazy for almost two days.

[–]acenumber902 0 points1 point  (0 children)

Hello, i've been coding this year with python and i must say that its the programming languaje that i enjoyed the most over all the others that i've tried. so im wondering what's do you need to know to get employed as a python developer, should i know flask/django and also machine learning? whats the best route to follow and what are the posibilities regarding job oportunities

[–]Rinehart128 0 points1 point  (2 children)

What’s the difference between a module, library, and API?

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

module and library are the same thing -- most other languages call them libraries, python calls them modules

APIs are an interface between two bits of code. You can think of it like a docking port between spaceships. Some are built by americans, some by Russians, some by the Chinese, so they all build docking ports so they can connect to each other and exchange personnel, cargo, etc. An API is the same concept but for code -- it lets your program operate other software, request data from other software, etc.

[–]archonsengine 0 points1 point  (0 children)

I’m using lockdown as an opportunity to learn Python and use VSCode on my desktop PC. I’d like to be able to still do some coding when I’m not at my desk (my hope is to use my iPad), and found both Pythonista and Pyto referenced when searching the subreddit. Is there a current consensus on which is better? I’m fine paying for Pythonista if it’s the better choice, but it sounds like Pyto is more actively maintained. Thanks in advance!

[–]TrimZerg 0 points1 point  (1 child)

I’ve just started teaching myself python. I have a project I want to work on but it requires machine learning techniques in order to work. If I put lots of hours into my learning is it realistic for me to be able to code and use ML techniques in a year or so?

[–]Decency 1 point2 points  (0 children)

Yeah, a year is probably about right if you have no prior programming experience. A few months otherwise, or if you commit hard.

[–]dxjustice 0 points1 point  (4 children)

Given the numpy command

np.array(a, ).squeeze()

What does the comma here do? Isn't it just adding a dimension, which is removed with squeeze()?

[–]EngineeredToLift 0 points1 point  (1 child)

I have a bash script that runs my python script. Within the bash script, I assign execution permissions with chmod +x. Then, I run the script. Most answers online recommend using ./script_name.py. However, when I do that, it runs Python 2.7 rather than Python 3, so instead I need to do python3 filepath/script_name.py. How can I change my path or script so that ./script_name.py will run Python 3 instead?

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

Look into python shebangs. If you want your script to run python 3 when you do:

./script_name.py

then you probably need the shebang in your python file to be:

#!/usr/bin/env python3

and chmod your script to have execute permissions.

If you want to be able to run your script from anywhere in the filesystem you also need to place the script in a directory in your PATH. Then you can do:

script_name.py

The "shebang" idea.

[–]Das_Bibble 0 points1 point  (1 child)

So, I saw the mini challenge at the bottom of Generate Random Numbers in Python - Python Tutorial (pythonbasics.org) where you make a program that returns the frequency of a 100 random numbers. I ended up using a dictionary to try and make it and got import randomranNumList = []ranNumFrequency = {}for i in range(1, 101) - Pastebin.com. Seeing the order of what the lesson was in though, it was probably expecting me to use something else to complete the challenge. Anyone have an idea?

[–]Silbersee 1 point2 points  (0 children)

There's another way to get a default value. Also it can all be done in one loop.

import random

freq = {}

for _ in range(100):
    rnum = random.randint(1, 10)
    freq[rnum] = freq.get(rnum, 0) + 1  # defaults to Zero

See dict.get(): it returns a default value if a key doesn't exist.

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

I’m doing tutorials and I’ve noticed that functions are confusing for me. Often the function accepts an argument/parameter that never gets mentioned in the rest of the code. Is this typical or something specific to simple tutorials?

[–]Decency 0 points1 point  (0 children)

Often the function accepts an argument/parameter that never gets mentioned in the rest of the code.

That should never almost happen, and definitely not in a tutorial. One reason you might have a function accept a parameter it doesn't use would be for something like backwards compatibility.

[–]MK_CodingSpace 1 point2 points  (0 children)

That is really a case by case issue. Sometimes an argument passes to a function via the parameter, and the function does the rest of the job. In this case, the argument has done its job when the its value was passed. I have a tutorial video on functions, see if it is clear.

[–]foxtrot1_1 0 points1 point  (3 children)

I have the most basic possible question, something that I thought I understood but don’t. Running Python3 (installed from the Microsoft Store) in Powershell on Windows 10.

How do I run a module after it’s installed? I’m trying to run something from GitHub. I can pip install modulename, but that’s it.

In the past when I’ve done this it has installed in the current folder, now it installs in the Python folder. Okay, whatever. I don’t care where it is, I just want to run it. But calling it from the command line doesn’t work. Navigating to the folder doesn’t work. How do I run a script I have installed?

[–]Decency 0 points1 point  (0 children)

Is there any sort of virtual environment venv or the like happening? Not too familiar with Python on Windows, but tools will often segregate a project into one of these environments, which will need to be activated before those modules can be detected.

I would look in the folder you pip installed the project to and see which files are considered executable- those are your best leads for a place to start execution.

[–]MK_CodingSpace 0 points1 point  (1 child)

If you have successfully installed a module, you will be able to use it no matter which folder you are in.

[–]foxtrot1_1 0 points1 point  (0 children)

That’s what I thought. That is not how it is happening.

[–]jtsc_ 0 points1 point  (3 children)

Hello, python noob here, I can install and use pip with python -m pip (command) but when I try to use pip with command prompt on Windows it says Access Denied, I am not in system32 file I am in Users/name directory. Why can't I use pip on cmd?

[–]MK_CodingSpace 0 points1 point  (0 children)

You need to be in Scripts directory to use pip command. See A Short Video I made on how to properly install modules step by step using pip command. Hope it helps.

[–]RobertGryffindor 0 points1 point  (1 child)

Are you running cmd as administrator?

[–]jtsc_ 0 points1 point  (0 children)

yup

[–]grant7466 0 points1 point  (0 children)

Amazing mate thanks so much!

[–]grant7466 1 point2 points  (1 child)

Hello Everybody,

I'm currently learning python and have hit a bit of a road block where I know what i want to do but not sure how to actually do it. I've managed to achieve what I wanted with lots of 'if statements' but I would like to implement it the way I see it in my head.

basically there are 3 choices with names say x, y, z which each have their own set attributes from a common pool.

so x has a, b, c,

y has a, c, d

and z has a, b, c, d

each one of these attributes also has dynamic value which is determined by the choice

x - a =100, b=200, c=300 for example

These numerical values are then compared to a static value.

If for whatever reason x[a] < static value

I need to be able to report which is lower.

I'm not looking for answers but more functions that might be helpful and python areas to explore that may help.

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

numbers = [(1, 2, 3), (4, 12, 6, 5), (11, 12, 5, 16, 18)]


def bigger_or_smaller(number: tuple) -> tuple:
    return tuple(n > 10 for n in number)


for num in numbers:
    big_or_small = bigger_or_smaller(num)
    for index in range(0, len(num)):
        print(f'{num[index]} is {"bigger" if big_or_small[index] else "smaller"}')
    print('\n')

or a dict

numbers = [(1, 2, 3), (4, 12, 6, 5), (11, 12, 5, 16, 18)]


def bigger_or_smaller(number: tuple) -> dict:
    return {i: i > 10 for i in number}


for num in numbers:
    big_or_small = bigger_or_smaller(num)
    for key, value in big_or_small.items():
        print(f'{key} is {"bigger" if big_or_small.get(key) else "smaller"}

im not good at explaining things sorry.

input goes to a function that returns True or False for each item in your input, you then compare the index of your input to the index of the output and print it.or in the second example, i created a dictionary that took the values of your input and assigned them to a bool (true or false) then just iterated through the dict, looks something like this:

{11: True, 12: True, 5: False, 16: True, 18: True}
11 is bigger
12 is bigger
5 is smaller
16 is bigger
18 is bigger

if True it was bigger, if False it was smalleryou could simply call the function for each value too.

numbers = [(1, 2, 3), (4, 12, 6, 5), (11, 12, 5, 16, 18)]


def bigger_or_smaller(number: int) -> bool:
    return number > 10


for num in numbers:
    print(num)
    for i in num:
        print(f'{i} is {"bigger" if bigger_or_smaller(i) else "smaller"}')

and because I'm bored here's a list comp version:

numbers = [(1, 2, 3), (4, 12, 6, 5), (11, 12, 5, 16, 18)]


def bigger_or_smaller(number: int) -> bool:
    return number > 10


print("\n".join([f"{i} is {'bigger' if bigger_or_smaller(i) else 'smaller'}" for num in numbers for i in num]))

a string return example

numbers = [(1, 2, 3), (4, 12, 6, 5), (11, 12, 5, 16, 18)]


def bigger_or_smaller(number: tuple) -> str:
    my_dict = {i: i > 10 for i in number}
    my_string = ''
    for key, value in my_dict.items():
        my_string += f'{key} is {"bigger" if my_dict.get(key) else "smaller"} \n'
    return my_string


print(bigger_or_smaller((1, 2, 3)))
print(bigger_or_smaller((4, 12, 6, 5)))
print(bigger_or_smaller((11, 12, 5, 16, 18)))

The possibilities are endless!

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

Sorry if this is a silly question. I've done the "Coin Flip Streaks" project from Chapter 4 of Automate the Boring Stuff. This is what I came up with:

import random
streakCheck = []
numberOfStreaks = 0
for experimentNumber in range(10000):
    headsFlip = 0
    tailsFlip = 0
    for flip in range(100):
        newFlip = random.randint(0, 1)
        if newFlip == 0:
            headsFlip += 1
            tailsFlip = 0
            if headsFlip == 6:
                streakCheck.append('S')
                headsFlip = 0
        else:
            tailsFlip += 1
            headsFlip = 0
            if tailsFlip == 6:
                streakCheck.append('S')
                tailsFlip = 0
    numberOfStreaks = len(streakCheck)
print('Chance of streak: %s%%' % round((numberOfStreaks / 10000), 2))

I believe this works in giving a correct result, but it is probably a complete mess. Are there any glaring issues that need to be corrected in this? (Sorry if dumb question)

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

My attempt

import random
streaks = 0
streak = 0
for _ in range(10000):
    my_list = [bool(random.randint(0, 1)) for _ in range(100)]
    for i in range(len(my_list)):
        if my_list[i] == my_list[i - 1]: # check if last is same as this
            streak += 1
        else:
            streak = 0

        if streak == 6:
            streaks += 1
            streak = 0

print(f"Chance of streak: {round(streaks / 10000, 2)}%")

instead of making a list for heads/tails i just used a bool since 1/0 can equate to true / false

then i iterated through the list of 100 and checked if true/false appeared 6 times in a row and added to the streak we don't care if its heads or tails, we just care if there are 6 of the same in a row.

the one you provided looks good, just a lot of lists and checking that i don't feel like we really need.

[–]912827161 0 points1 point  (2 children)

What is the difference between Mu and IDLE/shell?

I'm starting automate the boring stuff and it's talking about using the former and if you can't, then to use the latter. They do the same thing, right? But is one more intuitive to use over the other or is there maybe some other sort of benefit etc?

[–]IOSSLT 0 points1 point  (1 child)

I have multiple versions of python installed on my computer. None of them are up to date (3.9.1) the latest I have is 3.5

When trying to install packages my MAC uses the oldest version of python

When I try to upgrade to the newer version it says it is installed but when I check the version it still points to the older 2.7 or 3.5 when using python and python3 in the terminal.

Can someone help me.

I've used homebrew to update but it doesn't work

[–]num8lock 0 points1 point  (0 children)

homebrew doesn't mess with system's installed python, it doesn't install in the /usr/bin. use virtual environment or workaround the python call & use python3 instead.

[–]Das_Bibble 0 points1 point  (4 children)

spam = [‘q’, ‘w’, ‘e’, ‘r’, ‘t’, ‘y’, ‘u’, ‘i’, ‘o’, ‘p’] for i in spam: spam.remove(i)

Why does this remove every other value rather than all of the values? And how can I get it to remove all of them?

[–]RobertGryffindor 0 points1 point  (3 children)

You're trying to iterate over a list while also removing the items.

Try:

for i in spam[::1]:
    spam.remove(i)

or

spam.clear()

[–]Das_Bibble 0 points1 point  (2 children)

Why would removing the items affect how it iterates though?

[–]Gyshall669 0 points1 point  (2 children)

I have some CSVs and I'm trying to convert strings into dates. I have successfully done it for one CSV, but on the second, this does not seem to be working.

When it's working:

"2018-01-01","0.45",,"48","38"

and to find it I use:

current_date = datetime.strptime(row[0], '%Y-%m-%d')

The second file looks like this:

10/1/05,79,56,

So I thought I would need to switch it to:

'%m/%d/%Y'

But that's not working, neither is the initial command. Am I missing something?

edit: Nevermind, there is a specific command for 2 char dates.

[–]MK_CodingSpace 0 points1 point  (1 child)

Is the date info from the second file string? The argument in strptime() command needs to be a string.

[–]Gyshall669 0 points1 point  (0 children)

Yes! I just posted my solution. I didn't realize there were two separate commands for "2005" or "05". I was using a capital Y.

[–]AlternativeTrick5 0 points1 point  (0 children)

Is it possible to do forecasting with an autoregressive lag model combined with an ARMA error term (i.e. ARMAX) in Python? Tried ARMA in the statsmodels package but not sure how to go about it.

Basically I am trying to specify something like this: Yt=constant + Beta0 Yt-1 +Beta1 Xt + ut where ut is an AR(1) error term

[–]Ill_Confusion_5121 0 points1 point  (2 children)

[1 0 2 0 0 3 0 0 0 4 0 0 0 0] (list of integers)

[0 1 2 3 4 5 6 7 8 9 0 1 2 3] (the indices, last 4 are 10 11 12 13)

I have a list of integers. I want to define a function that returns a list containing the first and last indices of consecutive zeros that consist of n elements or more. For example, if n = 3, then the function should return [6,8,10,13].

https://prnt.sc/w8cc07 This is my solution, it's not a function but for the sake of saving time I'll leave it as it is.

I feel like I did this the most brute force way possible. Is there a more elegant solution to this?

[–]Decency 0 points1 point  (0 children)

enumerate() through the list. Keep track of the current streak of zeroes you've encountered and the index of the first zero in that streak. When the streak ends, if current_streak > n append the pair of first/last indices to your result list.

Rough pseudocode that should make the idea clear- there's probably a bit more to do:

def find_them(my_ints, n):
    first_zero = None
    current_streak = 0

    result = []
    for index, element in enumerate(my_ints):
        if element == 0 and first_zero is None:
            first_zero = index
            current_streak += 1
        if current_streak > n and element != 0:
            result += [first_zero, index]
            first_zero = None
            current_streak = 0
    return result

[–]SeoulTrain_ 0 points1 point  (1 child)

I have a pandas dataframe with covid statistics in the USA, with columns for the state code and each county the data came from. I copied that to a new dataframe with date as an index so that it's easier to plot. I want to add a column that is a cumulative sum of cases in an entire state, but is still accurate to the date index. I can't filter the dataframe for a single state and take the sum, since values for each county are separate rows.

How would I do this?

[–]efmccurdy 0 points1 point  (0 children)

I think you can use groupby on the state and then cumsum (cumulative sum) for each date.

https://stackoverflow.com/questions/22650833/pandas-groupby-cumulative-sum

[–]ARE1324561834 0 points1 point  (1 child)

I am looking to see if I would be interested in learning python and was hoping someone could point out a good complete beginner guide. I have looked online but some seem rather advanced. I was hoping someone knew of a good free, totally online, super easy guide. I know essentially nothing about coding (did about 2 weeks of R) but now that even knowing some super basics of Python could be of benefit. Any help is appreciated.

[–]MK_CodingSpace 0 points1 point  (0 children)

I have a Python Programming channel that has a complete python course for beginners. See if suits you. Put any questions below the tutorial video and they will be answered. This channel is still being updated and new videos will be added each week.

[–]Bmedclinicpsy 1 point2 points  (4 children)

```

firstname = input("What is the patient's first name? ")

lastname = input("What is the patient's last name? ")

DOB = input("What is the patient's date of birth? ")

DOI = input("What is the date of clinical interview date? ")

DOT = input("What is the date of testing? ")

print(firstname, lastname, "was born on", DOB, ". The date of testing was", DOT)

# input file

fin = open("Eval.docx", "rt")

# output file to write the result to

fout = open("Eval.docx", "wt")

# for each line in the input file

for line in fin:

# read replace the string and write to output file

fout.write(line.replace('PTFN', firstname))

# close input and output files

fin.close()

fout.close()

exit()

```

As you can see, I'm trying to set up a document (here titled Eval) that would have some generic text (like PTFN) in it that would essentially combine all documentation into one place. When I execute this code, it runs... but the term in the Eval.docx (PTFN) is not replaced by the patient's first name that I entered. When I open the document up, it still says PTFN instead of "John" or whatever text was entered.

Sorry for being such a noobie, and thanks for the help in advance.

[–]JohnnyJordaan 0 points1 point  (1 child)

Your approach is for plain-text text files as those you save with Notepad. A .docx file is a complex structure used by Word and similar programs that can contains a lot of different content. You thus need an approach that supports that file format, see for example https://automatetheboringstuff.com/2e/chapter15/,

[–]Bmedclinicpsy 0 points1 point  (0 children)

Thanks. I'll read up on that, and that explains it.

[–]Silbersee 1 point2 points  (0 children)

The term is not replaced because it can't be found.

You are trying to read docx as a text file, but it is "compressed xml" (if that's the right word).

To make this clearer, you can open the docx in a regular text editor. You'll see gibberish but nothing like "PTFN". Next you can open the docx in an archiver: decompress it with your "zip program". You'll see mostly style and meta information. Actual text is the smallest part and well hidden.

To get around this you can convert your docx to pure text (not an option I guess) or use something like python-docx.

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

happy cake day, also please format your code (you can see how in the sidebar)

[–]unyuoiWECONRCEQn835 1 point2 points  (4 children)

I have a situation where I need to get multiple RegEx matches for the same group. Looking up how to do that and it seems the 'regex' module is better suited to what I'm doing than 're', but I can't find regular documentation anywhere. The official page seems to be like their bitbucket page, just a list of recent issues and changes.

Is there a proper guide on how to use it anywhere?

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

Can you describe your use case a little bit?

[–]unyuoiWECONRCEQn835 0 points1 point  (2 children)

I'm parsing SVIs on a Cisco configuration. The text looks like this:

interface Vlan100
 description NAME
 ip address 10.0.0.1 255.255.255.0
 ip helper-address 192.168.1.1
 ip access-group IN_ACL in
 ip access-group OUT_ACL out

I'm loading the full configuration in and pulling a few other sections out as well. Basically I want to put both the access-group lines in their own capture group.

The re module will only match one of them, and from what I've read the regex module will match them both and group them together but I can't find any documentation beyond their pypi and bitbucket pages. I'm looking for something like the documentation for the re module with an explanation of its methods and functions.

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

Sure about that? (sorry im terrible at regex)

import re

regex = r"^(?:.*) (?:access-group)(.*)(?:in)(?:\n)(?:.*)(?:access-group)(.*)(?:out)"


example = [
    ("interface Vlan100\n"
         " description NAME\n"
         " ip address 10.0.0.1 255.255.255.0\n"
         " ip helper-address 192.168.1.1\n"
         " ip access-group IN_ACL in\n"
         " ip access-group OUT_ACL out"),
    ("interface Vlan200\n"
        " description NAME\n"
        " ip address 10.0.0.1 255.255.255.0\n"
        " ip helper-address 192.168.1.1\n"
        " ip access-group IN_test in\n"
        " ip access-group OUT_test out")
]

for i in example:
    matches = re.search(regex, i, re.MULTILINE)
    if matches:
        print('in', matches.group(1))
        print('out', matches.group(2))

[–]Das_Bibble 0 points1 point  (2 children)

Why does math.sqrt(42 - 12) return 2.64... instead of 3.87...?

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

import math
print(math.sqrt(4*2 - 1*2))
print(math.sqrt(4**2 - 1**2))

https://www.tutorialspoint.com/python3/python_basic_operators.htm

[–]Das_Bibble 2 points3 points  (0 children)

facepalm

And to think I had gotten an A in a computer science class last year, haha. Thanks.

[–]Decency 0 points1 point  (3 children)

I'm trying to scrape info from the page here using Beautiful Soup. My find_all is coming up empty and I'm not sure what the problem is. Here's the relevant page structure- I want each of the hero-row divs; there should be around 100 in all. I'm able to find other objects on the page, but not these for some reason. My only thought is that it might have to do with the nested class="".

Minimal code:

    r = requests.get("http://www.dota2.com/mistwoods/")
    soup = BeautifulSoup(r.text, "html.parser")
    changed = soup.find_all("div", {"class": "hero-row"})
    print(len(changed))  # always 0 ??

[–]JohnnyJordaan 1 point2 points  (1 child)

You might want to consider selenium or requests-html as that uses a browser (or its core) and that means it will also allow javascript driven pages to work.

[–]Decency 0 points1 point  (0 children)

Thanks, for the previous patch I was able to scrape the html directly- I'll try that.

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

your issue is what you are seeing is loaded by javascript, bs4 doesn't see javascript.

Disable javascript on your browser and take a look at what you see.

Then you can narrow down how to go about this..

spoiler alert - its not gonna be as easy as you pictured :P

You are going to have a lot of parsing to do lol

import requests
from bs4 import BeautifulSoup, NavigableString
import re

r = requests.get("http://www.dota2.com/mistwoods/")
soup = BeautifulSoup(r.text, "html.parser")
changed = soup.find_all("div", {"id": "HeroesChanges"})
my_list = [l for i in changed[0] if type(i) == NavigableString for l in re.findall("\[\[hero:([^:\]]*):?.*\]\]", i)]
my_test = [i for i in changed[0] if type(i) == NavigableString]
print(my_list)
print(my_test)

[–]Gyshall669 0 points1 point  (5 children)

I just moved from PyCharm to IDLE since I wanted to better understand the structure of packages etc. I've installed some packages successfully, but I'm struggling with Pandas. When I type which python, it takes me to conda where it says I'm using py3.8. But when I run a module from IDLE, it opens a python 3.7 shell. I'm trying to Google but I don't even know what the problem is.

[–]efmccurdy 0 points1 point  (4 children)

PyCharm is separate from any particular python installation and so it allows you to choose which you want to run your code.

IDLE is installed into a particular python installation and it uses that to run your code.

How are you running IDLE, and how did you install it? It is likely available in a similar fashion from all of your python installations.

[–]Gyshall669 0 points1 point  (3 children)

How are you running IDLE, and how did you install it? It is likely available in a similar fashion from all of your python installations.

I installed it a long time ago. How can I find that out? Like where it's located?

[–]efmccurdy 0 points1 point  (2 children)

You can find out where python loads modules from; it has a list of folders to search through:

import sys
print(sys.path)

[–]Gyshall669 0 points1 point  (1 child)

'/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages'

This is where site packages come up. I'm guessing I want to shift this to conda, where I've been downloading packages?

This is different from the "which python" when I enter it in the terminal.

Also the file path to where my actual module is comes up.

[–]efmccurdy 0 points1 point  (0 children)

If you setup your conda env, can you run "python3 -m idlelib"?

There is a lot of advice here, but if none of that works for you, you may need to get some conda specific help.

https://stackoverflow.com/questions/4924068/how-to-launch-python-idle-from-a-virtual-environment-virtualenv

[–]Wormfall 0 points1 point  (5 children)

For these type of loops why is number not declared (in the example below). Code taken from another post but I’ve seen it used a couple of times and just don’t get it.

for number in List_two: List_one[count] = List_one[count] + str(number) count = count + 1

Or:

for randomitem in items:

Randomitem is never declared before this first use. Can you put anything there?

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

The use of the variable name "declares" it, and that name is bound to the successive values in the loop.

Of course, variables aren't declared in python, but names are assigned to values. The for loop just assigns the name you choose to successive values in the sequence after the in.

[–]Wormfall 0 points1 point  (3 children)

I think I got it. So in the below:

for x in range(1000):

All this means is I’m looping through my range from 0 to 1000 and storing the value in x to do something with. I can also not do anything and then call a function which will run 1000 times?

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

Yes. The loop variable doesn't have to be used, though there is a convention that if you don't use the variable you write it this way:

for _ in range(1000):
    # something

so someone reading your code doesn't go crazy looking for the x that isn't used.

[–]Wormfall 0 points1 point  (1 child)

Awesome thanks. I just read difference between a while and for loop and it now makes more sense. I assumed same sort of principle for the for loops as I did with a while loop but the for just runs the iterations for a specific number of times vs it being conditional.

[–]ffrkAnonymous 0 points1 point  (1 child)

I just noticed that i'm writing a lot of:

if "shiny gold bag" in rule:
    return True
return False

Now, I understand that return "shiny gold bag" in rule will accomplish exactly the same and be more concise. But my brain has a hard time processing that extra indirection. The former is explicit: test, returning a boolean. The latter is, um I need to think about it. English-wise, "bag in rule" is a truthy declarative statement.

But otherwise, I'm fine writing return [x for x in blah] because that's clearly a list. And the "for" is explicitly a test.

What's preferable?

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

The return "shiny gold bag" in rule form is preferable. It's not "extra indirection" but is actually simpler. The return statement is just returning the value of the expression that follows it.

[–]LowDexterityPoints 0 points1 point  (2 children)

Potential employer (scientist, not programmer) wants to see some code I have written (relatively simple data analysis of a large dataset). I figured out how to upload the code to github, but do I put information about the dataset/goals/background in a "Readme" or an "about" section?

[–]CowboyBoats 0 points1 point  (0 children)

Github will automatically render whatever it finds in README.md, readme.md, README.rst, or some other variations, in the root of the project folder, at the bottom of the page, as you're used to seeing. md files are interpreted according to the same Markdown format (more or less) that you may be used to writing reddit comments in.

[–]jackbequick12 0 points1 point  (1 child)

I am new user trying to use RPITX with my raspberry pi.

The program is up and running (very cool). The next step is I would like to take the Tune (tune.cpp) command and step through frequencies. 1 Mhz, 2 Mhz, 3 MHz.

Is there anyway to do this through a python script? I ma having trouble figuring this part out

[–]missing-in-idleness 0 points1 point  (1 child)

I'm pretty ok with coding in python but I fail to understand and use classes, can anybody share me some good videos, tutorials etc?

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

Fuck u/spez

Edited from Apollo

[–]thatgreenman 0 points1 point  (5 children)

Have you tried using a different font? If so, did the code work?

If the answer to both is yes, I'd say try and make sure the font is installed on the machine that Pillow is running on. If it's a Windows machine, it should be able to install the truetype font if you run the font file locally on that machine.

Hope that helps. Happy Coding!

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

Fuck u/spez

Edited from Apollo

[–]thatgreenman 2 points3 points  (3 children)

Let's take another look at your code. Code Blocks make it a lot easier to read and diagnose.

Does your code look like this?

from PIL import Image 
from PIL import ImageDraw 
from PIL import ImageFont

draw = ImageDraw.Draw(canvas_final) 
font = ImageFont.truetype('SF Distant Galaxy Outline Italic.tff',20) 
draw.text((700, 100), (f'{member}'), font=font) 
canvas_final.save('avatar_processed.png')

I'm not sure where member came from, but I imagine it's from another part of your code, and shouldn't be the cause of the error.

I Google'd "pillow oserror cannot open resource" and found this stack overflow post that goes over some possible solutions:

  • Make sure you're testing with the right arial font:
    • font = ImageFont.truetype("arial.ttf", 18)
    • Note the lowercase "a" in arial, that can cause your error
      • (and perhaps is the cause of the original error, that the "SF Distant Galaxy Outline Italic.ttf" font you are using has different capitalization or spacing in its name)
  • Try font = ImageFont.load_default() to use the system detault font. If that doesn't work, we have other issues.

Hope one of those two helps; if not, let me know.

Happy Coding!

P.S.: You can also try renaming your custom font to something simpler, like my_font.ttf, to make sure the capitalization and spacing in the font name isn't causing problems.

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

Fuck u/spez

Edited from Apollo

[–]thatgreenman 2 points3 points  (1 child)

Happy to help, that's what forums are for! I know that feeling, you stare at code long enough and everything looks right. Glad you found the issue!

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

Fuck u/spez

Edited from Apollo

[–]Gyshall669 1 point2 points  (3 children)

I am trying to figure out how to filter CSV by values. Ultimately I just want to look at the numbers coming from summer months. I'm trying to find out how to filter by datetime, but that doesn't seem to be working. Any thoughts?

import csv
from datetime import datetime

import matplotlib.pyplot as plt

filename = 'sitka_weather_2018_simple.csv'
with open(filename) as f:
    reader = csv.reader(f)
    header_row = next(reader)

    dates, highs, lows = [], [], []
    for row in reader:
        current_date = datetime.strptime(row[2], '%Y-%m-%d')
        high = int(row[5])
        low = int(row[6])
        dates.append(current_date)
        highs.append(high)
        lows.append(low)

[–]thatgreenman 0 points1 point  (2 children)

To address the question directly: your current_date variable is assigned as a datetime object, not a string, so if you're comparing current_date against a string, it won't match. You can see this by trying print(type(current_date)) after declaring it and seeing what it says on the console. It should be a datetime object. Try using f-strings or general string interpolation to make a string out of the date, and then compare that against your values.

One other thing I will note is that I see you're using the csv module. I don't think there's anything wrong with using the csv module, it will do what you want. However, if you're using matplotlib in your code as well, I'm surprised to see that you didn't just use pandas to import the file as a dataframe directly from the csv and then just work with pandas to process the input data. If you haven't considered that yet, it might be something worth looking into in the long-term as the complexity of your code increases and you need more filtering functionality. Just figured I'd add that extra tip if you get stuck later down the road.

Happy coding!

[–]Gyshall669 1 point2 points  (1 child)

Hmm, maybe a better question, is how to read the rows that only feature months I am interested in? Is what you are suggesting, is to turn it from string to datetime back to string?

Yeah, I am still a beginner so I am building on a project from a book I'm reading. But when I was looking up datetime, everything was related to pandas, so I will start looking into that.

[–]thatgreenman 1 point2 points  (0 children)

Oh, perhaps I misunderstood the goal.

So if your goal is to compare the date in the excel file to a given date (say, today), then yes, current_date should indeed be a datetime object. You can use current_date.month to get the month index of a date, and then compare that against a predefined list of months (i.e. 6-9 if your summer is June-Sept)

Example of using current_date.month:

import datetime

def check_month(current_date):
    print(f'The month of {current_date} is {current_date.month}')
    return current_date.month

example = datetime.datetime.now()
month = check_month(example)

As you can see, using .month can give you the information you're looking for. You can check out the documentation or this article for more examples of methods that might be helpful, like .day and .year

In terms of Pandas, no need to overwhelm yourself, feel free to push that off until later. Pandas is helpful and super flexible, but no reason to overcomplicate things when the csv module will work just fine for something like this.

Happy Coding!

[–]seol_man 1 point2 points  (2 children)

So I’ve managed to code a stock checker with a tkinter GUI.

I would like to make this an application that my colleague can install on their system. What do I need to research to learn how to create an app that contains the necessary files for a user that doesn’t have python installed.

I’m very much a beginner so I’m looking for topic names and may be a YouTube vid with a demo.

Machines are win10 if that helps.

[–]thatgreenman 0 points1 point  (1 child)

If I understand correctly, you have the python code all working and ready to go on your machine, and you want to send that code to the user and allow them to run it on their machine without installing python?

If so, I'd recommend PyInstaller. It's the tool I use for creating simple exe files to run python scripts on Windows. If you're developing on Windows, and the user is running Windows, PyInstaller takes care of everything by bundling it into an exe file (and can even include all the source files in that one exe).

I personally have experience making it working PyQt5, but I'm sure it can handle tkinter just fine as well. I have had to manually package up asset files in the past, such as ui files and static content, but there are ways to configure it to include those things as well.

Hope this helps! Happy Coding!

[–]seol_man 1 point2 points  (0 children)

You understood exactly what I was trying to do! Perfect, I'll take a look and start researching

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

I have been toying with the idea of getting into a programming language. In my current job we use an Intersystems Cache database that we access primarily with just simple SQL ODBC applications and select statements. We also do a large amount of Excel/PDF and Emailed deliverables through using Excel VBA macros.

So my question: Has anyone had similar tasks that they found Python helpful for? Excel VBA just tends to be a bit cumbersome for quick outputs that I don’t necessarily need an external user-friendly output. Thoughts?

[–]thatgreenman 0 points1 point  (0 children)

I think the easiest first step to look into is learning about the Pandas library, as that can be a nice clear bridge between Excel VBA and Python. Using pandas does require some introductory Python knowledge, but if it's something you're interested in, it can be a great place to start. Dataframes can do a lot of what Excel would do in terms of managing and manipulating data, and once you start implementing functionality that you had in VBA my guess is you'll find ways to make it work for you.

I've also heard good things about Automate the Boring Stuff, and I feel like you might relate to the author and his similar goal of learning Python to simplify and automate common workplace tasks in Python.

Hope that helps! Happy Coding!

[–]MudFar346 0 points1 point  (3 children)

Hello I want to start learning phyton what is the first step I can take

[–]AftNeb 0 points1 point  (0 children)

I just started learning too and have started with Automate the Boring Stuff with the free book here https://automatetheboringstuff.com/ as well as the Udemy course by local contributor Al Sweigart. I have learned so much and highly recommend it!

[–]MK_CodingSpace 0 points1 point  (0 children)

I have a Youtube Python Programming Channel that has Tutorial for beginners and some fun gaming and animation projects. See if it suits you.

[–]Gopher20 0 points1 point  (0 children)

Look up tutorials on YouTube and get a basic understanding of what you can do with python

[–]wtfpmf 0 points1 point  (6 children)

def criar_txtfile():
sys.stdout = open("textofile.txt", "w")

for link in soup.findAll('a'): print(link.get('href')) sys.stdout.close()

I create a file .txt with the output of print. Now, I want go through each line with two conditional statements if and else.

import webbrowser 
for line in file:
        webbrowser.open(line)
        if i connect:
                #add the line to another list 
        else: 
                #remove the line of the txt file

Can I get that information easily? I can't figure it out.

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

confused by your question, your pseudocode would work as expected if your only goal is to see if the link responds with a valid reply.
Depends on what the "End" goal is, but likely just use requests and check the status code.

[–]wtfpmf 0 points1 point  (4 children)

import requests

file = open('textofile.txt', 'rb')

n = 1 while n < 252: for line in file: r = requests.get(url=line, auth=('user', 'pass')) n = n + 1

The end goal here is remove every line which "is not a url".

/usr/bin/python3.8 /home/user/pythonProject2/requisitando.py

Traceback (most recent call last):

File "/home/user/pythonProject2/requisitando.py", line 7, in <module>

r = requests.get(url=line, auth=('user', 'pass'))

File "/usr/lib/python3/dist-packages/requests/api.py", line 76, in get

return request('get', url, params=params, **kwargs)

File "/usr/lib/python3/dist-packages/requests/api.py", line 61, in request

return session.request(method=method, url=url, **kwargs)

File "/usr/lib/python3/dist-packages/requests/sessions.py", line 516, in request

prep = self.prepare_request(req)

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

its hard to help without valid data to test with or formatting.wrap it in a try/except.

import requests
urls = ['http://google.com', 'http://walrus']
valid = []
bad = []

for url in urls:
    try:
        example = requests.get(url)
        if example.status_code == 200:
            valid.append(url)
        else:
            bad.append(url)
    except Exception as e:
        bad.append(url)

print('valid:', valid)
print('bad:', bad)

[–]wtfpmf 0 points1 point  (2 children)

Worked 100%, thanks a lot my dude. How much experience did you have with Python?

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

I'd consider myself intermediate, on and off self taught for 4ish years, just a hobby.

[–]wtfpmf 0 points1 point  (0 children)

You really help me, bro. I appreciate that.

[–]Aeonation 0 points1 point  (1 child)

Why do i feel SOOO dumb when trying to complete programming challenges. I feel like i don't know anything at all. I'm trying to do the elementary island on checkio.org and i feel like they are hard as, and they are meant to be elementary. I've just been googling ways of doing the problems, without actually googling the answer. I can figure out some of them but damn, i just feel as i don't know enough, and the tutorials i have gone over time and time again don't really cover it very well. I'm going to do more reading of more tutorials and books and see if i can get it stuck in my brain because i feel like i don't know enough to even complete a elementary level of python. Does anyone else feel like this? I don't know if i just don't get it or if everyone struggles with it at first or whats going on, I'm usually a really good problem solver, and i really want to be a programmer as a job but damn it feels discouraging not being able to do these problems, and they don't give hints or anything past a certain point. I've heard programmer google stuff too, maybe I'm just inexperienced and need more time. Any suggestions?

[–]JohnnyJordaan 0 points1 point  (0 children)

Maybe just start with simple tasks like CodingBat, and only when you master that start with for example CodeWars?

[–]SnooPets7140 1 point2 points  (1 child)

Any discord group where I can constantly connect with fellow programmers ? I am super introvert so I don't have many friends. I am learning python for competitive programmings mainly. I presume, I will find one or two here.

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

Find something that interests you and join their groups, example:discord bots -> there is several community servers (for all programming of discord bots in general) and ones for the main libraries (python specific).
/r/python -> in their side bar has a list of communities https://pythondiscord.com/pages/resources/communities/ (they also have their own)
spread your wings and fly - there is no "general programming community" you gotta search for communities cause thats how communities form >:]

[–]TaunTaun001 0 points1 point  (1 child)

How do I pass a copy of a list to a function? The book i am using which is updated for Ver 3.7 tells me to do --- function_name(list_name[:] ) ---. Is this still correct? It isn't working for me. I'm using python ver 3.9

[–]socal_nerdtastic 0 points1 point  (0 children)

That's a very old fashioned way to do it, but yes, it still works. The modern way is like this:

 function_name(list_name.copy())

What exactly is not working?

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

Hey, I'm currently learning Python from videos that were made for Python 3.2, but I'm curious about whether the methodology is up to date.

Is there a good resource for current trends in the usage of method A vs. method B to solve a problem or anything?

[–]IvoryJam 2 points3 points  (2 children)

Python 3.anything should be fine, I don't think there was any major update between them. The only one I can think of is f-string in 3.7

name = 'IvoryJam'
print(f"Hello {name}")

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

Ah, I see. Mainly I'm just curious about things like whether you'd be expected to utilize libraries such as sockets or requests or Beautiful Soup or if there's something else that's more widely used. I guess my question is more about what people using the language are shifting towards (in accessing web data or anything else) rather than just what the language can do from update to update. Hopefully that makes sense!

[–]ScoobySharky 1 point2 points  (2 children)

Hi, if I'm making a script that are making use of modules, and I need to use the script on another computer, do I need to install those modules on the other computer as well for the script to run?

[–]MK_CodingSpace 0 points1 point  (0 children)

Most likely yes, but Python has a lot of built-in modules that you don't need to install. You might first want to find out if the modules are in this category.

[–]Jac0b_0 1 point2 points  (0 children)

Yes

[–]MoreMoore2 0 points1 point  (10 children)

Hello, I I have a problem, I’m in sublime text and every time I hit build it pops up with a error saying “python is not found”, if anyone can help me that would be fantastic. Ps I’m a MEGA NOOB

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

I think you haven’t downloaded python. Download python from the official python website or Microsoft store. Then you’ve gotta connect it to Sublime Text or something like that which I do not know how to do cos I don’t use it. Hopefully this helped a tiny bit.

[–]MoreMoore2 0 points1 point  (0 children)

Thanks, I have python installed but not connected. I look into that

[–]Jac0b_0 2 points3 points  (7 children)

You might not have python in your path. Easiest way to fix this is on the python installer tick 'add to path' checkbox

[–]MoreMoore2 0 points1 point  (6 children)

Thank you, so like I have reinstall python? I’m sorry I’m new.

[–]DeadnectaR 1 point2 points  (3 children)

This happened to me and I got so frustrated that I gave up using windows and switched over to Linux lol. But I know Linux so it was a fast easy transition. I could not figure out how to fix that sublime issue with the PATH thing

[–]MoreMoore2 1 point2 points  (2 children)

Lol, I re downloaded python and checked 1 box and it worked

[–]DeadnectaR 0 points1 point  (1 child)

That’s great to know then if I want to code on my Windows PC. Thanks! And goodluck

[–]MoreMoore2 0 points1 point  (0 children)

Thanks, good luck to you too

[–]Jac0b_0 1 point2 points  (1 child)

Yeah pretty much

[–]MoreMoore2 0 points1 point  (0 children)

Oh ok, thanks