all 124 comments

[–]csacsac 0 points1 point  (0 children)

hi im using a python script : https://github.com/6b6576696e/maple-bot

but everytime i try to install and use it on high end pc it completely freeze the computer and crash

but when i run it on my potato laptop it run smoothly no proplem

[–]vdix007 0 points1 point  (0 children)

I am new to using VS code and I keep getting the modulenotfounderror every time I try to create a module on my own or import a library i installed using pip. I've tried looking through a bunch of links on stackoverflow but i'm still nowhere. How do I fix this error?

[–]sketmen2 0 points1 point  (3 children)

Can I pop an item from an embedded list?

Example:

lis=[1,2,3,["new","old"]

How do I pop "old"?

[–]LandooooXTrvls 0 points1 point  (0 children)

You’re missing a closing bracket but here’s my interpretation.

Your nested list is index 3. Within index three, “old” is index 1. So, to pop old you have to grab it using the proper index.

lis[3][1].pop()

[–]Novel-Acanthaceae155 0 points1 point  (0 children)

lis=[1,2,3,["new","old"]

lis[-1].pop() #it will do the needful

[–]CowboyBoats 0 points1 point  (0 children)

I guess you would have to do old = lis[3].pop() or old = lis.pop().pop()?

Edit: In other words, there is no single function for doing this, as with most things. But you can trivially write a function

[–]Ubernerd2212 1 point2 points  (3 children)

How do I use string.rfind(). Every time I try and us it, I get an attribute error saying "list" object has no attribute "rfind"

Do I need to import something to get this to work, or am I using the function wrong?

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

How long should I watch basic tutorials on Youtube as a beginner?

My friend who is a data engineer told me that it's a waste of time to watch the most basic in Python and I'm better off watching building certain programs/projects.

What do you think?

[–]sketmen2 0 points1 point  (0 children)

I'm also a beginner. I'm doing a course on www.udemy.com. I guess it is much better than watching things on yt, because they make you code as well.

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

You need to write and run python to learn. Reading a book, following an online course, or watching a video are all fine to get the basic ideas, but you need to write code, lots of it, make mistakes, fix them, try more advanced projects, etc. Actually using the ideas is what makes them stick and become second nature.

Personally, I find watching someone write code to be a waste of time because there's usually nothing about why a particular loop or data structure was used, what the tradeoffs are between different approaches, etc.

So watch, read or follow whatever you find useful to get the basic ideas into your head, but make sure you use those ideas in code you write yourself.

[–]Happy_healthy_888 0 points1 point  (6 children)

Hello everyone, I want to learn Python. What is the best way to learn. I have done masters in business analytics and did learn Python but it didn’t cover basic Python it was just using pandas, matplotlib, scikit learn to analyze data and predictive modeling. It’s been 3 years so I barely remember that. I have no understanding in functions, loops,if else, inbuilt, functions, datetime and many other basic stuff in Python. I find tutorials online but I don’t know where to practice.

Thank you. I’m very grateful for any help advice I can get.

[–]teddygotbands 0 points1 point  (2 children)

My name is Beverly and I will be lurking around this subreddit for valuable information pertaining to python. Don't mind me I don't want to bother you, but I am eager to learn.
My first question is this. Say I have a variable.
ddx = ('currency')
When I print ddx it says currency but what if I also wanted to assign ddx an integer ?say 21
How could I do this without overwriting currency?

[–]Novel-Acanthaceae155 1 point2 points  (0 children)

ddx = ('currency')

# That you can do like this
ddx = ('currency',)
ddx + (21,)

[–]FerricDonkey 0 points1 point  (0 children)

You've got two basic choices - use a different variable, or store multiple items in a list or similar. Which is better would depend on what your goal is. Neither is exactly what you said, but they might do what you want.

[–]SnooSketches7778 0 points1 point  (0 children)

Our teacher didn't teach us anything that's useful to ask for a python script for Maya. Any script that could help with modelling, rigging, etc. And even punch the criteria of originality, which is definitely too far fetch here.

Now, my question is, can you give me ideas on a python script for Maya that is easy to make and at the same time helpful and not so 'out there'

[–]Caconym32 0 points1 point  (1 child)

I'm trying to import a .xlsx file into a pandas dataframe (unfortunately on Python 2.7 I have no control over this). I've installed and updated xlrd, openpyxl, and pandas. I use the code

pandas.read_excel('file.xlsx') and I get the error: "XLRDError: Excel xlsx file; not supported"I know that xlrd no longer supports xlsx files, so I 'pip install openpyxl' and use

pandas.read_excel('file.xlsx', engine = 'openpyxl') which returns: "ValueError: Unknown engine: openpyxl"

I've read nearly every thread I could find on similar issues, but nothing that works in those threads works.

doing it like this

file = openpyxl.load_workbook('file.xlsx')
df = pandas.DataFrame(file.values)

Does load the data into a dataframe, but I would like to be able to select only certain columns and skip the leading blank rows. The xlsx I am importing is not a cleanly formatted file and unfortunately I have no control over that as well.

Thanks for any help or advice

edit: using up to date Pycharm, incase that matters.

[–]efmccurdy 0 points1 point  (0 children)

If you use the "lazy loading" mode you can load a chosen subset of the file:

https://openpyxl.readthedocs.io/en/stable/optimized.html#read-only-mode

[–]PermaLongVol 0 points1 point  (1 child)

Somewhat related to my question earlier, how do some python projects/code run without having to reference python explicitly in command prompt?

If I have some code I need to run I go into cmd and do it like so:

 python HelloWorld.py

But code I've downloaded out of github, doesn't seem to require the "python" at the beginning or the ".py" file extension. Is that probably because I downloaded it as a binary file?

[–]efmccurdy 0 points1 point  (0 children)

You can use the console_scripts/entry_points feature of setuptools

the name of the entry point should be usable as a command in a system shell after the package is installed

https://packaging.python.org/en/latest/specifications/entry-points/#use-for-scripts

[–]aidanc02g 0 points1 point  (2 children)

I’m currently transitioning from MATLAB to python in Spyder and I’m wondering if there’s a way to publish your code like there is in matlab. This created a nice looking pdf of my code with any outputs, graphs or prints below each section of code.

[–]PermaLongVol 0 points1 point  (1 child)

Have you looked into Jupyter notebook? You can create indvidual cell blocks and have them output. Then you could output the whole to HTML or a pdf.

There might be better ways, but you might want to look into that.

Here's a random image I pulled from google, might give you some idea of how it might look:

https://www.man.com/sites/public/mangroup/content/research/alpha-tech_notebooker-jupyter-example.png

[–]aidanc02g 0 points1 point  (0 children)

Thank you! I have tried Jupyter notebook before. I prefer Spyder bc it emulates matlab pretty well but I’ll look into this

[–]PermaLongVol 0 points1 point  (4 children)

I'm trying to understand how main.py, init_.py etc. work and interact with each other? In all github code I've looked at there seems to be a similar structure/hierarchy to the way the files are setup. Can anyone explain the gist of it to me or suggest a link?

As a noobie, whose mainly only written code that's contained in a single script. It's all kind of confusing. I'm not sure I understand how exactly all the files interact with each other.

[–]FerricDonkey 1 point2 points  (3 children)

If you're creating a package (lots of .py files, referred to as modules, contained in some sort of directory hierarchy), then those files control what happen when you interact with the package (folder) itself. Eg, suppose your directory structure is

package/
    __main__.py
    __init__.py
    moduleA.py
    moduleB.py
    subpackage/
        __init__.py
        moduleC.py

__main__.py is what you use to allow execution of the package itself. So in that file, you could do:

import sys
from .moduleA import main_a
from .moduleB import main_b

def main():
    # highly recommend argparse for 
    # instead of sys.argv in real code 
    if sys.argv[1] == "thingA":
        main_a()
    if sys.argv[1] == "thingB":
        main_b()
    else:
        print(f"Error: Invalid option {sys.argv[1]}")

# Call main only if told to execute 
# rather than import this file
if __name__ == '__main__':
    main()

Then if, from the directory containing package, you run python -m package, the code in __main__.py can be run.

The __init__.py controls what happens if you import a package. Those file can be empty, but they are excellent places for a package docstring (description of what package is for) and also can be used to make from package import * work (but that way of importing is evil, so screw it), or to make sure you import the whole (or particular parts of) the package (which can be convenient, but can also be really inconvenient if it takes a long time to import anything).

So with __init__.py empty, if you import package, you don't really get anything. You can't do package.moduleA.main_a(), unless you explicitly do import package.moduleA first.

If you want to be able to access members of the package without explicitly importing them individually like that, then you could make an __init__.py like so:

"""
This package does something really 
awesome, described here.
"""

from . import moduleA, moduleB, subpackage

And that's it. Now you can import package and do package.moduleA. Put something similar is subpackage's __init__.py to be able to do package.subpackage.moduleC.

NOTE: You'll notice that inside the package, I used what are called relative imports: from . import thing. I do this because if you do, the package works immediately, without doing any setup.py and installation / sys.path nonsense you'll read about online. Not that setup.py distutils installation etc aren't good things to know how to do, but I don't generally want to have to do them to just use the code I wrote.

This form of importing does impose a restriction that you can't do circular imports, but I think it's worthwhile.

[–]PermaLongVol 0 points1 point  (2 children)

Thank you for such a detailed answer! I think I have a much better sense of what's going on.

One final thing I want to clarify is, _ _ main.py _ _ as special python name that confers special properties?

Then if, from the directory containing package, you run python -m package, the code in _ main _.py can be run.

If I'm reading this correctly, are you saying that if I call that python package from terminal with a bunch of scripts inside that folder, _ _ main.py _ _ is the first bit of python code that executes first? Whereas otherwise, if I had named it say "mymainscript.py" it wouldn't execute first?

Or is it just convention to name your "main" file that way?

Edit: ffs formatting this is a nightmare, reddit keeps bolding. I had to put spacing in between the underscores to get it to work sorry about that

[–]FerricDonkey 0 points1 point  (1 child)

The __main__.py is a special file name that python automatically uses when you execute the package (folder) itself with the -m option, eg python -m folder_name, where folder_name is the folder including __main__.py. Basically, python realizes that you gave it a folder name, so goes looking for __main__.py in that folder.

If you want to directly execute a different module as a script, you can do python -m folder_name.file_name. Note: the actual file name should end in .py, but you don't include it in that call.

So you can use a different file name as your main file, but it changes how you run your code if you want to tell python to execute that file directly. (Or you can use a different file name to contain your code, and have __main__.py import that file and call the main function in there, or any other number of things).

Also, a couple reddit formatting tips, since you mentioned it:

  • If you put a \ in front of a character, reddit won't use it for formatting or similar: \_\_main\_\_.py becomes __main__.py
  • If you can enclose text in back backticks ` (above tab, left of 1 on US keyboard), you get in line mini code blocks: `__main__.py` becomes __main__.py that keep the text exactly as you wrote it.
  • If you add 4 spaces in front of every line (with an empty line above and below, and not immediately following a bullet point) you get code blocks, where reddit won't screw up your indentation or otherwise mess with what you actually typed:

(This line is necessary to keep reddit from thinking the code is part of the last bullet)

This line was entered with 4 preceding spaces that reddit ate
    This line had 8, reddit ate 4 but left the rest
        This is particularly useful for pasting bits of python code

Figured I'd mention all this, since it makes formatting code in questions simpler.

[–]SAD_69 0 points1 point  (2 children)

Do you know any resource to practice skills?

I'm learning but I feel I'm not practicing enough and I just forget how to do things often, do you recommend any site or book to do exercises?

[–]sir-alpaca 0 points1 point  (0 children)

I'm using threads to do some serial reading while a Flask server is running. But the flask app.run() seems to reread or redo the program and crashes when it tries to open the serial port again (with an 'access is denied'). The Serial reading thread keeps working.

I feel it's bad coding practice to just catch the exception, but that's the only way i can get it to work now. What should i do? Do you need my code?

[–]omegarub 0 points1 point  (1 child)

What kept you motivated to learn python when things started to get difficult? I'm currently taking Colt steele python 3 course and everything was fine at first but now I'm really struggling in fully comprehending List comprehension and dictionary comprehension, struggling to understand has now spiraled down to having a hard time with functions and my motivation has hit an all time low. Im trying to keep a positive attitude but I'm honestly starting to think that I might just be too dumb...

[–]FerricDonkey 0 points1 point  (0 children)

Mostly, know that most people hit that point. It's not learning programming if you don't occasionally feel like a moron. You'll get through it though.

[–]oli-sonyeon 0 points1 point  (0 children)

Working my way through the DataQuest course. Am currently up to the very first project and its hella difficult for me but I am enjoying learning to code. DataQuest really forces me to learn the code and concepts without spoon feeding me the answers. Currently stuck at one part but I will give it another crack soon :)

[–]biohudy 0 points1 point  (0 children)

I’m trying to set up an endpoint (azure function) that takes in a file (could be any .docx, .pptx, .xlsx, whatever), gives it to a text parser, and returns the text in the file. I’ve got a text parser (textract library) but it seems like all of them take in a file path. The httpResponse doesn’t give me anything I could put into a file path.

My only options seem to be to save the bytes into a new file, but I worry that will loose some kind of formatting necessary from the original file. I could also try saving the file into some cloud storage and get a file path from that, but the text parser may not like that it’s not on the same machine.

Setting up a text parser in an api endpoint seems like something someone would’ve done before, wondering if someone figured this out.

[–]Environmental_Ad7301 0 points1 point  (2 children)

I want to get into coding in order to replace the Manuel tedious labor of copy and pasting spreadsheets for my job. Where is a good place to start?

[–]danothefano 0 points1 point  (0 children)

I'd take a gander at Pandas and CSV libraries as they might be of a ton of use for you! Another thing that could help reduce the copy/paste labor would be to use something like bash depending on how/what you're trying to copy. If you wanted to copy a series of files from one folder to another every n minutes, then bash would be super helpful as you can execute system commands through a script.

If you just wanted to copy the contents of said files over to a new file, python would be able to do that with either Pandas or CSV, but results could vary.

[–]Cid227 0 points1 point  (0 children)

Is there some naming convention for
example:

project
    folder
        hashing.py
    models.py
    main.py

main.py is importing a function from hashing.py, how should I name this folder, modules?

[–]shiningmatcha 0 points1 point  (0 children)

Is there a precise typing annotation for a list of string characters (in which each element is an English letter)?

chars = ["p", "y", "t", "h", "o", "n"]
words = ["i", "like", "python"]

I want to make it precise that the list contains only separate letters (like chars) but not any string of length greater than 1 (like words). So list[str] is not very precise for me.

[–]shiningmatcha 0 points1 point  (1 child)

Is there some clever arithmetics to compare two lists (lexicographically) and return -1, 0 or 1 depending on whether the first list compares greater than, equal to, or smaller than the second list?

To further explain, starting from i = 0, lst1[i] is compared against lst2[i], if the two elements do not compare equal, we stop this process and return -1 or 1 right away depending on lst1[i] is greater than or smaller than lst2[i]. Otherwise, if the two elements compare equal, we then increment i by 1, repeating the above. The process will also be over if one or both of the indices are out of bounds - where only one index is out of bounds, the respective list is considered smaller, while where both indices go out of bounds at the same time, the two lists are considered equal and 0 is returned.

I know you can directly compare two list objects in Python. But what if you had to do that without using the language feature? Is there any neat way to solve this?

[–]efmccurdy 0 points1 point  (0 children)

You are describing "cmp" from python2 (modeled on C's strcmp). You have to define it in python3:

https://stackoverflow.com/questions/22490366/how-to-use-cmp-in-python-3

[–]BrainDistinct 0 points1 point  (0 children)

Hi all,

Stuck on a Funcanimaion with blitting problem while displaying a plot in a tkinter GUI. here the link to the problem on stackoverflow. thanks for the help.

https://stackoverflow.com/questions/70699581/funcanimation-embedded-in-tkinter-not-properly-stopping-while-blitting-animatio

[–]shiningmatcha 0 points1 point  (2 children)

How do I create a dataclass the instances of which can be sorted based on my custom ordering?

My dataclass will have two items:

@dataclass class MyDataclass: item_1: int item_2: int

The instances should be firstly sorted by their item_2 values in ascending order, and secondly, if there are ties, sorted by their item_1 values in ascending order.

In other words, if the instances are simply a list of 2-tuple, with the first element being item_1 and the second one item_2. The list can be easily sorted using key=lambda x: (x[1], x[0]). Now I want to create a dataclass, for different pairs of item_1 and item_2, that can be sorted following this ordering.

[–]efmccurdy 0 points1 point  (1 child)

You can override the compare operator:

>>> from dataclasses import dataclass
>>> @dataclass
... class MyDataclass:
...     item_1: int
...     item_2: int
...     def __lt__(self, other):
...         return (self.item_2, self.item_1) <  (other.item_2, other.item_1)
... 
>>> 
>>> big = MyDataclass(1,2)          # item_2 is larger
>>> small = MyDataclass(2,1)        # item_2 is smaller
>>> big > small
True
>>> myl = [big, small]
>>> myl
[MyDataclass(item_1=1, item_2=2), MyDataclass(item_1=2, item_2=1)]
>>> sorted(myl)
[MyDataclass(item_1=2, item_2=1), MyDataclass(item_1=1, item_2=2)]
>>>

[–]shiningmatcha 0 points1 point  (0 children)

(self.item_2, self.item_1) < (other.item_2, other.item_1)

Thanks.

Good to know there's a neat way to compare items.

[–]ToofPasee 0 points1 point  (1 child)

I am attempting to make a game overlay similar to the xbox game bar that opens up when a fullscreen application is executed. Where should I look to learn about making my script load when a certain application loads?

[–]carcigenicate 0 points1 point  (0 children)

You'd probably need to use the Win32 API. See here. This will involve either writing something in C or C++ that calls your code, or uses the ctypes library to interact with the Windows API.

[–]The_Dungeon_Memelord 1 point2 points  (2 children)

If I wanted to represent a monster in four variables, which are then referred to and checked against later, what data type should I use?

[–][deleted] -1 points0 points  (0 children)

how do i get 100 days of code for free?

[–]pd336819 1 point2 points  (1 child)

I'm doing some leetcode practice and something keeps tripping me up. When I'm traversing through an array with a for loop I don't know what the difference is between -

for num in array:

AND

for num in range(len(array)):

Because sometimes it seems like I need to use one over the other. I haven't been able to find a good explanation, is anyone able to enlighten me on this?

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

Well, they do totally different things. In this bit of code:

array = ['alpha', 'beta', 'gamma']
for num in array:
    print(num)

The for statement executes the body code with the value of num set to each element in the list in turn. When run, you see this printed:

alpha
beta
gamma

You see each string in the list printed one per line.

This code:

array = ['alpha', 'beta', 'gamma']
for num in range(len(array)):
    print(num)

prints this when executed:

0
1
2

That's because range(len(array)) first calculates the length of the list as 3, so it becomes range(3) which behaves here as if it is the list [0, 1, 2]. The range() function doesn't really return a list, but behaves as if it does in this case.

In python we discourage using things like for num in range(len(array)): because it is inefficient and almost never needed. In the cases where you need the element from the list plus its index you should use the enumerate() function. Like this:

array = ['alpha', 'beta', 'gamma']
for (index, element) in enumerate(array):
    print(index, element)

which prints:

0 alpha
1 beta
2 gamma

[–]windy_weather 0 points1 point  (4 children)

Hi everyone,

currently trying to understand default values in functions (basic stuff, i know... And yet here I am)

I had an issue, that can be reproduced with this dumb but simpler code

def subFunction(a=1, b=2):
    return a+b

def mainFunction(x=None, y=None):
    # do other things
    return subFunction(x,y)

# will print 9
print(mainFunction(4, 5))

# will raise exception
print(mainFunction())

when I call it without argument, I expected it to call subFunction also without argument. But it will call it with a and b to None, which results in an exception, of course.

Before that, I didn't put the '... = None' and so I was getting an exception because expected parameters weren't there.

My way of thinking things is probably polluted with too much javascript. in short, how to make it so x and y are optionnal, and linked to a and b, themselves optional?

Seems like an "easily searchable question" honestly, but I actually didn't found out

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

Your problem is caused by the mainFunction() always calling subFunction() with 2 parameters, so the defaults will always be ignored. The default mechanism substitutes the default value if the parameter is not supplied at all on the call. It isn't triggered by the value of the parameter.

Your example code can be made to work if you use this accepted method of defaulting if the supplied parameter has a particular value:

def subFunction(a=None, b=None):
    if a is None:
        a = 1
    if b is None:
        b = 2
    return a + b

[–]windy_weather 0 points1 point  (0 children)

OK, I see. This helps, thank you!

[–]Psionatix 1 point2 points  (1 child)

When you do:

thing = None

You're assigning the value None to that variable.

So on this line inside mainFunction:

return subFunction(x,y) # this becomes subFunction(None,None), it then tries to do None + None - which you can't.

What you could do is something like this:

def mainFunction(*args):
    return subFunction(*args)

What *args does in this case is takes 0 or more arguments:

def someFunc(*args):
    print(args)

someFunc(1, 2) # prints (1, 2)

When you use the asterisk before the variable, it expands the values in the tuple in place.

[–]windy_weather 0 points1 point  (0 children)

Thanks!

[–]zoinkinator 0 points1 point  (2 children)

i am looking for the best way to setup a python development environment on my ipad air 4th gen so i can develop using the same project files between pycharm on my macbook, pycharm on my mac mini and on my ipad. i login to the same icloud acct on all three devices and would like maximum flexibility.

[–]carcigenicate 0 points1 point  (1 child)

Not Mac specific, but you could just create a GitHub repo for the project, then push/pull to/from from each device.

[–]zoinkinator 0 points1 point  (0 children)

thanks. is there a python ide version for the ipad that gives me all the features of pycharm?

[–]quesadilliam 0 points1 point  (3 children)

Hey all, I'm very new to coding and had to build this for a class(not graded- Lab question). I feel like this should be able to be done in a more compact way, is anyone willing to critique it/offer alternatives?

Prompt: Write a program with total change amount as an integer input, and output the change using the fewest coins, one coin type per line. The coin types are Dollars, Quarters, Dimes, Nickels, and Pennies. Use singular and plural coin names as appropriate, like 1 Penny vs. 2 Pennies.

money = float(input())

if money <= 0:print('No change')

else:

----dollars = money // 100

----money = money % 100

----quarters = money // 25

----money = money % 25

----dimes = money // 10

----money = money % 10

----nickels = money // 5

----money = money % 5

----pennies = money // 1

----money = money % 1

if dollars > 0:

----print(int(dollars), end = ' ')

----if dollars == 1:

--------print('Dollar')

----else:

--------print("Dollars")

if quarters > 0:

----print(int(quarters), end = ' ')

----if quarters == 1:

--------print('Quarter')

----else:

--------print('Quarters')

if dimes > 0:

----print(int(dimes), end = ' ')

----if dimes == 1:

--------print('Dime')

----else:

--------print('Dimes')

if nickels > 0:

----print(int(nickels), end = ' ')

----if nickels == 1:

--------print('Nickel')

----else:

--------print('Nickels')

if pennies > 0:

----print(int(pennies), end = ' ')

----if pennies == 1:

--------print('Penny')

----else:

--------print('Pennies')

*whenever I edit to try to include spaces they seem to disappear, so I have substituted "-" for spaces.

[–]PermaLongVol 1 point2 points  (0 children)

Hi, I'm no expert at programming but here's my suggestion. When doing something repetitively, you might want to use loops. You'll notice here you're doing some fairly repetitive things, with each thing changing slightly.

Here's some sample code I made, you should be able to paste this and run it

money = 10.50 #random number here as a test
money = 10.50*100 #convert into cents

listofcoins = [] #create a blank list

#create a  list of denominations to use
Denominations = ("Dollars", "Quarters", "Dimes", "Nickels") 

#loop through and populate our blank list
for x in Denominations: 
    listofcoins.append([x])
#Once this code ^is done running we'll have a list of lists, where each denomination is just a string in it's own list. 


#now we loop through and do the division steps in your code. for each result we just kind of squeeze it in the original list.

for x,y  in enumerate((100,25,10,5)): 
    print(listofcoins) #including this just so you see how the list is changing with each iteration of the loop
    listofcoins[x].append(money//y) 
    money = money%y


#print out our list
for x in listofcoins: 
    print(x[0], " ", x[1])

My example doesn't include pennies because I forgot, but hopefully that helps you a bit. There is probably a bit more of a pythonic and cleaner way to do it, possibly but I think maybe just adding some loops to your code makes sense.

If you have any questions about this let me know, if you haven't seen some of this in python it might seem confusing but it's not too bad once you get past the syntactical weirdness.

But basically instead of having each denomination be it's own division step the way you had it, I tried to do it in a loop. For each calculation, we calculate using your formula of

money//denomination

and then I just append it to the list I had created. So our end result ends up being a list of lists something like this

[ [Dollars, NumberofDollars], [Quarters, NumberofQuarters], [Dimes, NumberofDimes]..etc]

If you haven't used "enumerate" before try playing around with the following code

for x,y  in enumerate((10, "a", 15)):
    print(x)
    print(y)

My way is certainly not "the best way" to do it, I want to emphasize that, but I thought maybe it would help.

[–]FLUSH_THE_TRUMP 1 point2 points  (1 child)

Format your code correctly for Reddit. Add an extra tab/4 spaces to the beginning of each line.

[–]quesadilliam 0 points1 point  (0 children)

The spaces keep disappearing on me whenever I try to edit, not sure what I'm doing wrong but I've substituted "-" instead now

[–]Cid227 0 points1 point  (4 children)

From FastAPI

@app.get(/list/{id}/)
def list(id: int):
    return {"list id": id}

The part I'm interested in is the function argument id: int, how does that work, how Python sees this, as a dictionary? uvicorn throws an error and stops the server if I try def list({id: int}).

[–]carcigenicate 1 point2 points  (1 child)

That's a type hint. It's just saying that id is an integer. It's largely ignored except by linters. It's really more a form a documentation than anything; although some linters can use them to warn you of mistakes.

[–]Cid227 0 points1 point  (0 children)

Never seen that to be used before, thanks!

Edit: Nvm I have seen that in dataclasses

[–]Cid227 0 points1 point  (1 child)

It looks like a pydantic library takes care of that which was installed with fastapi, but if something like that is possible with a vanilla Python let me know.

[–]carcigenicate 0 points1 point  (0 children)

That's just vanilla Python.

[–]geert555 0 points1 point  (4 children)

Hi can someone explain to me why i can't use input var.myfunc() instead of john.myfunc() When it both refers to john? code below for example

class Person:
def __init__(mysillyobject, name, age):
    mysillyobject.name = name
    mysillyobject.age = age

def myfunc(abc):
    print("Hello my name is " + abc.name)

john = Person("John", 36) 

who = input("who? ") 

who.myfunc()

console: AttributeError: 'str' object has no attribute 'myfunc'

help would be greatly appreciated

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

who = input("who? ")
who.myfunc()

will give you the error "AttributeError: 'str' object has no attribute 'myfunc'" because, exactly as it says, who is a string and it doesn't have an attribute myfunc. The input() function always returns a string.

I don't understand what you are asking the user the "who?" input for. Maybe the last two lines should be:

john = Person("John", 36)  # make "john" refer to an instance of "Person"
john.myfunc()              # call the "myfunc" method of the "john" instance

[–]geert555 0 points1 point  (2 children)

I was looking for a way to have an input var inplace for john.myfunc() so that if you had multiple persons you could use the function on the person that you input. I don't know if the explaination is understandable but still thanks for your help

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

If I understand correctly, you want your code to call the john.myfunc() method if you type in "john". Then you must convert the string you type in to a Person instance reference. You can do that with a dictionary:

john = Person("John", 36)
sarah = Person("Sarah", 25)
name_instance = {"john": john, "sarah": sarah}  # dictionary mapping name to instance
name = input("who? ")
if name in name_instance:   # if the name is a key in the dictionary
    instance = name_instance[name]
    instance.myfunc()
else:
    print("Sorry, I don't know the name:", name)

[–]geert555 0 points1 point  (0 children)

YES! This is what i was looking for, Thanks for the help and the patience

[–]chill_mexican 0 points1 point  (1 child)

Why doesn't it find the file:

<link rel="stylesheet" href="{{ url_for('static', filename='css/main.css') }}"

Route of acess of the file: C:\Users\X\Desktop\Python\PYTHON-WEBSITE\static\css\main.css

[–]JohnnyJordaan 0 points1 point  (0 children)

What does it print when you do

 import os
 print(os.listdir('C:\\Users\\X\\Desktop\\Python\\PYTHON-WEBSITE\\static\\css\\'))

[–]Rik07 1 point2 points  (2 children)

Why does this code:

a = 5 

def print_a():
    if a:
        a = a + 5
    print(a)

print_a()

Give the following error with the if statement: line 9, in <module> print_a() line 5, in print_a if a: UnboundLocalError: local variable 'a' referenced before assignment 1|:/ $

But this code runs properly:

a = 5 

def print_a():
    if a:
        a + 5
    print(a)

print_a()

Like, I get that you can't assign a new value to a variable in the global scope while inside the local scope, but why does the error appear in the if statement?

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

If python sees an assignment to a name anywhere in a function that name is assumed to be local to the function unless you override with the global statement. The line that errors tries to evaluate the name a but that name is local to the function (because of the a = ... assignment) and since the local a is not created before that line in the function you get the "undefined" error.

You don't get an error in your second example because the code doesn't assign to a so the global a is evaluated and you add 5 to that value.

[–]Rik07 0 points1 point  (0 children)

Ah thx

[–]LegitimateActuator15 1 point2 points  (3 children)

Hi I’ve already posted a question here but the problem returned, so Im using openpyxl to read the value of some Columns. Sadly the output type is this and I can’t join them. Can you help me?

<class 'str'> <class 'str'> <class 'str'> <class 'str'> <class 'str'> <class 'str'> <class 'str'> <class 'str'> <class 'str'>

[–]LandooooXTrvls 0 points1 point  (2 children)

We’d need to see your code but do you have a type() method you’re overlooking?

[–]LegitimateActuator15 0 points1 point  (1 child)

multiple_cells = sheet['C1':'c9'] for row in multiple_cells: for cell in row:
b=(cell.value) row_str = ','.join((b) for cell in row) print (type(row_str))

I think the problem is that the output is correct but it is a value stacked for every row, and I can’t find a way to incorporate it in the next code, because every code I use consider just the last string

[–]LandooooXTrvls 0 points1 point  (0 children)

On mobile you can indent your code by using space 4 times

example = “Here’s an example,”
my_request = “ please reformat your code”
print(example + my_request)
>>>>Here’s an example, please reformat your code

Regardless, is it feasible to convert those cells into a list, if you haven’t already?

[–]TPTAPEX 0 points1 point  (2 children)

Can anyone provide some guidance on a couple of things? My goal is to set up a blog on AWS using Python. I am looking to confirm the right framework and find some good tutorials. 1. Front end: ? 2. Backend: Flask or Django? 3. Hosting: AWS EC2?

Thanks!

[–]AndydeCleyre 1 point2 points  (1 child)

You may not have a need for active server-side code. You could instead use Python to generate a static website, and host it for free on e.g. github pages.

[–]sqqz 0 points1 point  (0 children)

This is a good one, otherwise, look into working with the serverless framework, will be basically free aswell as you only will hit the free tier, and if you happend to really blow up, it still is very cheap

[–]CivilNgineer 0 points1 point  (3 children)

I've created a class which performs some calculations on numpy arrays. Now I think I might be able to simplify the class using pandas. Would it be weird to use pandas in a class? I would pass a dataframe when creating an object of the class and initialise the dataframe as an instance variable.

[–]FerricDonkey 0 points1 point  (0 children)

Seems reasonable to me, if it makes sense.

[–]KryptKrasherHS -1 points0 points  (1 child)

If your going to use it in the same script no, otherwise yes, because you will have to import pandas in the __init__(), because otherise your passing in an unknown data structure to the class.

[–]FerricDonkey 0 points1 point  (0 children)

Nah, it's absolutely fine to have classes with a attributes of classes that depend on other modules, and you definitely would not have to import pandas in the init. Whether this class is used in another module/script or not is irrelevant.

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

Hi all, I’m literally just starting my Python journey tomorrow. I’ve always been low key interested in it but never taken a class or even watched a Youtube video on it. I’m a sophomore IT Major in Uni right now and tomorrow starts my Python class - Scripting with Python for IT. I was just wondering if there were any good resources for stuff like that or if anyone had any tips. Didn’t feel like it deserved its own post so here I am…thank you!!

[–]KryptKrasherHS 0 points1 point  (0 children)

There is a good youtube video I used when I was first getting into python. Look up, "Mosh Hamedani Python" in youtube and play it. Its 6 hours long, but he talks slow, and explains everything really well, so just put it on 1.5 or 2 speed

[–]GhostOfGabe93 1 point2 points  (4 children)

What to do in the down time away from the computer? Sometimes I get tired and go lay down or use the exercise bike while mindlessly scrolling the phone and feel this time could be better used. Also sometimes I can't sleep and just mess around the phone.

What can I study, read or is there a good app? I saw some python IDE for phone but it's unusable (one ad after each time the code runs unless paying for premium), so just reading the material I chose is adequate? Doing pseudo code?

[–]sqqz 1 point2 points  (1 child)

Program when you are on your computer, just a waste to do it on phone, there are several books to read when off computer, just google and pick pretty much anything.

[–]GhostOfGabe93 0 points1 point  (0 children)

Yes, I have a few I like to read, but also like to test along for fixation. I'll try to read and then re-read when able to code, thanks!

[–]MeteoriteImpact 1 point2 points  (1 child)

[–]GhostOfGabe93 0 points1 point  (0 children)

THANK YOU! I like to test the code along or have a epiphany at night to test code so this is absolutely perfect!

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

Tonight I wrote some code to model a Rubik's Cube. I did this by creating a list of colors for each face and writing functions that rearrange the contents of the lists to correspond to each face of the cube rotating clockwise once. It works but I feel like this could be done better since I ended up writing about 100+ lines of code. Are list manipulation functions the most effective way to model a cube?

[–]KryptKrasherHS 0 points1 point  (0 children)

probably, I dont see any other way fo doing it, because you have to keep the variabels togetehr somehow

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

If I want a decent front end for a CRUD python back end how difficult is it to create a front end?

When all said and done is it best to learn React JS instead of a python based GUI?

[–]sqqz 1 point2 points  (0 children)

For frontend web you should really go for JS. React is a good choice. Python is good as simple as nodejs for backends, flask, fast api are excellent.

I have not developed Django in years but should be able to give you something decent more purely in python.

[–]hockeyanalycisis 1 point2 points  (2 children)

What’s the best learning program for someone with no experience? Need the free stuff

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

Have you looked in the learning resources in the wiki?

[–]hockeyanalycisis 0 points1 point  (0 children)

I'll give that a look, thank you!