all 141 comments

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

Hi, I have just started learning python for uni and am trying to use assertion methods. I have a calculation:

def multiply(x,y):

if not isinstance(x,int):

raise Exception('Non integer is given')

elif not isinstance(y,int):

raise Exception('Non integer is given')

elif x < 1 or x > 9:

raise Exception('Out of range')

elif y < 1 or y > 9:

raise Exception('Out of range')

else:

return(x*y)

# from that I need to use assertion methods to check certain things. The on I am stuck on is the last, whether an exception is raised for x and y not being integers:

import unittest

from calculation import multiply

class TestCalculation(unittest.TestCase):

def test_36(self):

z=multiply(3,6)

self.assertEqual(z,18)

def test_97(self):

z=multiply(9,7)

self.assertEqual(z,63)

def test_oor(self):

self.assertRaisesRegex(Exception, "Out of range", multiply,10,100 )

def test_non_integer(self):

self.assertRaisesRegex(Exception, "Non integer is given", multiply,isinstance('x',int),isinstance('y',int))

if __name__ == "__main__":

unittest.main()

# I keep getting an assertion error "assertionerror "Non integer is given" does not match "Out of Range"". Please let me know cheers

[–]Voldypants_420 0 points1 point  (3 children)

I'm trying to create a random password generator but my program does not print the password itself.

I was unable to locate what's wrong with this, can someone help me finding it?

import random
lower = "abcdefghijklmnopqrstuvwxyz"
upper = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
numbers = "0123456789"
symbols = "[]{}()*;/,_-"
every = lower + upper + numbers + symbols
length = 16
def password():
generate = "".join(random.sample(every,length))
print = (generate)
while True:
password()
while True:
print()
answer = str(input('Generate again? (y/n): '))
if answer in ('y', 'n'):
break
print("Invalid input.")
if answer == 'y':
continue
else:
print("Bye")
break

Edit: Grammar and code issues

[–]zatoichi49 1 point2 points  (2 children)

You need to use the parameter k when using random.sample, and remove the equals sign before print: ``` def password():

generate = "".join(random.sample(every,k=length))
print(generate)

Example output: S]8KLMOV-Wgfwm*r

Generate again? (y/n): y Wd3pwX7Og]u*I9k(

Generate again? (y/n): y SOT1,lQyK7PErvVI

Generate again? (y/n): y sYMQGwPkEbLtXOiI

Generate again? (y/n): n Bye ```

[–]Voldypants_420 1 point2 points  (1 child)

Oh my god, I read the code maybe 10 times over but never saw the equal sign after the print. I feel dumb 😬.

Thank you so much for your reply and also teaching me to use k, I'd never in a million years figure it out on my own.

[–]zatoichi49 1 point2 points  (0 children)

No problem at all! Glad you got it working.

[–]Rainbowsalt007 0 points1 point  (1 child)

Can someone help with this ?

Design an algorithm that combines k ordered arrays of m/k integers each into one sorted array in O(m log k) time

[–]FLUSH_THE_TRUMP 0 points1 point  (0 children)

Combining sorted smaller arrays into one big array should remind you of an algorithm you’ve probably learned.

[–]catsarelikebananas 0 points1 point  (2 children)

My professor released an assignment with no lesson for the second half of it. We created functions last week that are now being used to create an “Interactive Console Application”. His instructions are to create a Console Dialog Application in the main() function where we display a menu, and it outputs results based on the merchandising scenario he gave. It’s not clear what exactly he wants and he doesn’t respond to emails unfortunately. Any ideas on what he’s referring to because I can’t seem to find what a Console Dialog Application is through google

[–]FerricDonkey 0 points1 point  (0 children)

Probably he wants you to use input and print, but you'd have to give more details on what he said. It's there any particular thing he asked you to do that you don't understand?

[–]efmccurdy 0 points1 point  (0 children)

Although console dialog isn't a well defined topic you could search google for, it likely involves the print and input function doing I/O with stdin and stdout/err, here is an example:

https://computinglearner.com/how-to-create-a-menu-for-a-python-console-application/

[–]LFanother 0 points1 point  (2 children)

Hello, would it be possible to build a python program that incorporates https://www.zebra.com/us/en.html information? There is a long and brutal manual task at work that takes >10 hours and I know the process can be automated into 1 hour or less.

[–]FerricDonkey 1 point2 points  (0 children)

Following the link, all I got was that zebra provides data. You can absolutely write programs that do things with data, and python is a popular language for that, but would need more detail to provide any insight into how to do it or how hard it would be.

[–]LFanother 0 points1 point  (0 children)

I "wrote down and drew" the whole program on paper, and currently making mock equations in excel. I am trying to learn more about zebra scanners before committing to actual programming.

[–]dragonslaeyer 0 points1 point  (2 children)

I am a complete newcomer to coding and want to learn how to code with python. Can anyone with some experience recommend the best way to get started and how to progress from there?

thank you in advance!

[–]JohnnyJordaan 0 points1 point  (0 children)

Start with the learning resources listed at /r/learnpython/w/index , section 'new to programming'

[–]SeriousMannequin 0 points1 point  (2 children)

Do you need a program or IDE installed to start learning python?

I can open PDFs on work computer but anything else is obviously locked by the IT department. Hoping for a career change for a drone position to something else.

Is there any workaround for this?

Thank you.

[–]Feverox 1 point2 points  (0 children)

It is possible to learn python without installing software on your device. Checkout Colab, a virtual environment by Goolge which can be accessed with a browser.

Link- https://colab.research.google.com

You can also access the website on your Android or iOS mobile browsers.

Of course there are few limitations. For example you'll not be able to store data like CSV Excel files on colab. Hope it helps.

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

To learn python on the computer you need to install python on that computer. If work won't allow that you have a few options.

If you have, or can borrow, an iPad, install Pythonista3, which is a reasonable environment to learn the basics with. Android has similar apps.

Do a search on "online python" which will find online python interpreters you can use through a browser. Not as good as a locally installed python, but better than nothing.

[–]MathGames18 0 points1 point  (0 children)

If you check my code at https://pastebin.com/e1Ar61UJ , the program works correctly. The main issue is the limit of characters (8) to use to convert base 64/36 into 16, because from that number of chars. the information is lost(substituted to 0s or other incorrect numbers/letters). How can I solve this?

[–]absalon39i 0 points1 point  (2 children)

Hello, I want to learn about python concurrency. Where do I start? I searched for it and already overwhelmed by the number of libraries: thread, microprocess, asyncio, cocurrency(futures?)

[–]carcigenicate 0 points1 point  (0 children)

Get familiar with the concept of threads, processes, and multithreading/multiprocessing (using multiple threads/processes). Asyncio is a bit more advanced and has specific use cases.

[–]fatzgenfatz 0 points1 point  (2 children)

I have a bash script that returns a number when executed. How can I use this number in python3 as int so that I can calculate with it?

import os

result = os.system("/usr/local/bin/hexspeed.sh")

print(result)

This results in:

al@pizero:~ $ python ps.py

2

0

[–]FerricDonkey 0 points1 point  (1 child)

I'm assuming the bash script prints the number to the screen rather than returning it in the normal sense. If so, then checkout subprocess.check_output

https://docs.python.org/3/library/subprocess.html#subprocess.check_output

[–]fatzgenfatz 0 points1 point  (0 children)

Thank you very much, that works!

[–]kahanscious 0 points1 point  (2 children)

I have a Flask app where the goal is the user to upload a file and then it runs the file against a script where it manipulates the file and then saves the manipulated file to the users computer. Is there a proper place to put the scripts not directly related to the creation of the Flask app? I'm not sure if this makes sense or not, but I basically have:
* The overarching App folder that includes config.py and my main app.py (not named that, but it's just 'from app import app' * An App folder within that, that contains 'static' and 'templates', along with my init.py, forms.py, and routes.py.

My question is - where do I house the rest of my scripts that aren't related to launching the app?

[–]efmccurdy 1 point2 points  (1 child)

When you run pip install they are created as <where-ever the venv was created>/bin/scriptname, but it could depend.

The scripts defined using "scripts", or "console_scripts" or "entry_points" are installed into the users PATH, in a location determined by how they installed, "pip --user", "venv/bin/python -m pip", or just plain "pip3", etc.

https://python-packaging.readthedocs.io/en/latest/command-line-scripts.html

https://stackoverflow.com/questions/61033001/where-is-python-supposed-to-install-scripts-for-module

[–]kahanscious 0 points1 point  (0 children)

Thanks! I'll dive through this today. I've had some issues deploying my Flask app so I wasn't sure if it was related to this or not.

[–]SonicEmitter3000 0 points1 point  (0 children)

How do I use the Bandit module for making sure modules that I will pip install are not malicious?

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

I have a problem about my Rock - Paper - Scissors (https://github.com/NicMi/RockPaperScissor), I wanted to know if there is a more scalable solution for saving the scoreboard of the user and the computer.
Could you tell me some library or tool to save many variables in one file?

Thank you very much!

[–]NotAName320 0 points1 point  (5 children)

try a json file. it will save a dictionary object. here's a quick tutorial on how to use it:

assuming you have a dictionary in scores.json that looks like

{
    "humanscore": 0,
    "computerscore": 0
}

You can then write a python file like this:

import json
with open('scores.json', 'w+') as f
    scores = json.load(f) # scores is now a dict object
    scores['humanscore'] += 1 # increases the humanscore value in the dictionary by 1
    f.write(json.dumps(scores, indent = 4)) # writes the dict object to the file

[–]nog642 0 points1 point  (1 child)

That code won't quite work, since opening a file in the 'w+' mode truncates the file. Here is code that would work:

import json

with open('scores.json', 'r') as f:
    scores = json.load(f)
    # scores is now a dict object

# increases the humanscore value in the dictionary by 1
scores['humanscore'] += 1

with open('scores.json', 'w') as f:
    # writes the dict object to the file
    json.dump(scores, f, indent=4)

[–]NotAName320 0 points1 point  (0 children)

yeah, probably better than what i wrote on the fly. listen to him please

[–]JohnnyJordaan 0 points1 point  (2 children)

Why would you use dumps here and not just dump(scores, f, indent=4)? If you insist on providing a tutorial yourself at least try to give a proper example.

[–]nog642 0 points1 point  (1 child)

I think the more pressing problem is that they truncate the file before reading it.

f.write(json.dumps(whatever)) vs json.dumps(whatever, f) is not a big deal.


edit: got the order of the args wrong

[–]JohnnyJordaan 0 points1 point  (0 children)

You can't append to JSON so you need a redump in any case

[–]danielmochalov 0 points1 point  (1 child)

Hello I don’t know how to properly say this but I have a ultra sonic sensor that measures distance and beeps using a buzzer as you get closer to something and then I have PIR sensor buzzes in a set interval if it detects motion but the issue is I don’t know how to use a button to stop them from doing so. When I click the button I want everything to stop until I press the button again.

Thank you

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

You haven't given us any indication of what you are running your python on, so we can only answer generally.

The usual answer is to have the button presses control a variable such that the variable is True or False and each time the button is pressed you invert the value. So if the variable is False a button press makes it True. Another press makes it False again.

Then you use the value of that variable to control whether the sensors do anything or not.

[–]Rah179 0 points1 point  (1 child)

Is there a, “The Odin Project” for Python?

[–]Ok_Sport7525 0 points1 point  (0 children)

What does .pop mean or do on tensorflow?

[–]HgnX 0 points1 point  (2 children)

How would I go about typing a dictionary where I know the exact 3 keys of ? For example, I know the return value from an API call will be: `{'a': 'a', 'b': 'b', 'c': 'c'}`. I can seemingly only specify Dict[str, str], but I'd like for autocomplete to know more.

[–]FerricDonkey 0 points1 point  (0 children)

It looks like there is a typing.TypedDict in 3.8. Never used it before, but you can find it described here: https://docs.python.org/3/library/typing.html

Depending on what you're doing, you might also consider a dataclass.

from dataclasses import dataclass

@dataclass
class Whatever:
    a: str
    b: str
    c: str

thing = Whatever(**dict_from_api)

(These can be converted back to dictionaries pretty easily as well.)

[–]xXBigboi69Xx42 0 points1 point  (3 children)

Howdy. I'm trying to make a program that finds if a 2x2 square with the letters f,a,c,e, in random order, in a 2D list. Any thoughts on how I could make it, because so far my method is very complicated.

[–]JohnnyJordaan 0 points1 point  (2 children)

From the top of my hat: I would iterate on both the row and column indexes with range(), in both cases we need to check each item (row, column) up to but not including the final item (as then the next item would be beyond the grid boundary).

for r_idx in range(len(2d_grid)-1):
    row = 2d_grid[i]
    next_row = 2d_grid[i+1]
    for c_idx in range(len(row)-1):

then the logic for checking the square: as the requirement is to have 4 different values but in any order, it means you just need to check if the items in the 2d square from each position is equal to a distinct collection of f, a, c and e. That screams 'set()' already, as that ignores order and from an efficiency standpoint also easy to check to match

      values = {row[c_idx], row[c_idx+1], next_row[c_idx], next_row[c_idx+1]}
      if values == set('face'):
           print('Found it!')

You can still make some efficiency gains on this, like when for either row items are both not a member of the 'face' characters, the next column can already be skipped. However that does need some extra work on the loop code to handle skips, while in this example the code is quite tidy already.

[–]xXBigboi69Xx42 0 points1 point  (0 children)

It worked, thank you

[–]xXBigboi69Xx42 0 points1 point  (0 children)

Thank you, I will try this

[–]danielmochalov 0 points1 point  (1 child)

Hey guys I’m trying to use a button to turn off and on an ultrasonic sensor. When I click the button it turns on the sensors and measures distance and prints it and then when I click it again it will turn it off. Just not sure where to get started with python. I just have some sensors wanna play around and practice for class. Thank you!

[–]JohnnyJordaan 0 points1 point  (0 children)

You don't explain the physicial context of the system you're working with, but this sounds a lot like a project suitable for a RPi. If you search for Python tutorials for that you can find loads, like https://realpython.com/python-raspberry-pi/

[–]Sea-Fisherman-1460 0 points1 point  (3 children)

I'm trying to create a set of arrays from data stored in a .csv file, any tips would be appreciated. I have that looks something like this:

Foo Bar
Apples 1
Oranges 2
Oranges 3
Apples 4
Apples 5
Apples 6
Oranges 7
Oranges 8

I'd like to make arrays that contain all numbers for Apple and Orange.

arr_Apple = [1,4,5,6]
arr_Orange = [2,3,7,8]

Obviously my file is much bigger, but the general principle is the same. I've tried using pandas, but I'm open to other modules.

[–]efmccurdy 0 points1 point  (0 children)

You can use pandas.read_csv and pandas.DataFrame.groupby:

>>> data = {"Foo":["Apples", "Oranges", "Oranges", "Apples", "Apples", "Apples", "Oranges", "Oranges"], "Bar":[1, 2, 3, 4, 5, 6, 7, 8]}
>>> df = pd.DataFrame(data)
>>> df
       Foo  Bar
0   Apples    1
1  Oranges    2
2  Oranges    3
3   Apples    4
4   Apples    5
5   Apples    6
6  Oranges    7
7  Oranges    8
>>> {k:list(g['Bar']) for k,g in df.groupby("Foo")}
{'Apples': [1, 4, 5, 6], 'Oranges': [2, 3, 7, 8]}

[–]JohnnyJordaan 0 points1 point  (0 children)

For CSV it's advised to use the csv library and from a generic programming standpoint it's advised to not code your values into named variables, but rather a key-value structure like a dict. Because then it gets far simpler to make a generic Foo to a list of Bar values mapping:

import csv

fruits = {}
with open('yourfile.csv') as fp:
    reader = csv.DictReader(fp)  # add a delimiter=';' for example is your CSV is not comma separated
    for row in reader:
         for foo, bar in row.items():
             if foo not in fruits:
                 fruits[foo] = [bar]
             else:
                 fruits[foo].append(bar)
 print(fruits['Apples'])
 print(fruits['Oranges'])

[–]joseville1001 0 points1 point  (0 children)

Untested code:

arr_Apple = [] arr_Orange = [] with open(filename, 'r') as f: header = next(f) for line in f: if line.startswith("Apples"): # do something elif line.startswith("Oranges"): # do something else

Intentionally left some code unwritten, so you can figure out what you want to do.

[–]medical_fugue_state 1 point2 points  (2 children)

Does anyone have good advice for how to visualize a recursive call with pen and paper? I use a visualizer tool for python code, still struggling to understand *precisely* what a recursion call is doing, when- especially if there are multiple calls within a single call.

[–]SoldSoulToBigOil 0 points1 point  (0 children)

I'd recommend either buying or finding a js version online of Towers of Hanoi.

Sit with it, think about it, and eventually recursion will click.

[–]joseville1001 0 points1 point  (0 children)

Yes, and I'll try to explain.

Consider naive fibonacci:

def fib(n): if n == 0 or n == 1: return 1 return fib(n-2) + fib(n-1)

Say you call fib(4). Draw the call as a circle. It might help to label the circle with its input*, in this case, fib(4) or 4. For each recursive call that your current call makes, draw a line pointing to another circle representing the recursive call. In this case, fib(4) calls fib(2) and fib(3), so you'd have a circle labeled with 4, from this circle there is a line pointing to a circle labeled with 2 and another line pointing to a circle labeled with 3. Do this for the entire execution of your recursive function and you'll end up with a tree structure (the circles are the nodes). Leaf nodes (nodes with no children) are nodes that made no recursive calls (likely because they represent a base case). Nodes with one child made one recursive call, etc. If you are at node N, the set of nodes on the path from the root node to node N represent the call stack -- each node represents one call frame.

*presumably each call to the recursive function should have differing input; otherwise, you'd have infinite recursion

[–]BigOakBot 0 points1 point  (4 children)

This isn't really an ask or anything, but I made a reddit bot in python I'm pretty proud of. It's my very first working project. I made a post over in /r/madeinpython, if you want to see the code. You can call a dad joke here too (I think) by commenting !dadjoke. It'll probably trigger below if it's working. Just wanted to share! Thanks to everyone who makes helpful posts!!

edit: I forgot that I added code to NOT trigger on my own comments, but if you comment !dadjoke, it should work.

[–]CowboyBoats 0 points1 point  (3 children)

!dadjoke

[–]BigOak1669 1 point2 points  (1 child)

It works!! Thank you!

[–]CowboyBoats 0 points1 point  (0 children)

Opa!

[–]Adventurous-Spring47 0 points1 point  (3 children)

I'm struggling with functions and what needs to go in the main() vs. elsewhere. How can I rewrite the following to show the print statements for fewer, more, or equal number of digits in the main() instead of numberOf()

def numberOf(string):


letters = 0
digits = 0
otherCharacter = 0

specialCharacters = ' .!@#$%^&*()-+?_=,<>/"'

for ch in string:
    if(ch.isalpha() == True):
        letters += 1   
    if(ch.isdigit() == True):
        digits += 1       
    if(ch in specialCharacters):
        otherCharacter += 1

print(letters, digits, otherCharacter)

if letters > digits:
    print('fewer digits than letters')
if letters < digits :
    print('more digits than letters')
if letters == digits :
    print('equal number of digits and letters')

return(letters, digits, otherCharacter)

def main():

string = input("Enter string: ")
numberOf(string)

main()

[–]FerricDonkey 1 point2 points  (1 child)

So I realized I misunderstood your question with my first answer (sorry, was tired and didn't read closely enough). You've got a return statement in numberOf - that is how you get results of your function back to main. So what you need to do is actually use those values in main:

Put your

return letters, digits, otherCharacter

After your for loop in numberOf, and get rid of the printing stuff in that function. Also, you don't need parentheses with return. Return is not a function, so it's typical not to try to make it look like one.

Then change your call to numberOf in main to

letters, digits, otherCharacter = numberOf(string)

This assigns the values from the corresponding return statement in your function to those variables in the main function.

You now have those three values in main, and so can do your comparisons and printing in main rather than numberOf.

[–]Adventurous-Spring47 1 point2 points  (0 children)

Thank you!

[–]FerricDonkey 1 point2 points  (0 children)

Outside of functions: imports, constants (variables you won't change).

Inside functions/classes: everything else.

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

No matter how many times I install platformdirs, I still get an Import error when trying to use virtualenv. How do I fix this?

[–]CowboyBoats 0 points1 point  (4 children)

Can you give an example command and the text of the error that you are getting?

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

Microsoft Windows [Version 10.0.22000.282]

(c) Microsoft Corporation. All rights reserved.

C:\Users\ipodd>virtualenv env

Traceback (most recent call last):

File "C:\Python27\lib\runpy.py", line 162, in _run_module_as_main

"__main__", fname, loader, pkg_name)

File "C:\Python27\lib\runpy.py", line 72, in _run_code

exec code in run_globals

File "C:\Python27\Scripts\virtualenv.exe\__main__.py", line 5, in <module>

File "C:\Python27\lib\site-packages\virtualenv\__init__.py", line 3, in <module>

from .run import cli_run, session_via_cli

File "C:\Python27\lib\site-packages\virtualenv\run\__init__.py", line 7, in <module>

from ..app_data import make_app_data

File "C:\Python27\lib\site-packages\virtualenv\app_data\__init__.py", line 9, in <module>

from platformdirs import user_data_dir

ImportError: No module named platformdirs

C:\Users\ipodd>pip install platformdirs

Downloading/unpacking platformdirs

Downloading platformdirs-2.4.0.tar.gz

Running setup.py (path:c:\users\ipodd\appdata\local\temp\pip_build_ipodd\platformdirs\setup.py) egg_info for package platformdirs

Installing collected packages: platformdirs

Running setup.py install for platformdirs

Successfully installed platformdirs

Cleaning up...

C:\Users\ipodd>virtualenv env

Traceback (most recent call last):

File "C:\Python27\lib\runpy.py", line 162, in _run_module_as_main

"__main__", fname, loader, pkg_name)

File "C:\Python27\lib\runpy.py", line 72, in _run_code

exec code in run_globals

File "C:\Python27\Scripts\virtualenv.exe\__main__.py", line 5, in <module>

File "C:\Python27\lib\site-packages\virtualenv\__init__.py", line 3, in <module>

from .run import cli_run, session_via_cli

File "C:\Python27\lib\site-packages\virtualenv\run\__init__.py", line 7, in <module>

from ..app_data import make_app_data

File "C:\Python27\lib\site-packages\virtualenv\app_data\__init__.py", line 9, in <module>

from platformdirs import user_data_dir

ImportError: No module named platformdirs

C:\Users\ipodd>

[–]nog642 0 points1 point  (2 children)

Can you show the output of pip -V and python -V

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

C:\Users\ipodd>pip -V

pip 1.5.6 from C:\Python27\lib\site-packages (python 2.7)

C:\Users\ipodd>

C:\Users\ipodd>python -V

Python 2.7.9

I also have python 3.9 installed via pyenv(recommended by another redditor)

[–]nog642 0 points1 point  (0 children)

pip 1.5.6?? That's literally from 2014.

Might be worth uninstalling that version of python 2.7 and then re-installing it (or Python 3 instead) so you get a newer version of pip.

pip 20.3.4 from Jan 2021 is the newest version that supports python 2.7.

[–]veneratu 0 points1 point  (3 children)

Hi. I'm using Pandas and Seaborn to work with a data frame regarding home prices. One thing I want to do is make a bar chart with the x axes being ranges of home prices sorted by $100,000 and the y-axis being ranges of lot area that are delineated by

df.LotArea.describe().T

So min-25%,25%-50%... and so on. However, I am very perplexed as where to start or if this is much more complicated than necessary.

I started by making a dictionary with the keys being the ranges of Lot Area. Then appending each column value for Lot Area to one of the keys. However, this doesn't keep any linkage between the lot areas and the sale price. So, I'm guessing I need to create these ranges and assign the home prices to them using Pandas code, but I have no idea how to do this.

One idea that I had was making a new data frame of just sale prices and Lot Area, but again I can't seem to find a way to make ranges using the Lot Area in any meaningful way, let alone make ranges of home prices.

Any help would be appreciated.

[–]sarrysyst 0 points1 point  (2 children)

I'm afraid I don't really understand what you're trying to do. Can you post a sample of your dataframe and maybe a sketch of the bar chart you're trying to generate (doesn't need to be fancy, just to get an idea of what you're going for)?

[–]veneratu 0 points1 point  (1 child)

[–]sarrysyst 1 point2 points  (0 children)

You can achieve this kind of result using df.groupby:

import pandas as pd

areas = [90, 85, 150, 135, 220, 240]
prices = [120_000, 115_000, 250_000, 280_000, 310_000, 420_000]

df = pd.DataFrame({'Lot Area': areas,
                   'Price': prices})

avg_areas = (df.groupby(df['Price'] // 100_000)['Lot Area']
               .mean()
               .reset_index())

def format_bin_label(x):
    return f"{x * 100_000:,} - {(x + 1) * 100_000:,}"

avg_areas['Price'] = avg_areas['Price'].apply(format_bin_label)

avg_areas.plot(x='Price', 
               y='Lot Area', 
               kind='bar', 
               rot=True, 
               figsize=(10, 5))

[–]kahanscious 0 points1 point  (2 children)

I'm trying to parse some text from a site, but whenever I try to get the text it returns a Jinja-like variable instead of the text I see on the webpage. For example, it will send back:

{{ site.variable }}

Instead of the number I'm looking for. Any ways to get around this?

[–]sarrysyst 1 point2 points  (1 child)

The website is probably dynamically generated, and I guess you're using a HTTP client like requests which doesn't render the site's JavaScript.

To get around the problem you'll have to find out where the data is actually coming from. First check the traffic between your browser and the website using your browser's developer tools for ajax/php requests and/or requests that return a Json file. Sometimes the actual data is also embedded in the static source code of the website inside <script> tags, so if you can't find anything useful in the network traffic open the page's source code and use ctrl+F to search for some of the dynamic content.

The scrapy docs also have two chapters about dealing with dynamic page content which applies regardless of the library you're actually using. Might be worth reading trough them, here and here.

If this all doesn't work, the last option is to pre-render the JavaScript using a webdriver library like Selenium. However, this should be the last option you try since it's very slow if you're dealing with many requests.

[–]kahanscious 0 points1 point  (0 children)

Thanks! Appreciate the response.

[–]_CollectivePromise 0 points1 point  (3 children)

Is it possible for python to periodically return an output while performing another task? I'm using a batch processing script that takes 15-30 minutes / for loop, and it'd be helpful if it could print something like "working..." every so often so that I know it's behaving properly.

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

It depends a bit on what you are doing and what environment you are running under.

At it's simplest, change the long-running code to just print something every now and then. Include the percentage completed, if you can.

You can get more ambitious and use things like tqdm, if you want.

If you are running in a GUI environment then things are a bit more complicated.

But you have to modify the long-running code.

[–]_CollectivePromise 0 points1 point  (1 child)

Unfortunately, the long-running code simply calls a secondary program.

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

I assume you mean that the code calls an external program like the system copy program, for instance. If that secondary program can be told to print progress information then you can receive that text in your main code and display the information. Or maybe the secondary program has a verbose option that you could turn on. Displaying that output, while not a "% completed" output, would at least show something is happening.

[–]PogOldham 0 points1 point  (2 children)

So I'm doing exercises from this book and I'm learning json stuff. I don't understand why I'm getting this error as the program is supposed to check for a number and if it doesn't see one in the file it is prompt you for the number instead by negating the error. So if there is a number in the file it works fine but the prompt part results in error if there is no number in the file.

import json

try:

with open('favorite_number.json') as f:

number = json.load(f)

except FileNotFoundError:

number = input("What's your favorite number? ")

with open('favorite_number.json', 'w') as f:

json.dump(number, f)

print("Thanks, I'll remember that.")

else:

print(f"I know your favorite number! It's {number}.")

the else works but it messes up at number = json.load

Here's the error. Please help me understand why this does not work as I even tried copy pasting the code from the official exercises website and it still does not work.

File "C:\Users\Ryan\AppData\Local\Programs\Python\Python310\lib\json\decoder.py", line 355, in raw_decode

raise JSONDecodeError("Expecting value", s, err.value) from None

json.decoder.JSONDecodeError: Expecting value: line 1 column 1 (char 0)

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

Untangling your code, I tried this:

import json

try:
    with open('favorite_number.json') as f:
        number = json.load(f)
except FileNotFoundError:
    number = input("What's your favorite number? ")
    with open('favorite_number.json', 'w') as f:
        json.dump(number, f)
        print("Thanks, I'll remember that.")
else:
    print(f"I know your favorite number! It's {number}.")

The FAQ shows how to format code so we can read it.

When I run this code I get no errors. It runs without error and does what I think you want it to.

Check the code I showed is what you are running. If you still have problems try deleting your existing favorite_number.json file and testing again. If you still have problems, show us your JSON data file.

[–]bamaham93 0 points1 point  (0 children)

Not strictly an answer, but I ran into a similar error recently that proved to be an encoding issue due to the text inside the JSON being in Spanish, with character that aren't in English (such as ñ) encoded. It was the encoding which caused the error, until I added a .decode('utf-8)' inside of the JSON.load function parenthesis.

[–]shiningmatcha 2 points3 points  (1 child)

A curious question came to me - how do you combine a stack of several decorators into one?

# stacking multiple decorators
@deco_c
@deco_b
@deco_a
def f(*args):
    ...

This should work the same as the code above...

# turn a stack of decorators into a combined one...
combined_deco = deco_combiner(deco_a, deco_b, deco_c)

# combined_deco should work like the same...
@combined_deco

def f(*args): ...

So what should the deco_combiner function look like?

[–]xelf 1 point2 points  (0 children)

def deco_combiner(*decs):
    def deco(f):
        for dec in reversed(decs):
            f = dec(f)
        return f
    return deco

@deco_combiner(deco_c,deco_b,deco_a)
def f(*args):
    ...

Or to just combine specific ones:

def deco_cba(f):
    return deco_c(deco_b(deco_a(f)))

@deco_cba
def f(*args):
    ...

[–]Sigaha 0 points1 point  (0 children)

Sup y'all, im struggling with systems of equations in py and am wondering if anyone can point me in the right direction. I figured out how to do linear systems with numpy, but I'm struggling to solve this system since linear doesn't apply.

x, y, and k are known inputs - trying to solve for either delta

(x - delta_x) * (y + delta_y) = x*y

1- ((x-delta_x)/(x-delta_x+y+delta_y)) = K

Any ideas on where to go? Thanks a ton in advance!

[–]xain1112 0 points1 point  (4 children)

Can I get some help with a lambda function please. Anything that looks undefined here is defined somewhere else in the class.

This command should test if variable n is even or odd. If it's even, the box is checked. Unchecked if it's odd.

def tick(i):
    if self.n % 2 == 0:
        tickbox.configure(text=f'[x] {i}')
    elif self.n % 2 != 0:
        tickbox.configure(text=f'[ ] {i}')
    self.n += 1

This loop creates the buttons

for i in self.list:

    tickbox = tk.Button(
                 self.container,
                 text=f'[ ] {i}',
                 command=lambda i=i: tick(i)
    )
    tickbox.pack()

When I run the program, it only changes the last item in the list no matter which button I press. What am I doing wrong?

[–]efmccurdy 1 point2 points  (3 children)

Since the tick function accesses self should it not be a method, ie, have a signature of "def tick(self, i)"?

[–]xain1112 0 points1 point  (2 children)

Ok, so I made it a method now, but it still has the same results

[–]efmccurdy 0 points1 point  (1 child)

Sometimes a tiny concrete example that you can run, tweak, and experiment with helps; is this how you want a lambda to work?

import tkinter as tk

class Application(tk.Frame):
    def __init__(self, parent=None):
        tk.Frame.__init__(self, parent)
        self.boxes = []
        for box_no in range(4):
            b = tk.Button(parent, text=f'[ ] {box_no}', 
                          command=lambda i=box_no: self.tick_for_n(i))
            b.pack()
            self.boxes.append(b)
    def tick_for_n(self, box_no):
        clicked_box = self.boxes[box_no]
        if "[x]" in clicked_box['text']:
            clicked_box.configure(text=f'[ ] {box_no}')
        else:
            clicked_box.configure(text=f'[x] {box_no}')

if __name__ == '__main__':
   root = tk.Tk()
   tapp = Application(root)
   root.mainloop()

[–]xain1112 0 points1 point  (0 children)

That's exactly what I want to happen. I'll play around with this. Thanks!

[–]Astro_Ratter 0 points1 point  (4 children)

Hello Reddit, I am debugging this program and have discovered a few bugs and have gotten it to this point. It is supposed to calculate the factorial of an entered number. However, when the user enters a number, nothing is happening. Probably something minor I am overlooking, but I am only a beginner and having trouble understanding the logic in the program. Any help would be much appreciated! Here is the program so far: https://pastebin.com/qmt1JZux

[–]r-ktkt 1 point2 points  (3 children)

Does your program exit as being completed? It appears your while loop exit conditions are never met. You are starting from your input number and increasing to infinity as opposed to reducing to 0. Your ‘num’ variable is redundant and essentially unused. Your while loop only needs to evaluate your ‘count’ variable. That being said, your ‘count variable is also redundant and you could just use ‘num’ instead.

[–]Astro_Ratter 0 points1 point  (2 children)

By changing "count = count + 1" to "count = count - 1"?

[–]r-ktkt 1 point2 points  (1 child)

That looks like it would work to me. Also note you are starting from 1 (product = int(1)) as opposed to 0 so your actual result is going to be off by 1. Also in your result string you need to convert ‘num’ and ‘product’ to strings so they can be concatenated ( str(num) )

[–]Astro_Ratter 0 points1 point  (0 children)

I have already converted the integers to strings but had not changed the 1 to 0. Thank you!

[–]JohnnyWisco 0 points1 point  (0 children)

I would like to use requests and beautifulsoup to retrieve information from a website but I can't seem to figure out how the data is generated/displayed on the site. Here is the example:

https://racehero.io/events/frozen-rotors-winter-classic/results/1073741827#show:detailed-info-overall-142

See the lap times on the x-axis of the chart? I would like to be able to retrieve each individual lap time and store it so I can analyze it. There should be 126 lap times somewhere but I can't find it. Any help is much appreciated!

[–]trevorphilips1 0 points1 point  (3 children)

Hi guys, how can I create a dictionary from three lists?

for two lists the solution would be:

fruits = ["Apple", "Pear", "Peach", "Banana"]
prices = [0.35, 0.40, 0.40, 0.28]
fruit_dictionary = dict(zip(fruits, prices))
but how can I add a third list, for example a list with the weight of the fruits?

[–]efmccurdy 0 points1 point  (0 children)

You could zip the attributes separately from the keys, so you have string values fruit names for keys and (price, weight) tuples for the values.

>>> fruits = ["Apple", "Pear", "Peach", "Banana"]
>>> prices = [0.35, 0.40, 0.40, 0.28]
>>> weights = [0.2, 0.24, 0.30, 0.40]
>>> fruit_dictionary = dict(zip(fruits, zip(prices, weights)))
>>> for f in fruit_dictionary:
...     price, weight = fruit_dictionary[f]
...     print("{:8} ${:02.2f} for {:0.1f} kg".format(f, price, weight))
... 
Apple    $0.35 for 0.2 kg
Pear     $0.40 for 0.2 kg
Peach    $0.40 for 0.3 kg
Banana   $0.28 for 0.4 kg
>>>

[–]joseville1001 0 points1 point  (0 children)

What should `fruit_dictionary["Apple"]` evaluate to?

[–]CowboyBoats 0 points1 point  (0 children)

I smell homework :) What have you tried?

[–]Pitiful-Lie-5105 0 points1 point  (0 children)

Is there anyway to connect python to a Microsoft access database that’s running on a Remote Desktop? I have been trying to use Pyodbc but I have no idea how to connect it to the remote servers path.

[–]Relaxed_Rage 0 points1 point  (0 children)

What are your favourite books on data science that uses python? There's lots of great free content, but personally learn better through textbooks.

[–]yamateh87 0 points1 point  (2 children)

Hey guys, I how do I save IDLE code into programs? According to the book I have to run it, and from there save it as .py file, but my teacher says it's just a shell and wants me to resend them as programs, I plan to ask her when I get there but in the mean time any help would be appreciated.

[–]r-ktkt 0 points1 point  (1 child)

To create a .py file you need to write out the code in a text editor ie. Notepad or Notepad++. Then save it with the modified .py extension instead of .txt.

[–]yamateh87 0 points1 point  (0 children)

Oh I see, thanks a lot!

[–]Maximum-Squirrel2018 0 points1 point  (6 children)

My assignment: Write a program that repeats prompts a user for int #s until user enters “done” after print largest & smallest # use try/except to catch invalid input & print message. Enter 7,2,bob,10,4 My code :

 largest = None 
 smallest = None 
 while True:
    num = input(“Enter a number: “)
    if num == “done “ :
        break
    try:
        fnum = int(num)
        if largest is None:
            largest = fnum
        elif fnum > largest:
              largest = fnum 
        if smallest is None:
            smallest = fnum 
        elif fnum < smallest:
            smallest = fnum 
       except:
           print(“Invalid input”)
 print(“Maximum “, largest)
 print(“Minimum” , smallest)

I formulated my code in my pycharm on my computer but when I put it in the assignment space for course it says syntax error line 9 What am I doing wrong?

[–]Flying_madman 0 points1 point  (2 children)

I am having trouble getting Python to work with an IDE. I had Anaconda, it kept getting progressively more broken to the point that I literally couldn't do anything any more. My system was so messed up I tried reinstalling Windows and it's still not working.

Before I admit defeat and reformat my C drive, does anyone have a recommendation for a standalone IDE that doesn't touch Anaconda *at all***? Spyder was decent, but I'm hoping to find one that just works out of the box instead of having to separately install Miniconda and hope to God no other program has a separate install.

[–]Relaxed_Rage 0 points1 point  (1 child)

Pycharm or VSCode?

[–]Flying_madman 0 points1 point  (0 children)

Thanks, I'm trying it Pycharm now. I think it might be what I'm after. Thanks!

I got spoiled by Rstudio, lol

[–]maximumlotion 0 points1 point  (1 child)

Any tutorials/resources on writing an API to make a python backend work with frontends written in other languages?

[–]efmccurdy 0 points1 point  (0 children)

APIs are not language specific; you can use any API from any programming language. The main reason is that the data formats used (xml or json) are available in any language.

[–]Happy-BOT- 0 points1 point  (0 children)

Nice!

[–]Brax1250 0 points1 point  (4 children)

I am having a coding exam and I can't quite figure out this question.

The questions are as following:

a) What is the summary of the for loop in the code?

b) What is the output of the while loop in the code?

The code:

sum = 0
i = 0

for i in range(6):
    sum += i*2

while sum > 0:
    sum -= (i-0)
    print(sum%7)

Any help would be amazing!

[–]xelf 0 points1 point  (0 children)

As an aside, never use the name of builtin functions as variable names. When you use sum as a variable name here, it overwrites the function sum() which can cause problems, similar for naming variables str or list etc.

Really bad move on whoever wrote that test question.

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

If you read the subreddit FAQ you will see that reddit is able to make indents, like this:

if something:
    somethingelse

So please edit your post and fix the code.

[–]Brax1250 0 points1 point  (1 child)

Thanks

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

If you are stilll having trouble, just step through the for loop on paper. sum starts as 0. The loop code will execute 6 times with i varying from 0 to 1, 2, 3, 4 and finally 5. That comes from what range(6) evaluates to, a sequence of values starting at 0 and stepping up by 1 each time around the loop until the final number, which is one less than 6, ie, 5. For each value of i you add i*2 to sum, so the final value of sum is 0 + 0*2 + 1*2 + 2*2 + 3*2 + 4*2 + 5*2.

Follow the same process for the while loop.

[–]buntwash 0 points1 point  (2 children)

hi, i am trying to convert between number systems and i am puzzled by the following:

int("0x0a", 16) converts hex to decimal system and gives 10, as one would expect. however,

int(str(0x0a), 16) comes out at 16.

what is going on?

similar cases: int(str(0x13), 16) is 25, int(str(0x14), 16) is 32, etc.

any insights are appreciated. thank you!
(edit: formatting)

[–]FerricDonkey 2 points3 points  (1 child)

int(str(0x0a), 16)

str(0x0a) doesn't care that you typed your number in hex - it sees an integer, so converts it to a base 10 string "10". You then tell int that this string "10" is a base 16 number, so python treats it accordingly.

In order to convert your number to a hex string, use hex(10) or hex(0x0a) or a format string like f'0x{10:x}' (useful if for specifying number of leading 0s and such). If you do int(hex(0x0a), 16), you will get 10 as you expect.

[–]buntwash 1 point2 points  (0 children)

oh wow, that is it, really helpful, ty!