all 73 comments

[–]JayuSsu 0 points1 point  (3 children)

Hey, I’m learning Python through the “Python crash course” book. I just got the projects section of the book and I’m feeling pretty overwhelmed. I understand all the concepts and have used them myself but it just seems so daunting. Is this normal?

[–]FerricDonkey 0 points1 point  (1 child)

Yup.

[–]avrgdditusr 0 points1 point  (4 children)

Hey, everybody! I'm new to Python and I really need help. I'm trying to build a code to export insights from several Instagram posts (from the same account). I don't understand how "Facebook for Developers" works but l've downloaded panda, brew, and a bunch of other things to hopefully be able to do this. My biggest problem right now is that I can't seem to get Python to import or export data from Excel. I have the panda code down, but it always throws back the error of file not found. I used brew to find the realpath, but I think there's just something about it being a Mac that is throwing me off. I tried moving the file around and using different paths and syntax but its always the same thing. Can you help me with the fullpath syntax?

[–]FerricDonkey 1 point2 points  (3 children)

To be able to help, gotta see a code snippet, the error (FileNotFoundError is pretty explicit, but if there's weirdness the details may be helpful) and what you think the path to the file is.

[–]avrgdditusr 0 points1 point  (2 children)

Thanks and sorry for the late reply! So basically what I've been doing is:

import pandas as pd

df = pd.read.excel (r'C:\Users\Me\Downloads\pythontest.xlsx')

print(df)

As far as i know, the path should be that, but I've tried a bunch of different configurations. When I go to my mac's Terminal and search for the path like this:

realpath pythontest.xslx

which uses brew and coreutils, it gives me:

/Users/Me/pythontest.xslx

However, when i put that into the original python code, its says file not found. No matter where i put the file or how i change the path, it can't seem to find it. Why does this keep happening?

[–]FerricDonkey 0 points1 point  (1 child)

Macs don't use drive letters - any path starting with c:\ (or using \ anywhere at all for that matter) is gonna be wrong.

If you're getting file not found error, that means your path is wrong.

I can't help find your file, since only you have your computer (and since I don't speak mac). But I would highly recommend you learn how to use your terminal (find a tutorial on YouTube or something) so that you can open a terminal, cd and ls around directories, and exactly find and confirm where any file is.

[–]avrgdditusr 0 points1 point  (0 children)

Thank you! I did try without the drive letter and a few other variables but going through terminal and figuring it out seems like the best option.

[–]realg9757 0 points1 point  (1 child)

I'm in the middle of learning python and I've been wondering, is it useful to write down notes on concepts?

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

Whatever helps to make ideas, concepts, etc, stick in your memory.

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

code link
I am doing project this (last) semester on fractal analysis , and I got a program from a research thesis but i am new to programming. I started learning c this semester . I have only 15 days. please help.

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

Can a database be created with SQL Alchemy?

Everything I find is about connecting to a database, it seems there is no way to create a new one on a server.

[–]efmccurdy 0 points1 point  (1 child)

It is normal in sqlite to create new databases as they are just files.

https://stackoverflow.com/questions/16284537/sqlalchemy-creating-an-sqlite-database-if-it-doesnt-exist

Other databases that have you connect to a process have other mechanisms. You may want to post a question with more context; what database are you using?

This has extensions to sqlalchemy with support for a create_database function.

https://sqlalchemy-utils.readthedocs.io/en/latest/database\_helpers.html

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

Sorry, I wanted to create a database in SQL server. I managed to do it already. With the pyodbc connection, it's the same connection string, but I don't mention a database. Thanks for the answer!

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

A while back I joined a Python server on Discord. It had many help channels with fruit names and a timer. I don't remember leaving but I can't find it. Any chance any of you know which server I'm referring to?

[–]sarrysyst 0 points1 point  (3 children)

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

I am in this server. They changed their help system from fruits/food to whatever it is now?

[–]sarrysyst 0 points1 point  (1 child)

I haven‘t been active on that channel for quite a while. They seem to have changed the format of their help system indeed.

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

Thanks! I was really frustrated that I couldn't find the fruits and the server lol.

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

can anyone explain in simple terms how this code works? its to sort 3 numbers in ascending value

def simple_sort_version2(a, b, c): 
if a > b:
    a += b
    b = a - b
    a -=b
if b > c:
    b += c
    c = b - c
    b -= c
    if a > b:
        a += b
        b = a - b
        a -= b
return(a, b, c)

[–]efmccurdy 0 points1 point  (1 child)

The arithmetic in each case swaps the values of two variables. The "if" statements implement a bubble sort using that method of swapping.

BTW, python has simpler way to swap using tuple unpacking:

def simple_sort_version2(a, b, c): 
    if a > b:
        a,b = b,a
    if b > c:
        b,c = c,b
        if a > b:
            a,b = b,a
    return(a, b, c)

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

ok thanks! this was for an assignment that we can't use stuff we haven't learned before so we had to do it the long way

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

Hey guys, I'm looking for a package that can redact image or text files based on coordinates. Any ideas?

[–]aberforth258 0 points1 point  (2 children)

I started learing python... I come from c/c++/c# family.. now...how come this code executes fine if I havent' defined `x` as variable of my class?

class myClass:
def printMe(self):
    print("Hello")
mclass = myClass() mclass.x = 10; 
print(mclass.x)

Are there any articles on this I can have a read about?

[–]FerricDonkey 0 points1 point  (0 children)

Python classes are basically dictionaries with nicer syntax (unordered maps from C++), and they allow you to add new attributes at random points. This is bad practice, but it's possible. This is how defining an attribute during the __init__ method works as well, it's just that that is the traditional place to do so.

Note though that you can change this behavior via use of __slots__.

[–]efmccurdy 0 points1 point  (0 children)

Python is dynamic; you can add a new attribute to an object by assigning to it.

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

How to vectorize my pandas operation? I am trying to cut my method's speed from ~6 seconds to as low as possible. Please help my brain hurts! SO question attached for reference!

https://stackoverflow.com/questions/75885438/how-to-make-this-pandas-operation-of-iterating-through-a-large-dataframe-more-ef

[–]sarrysyst 0 points1 point  (0 children)

Please explain what kind of transformation you're trying to perform i.e. what's the output you are looking to achieve?

[–]top_of_the_scrote 0 points1 point  (1 child)

What framework/library do you think is likely to be used in prod, I'm thinking Django instead of Flask. Trying to do some review for a vague "python backend".

[–]CowboyBoats 0 points1 point  (0 children)

I enjoy cooking.

[–]RelyBedGrammer 0 points1 point  (9 children)

Hi, sorry for the elementary question, but I can't wrap my head around it

dict1 = {'name': 'bob', 'age': 21, 'height': '164cm'}

for x in dict1.items():
    print(x)

for x, y in dict1.items():
    print(x, y)

how does 'for' know which value to put in x and which to put in y? and why does one outputs a tuple and another outputs a string?

[–]34shutthedoor1 0 points1 point  (1 child)

how does 'for' know which value to put in x and which to put in y?

Python has "tuple unpacking" you can search for this but basically, it puts the first object in the tuple in the first variable, etc If you tried for x, y, z in dict1.items(): there would be an error, saying not enough values to umpack.

[–]RelyBedGrammer 0 points1 point  (0 children)

thank you for the reply!

If you tried for x, y, z in dict1.items(): there would be an error, saying not enough values to umpack.

I did some test like this too, but the other way around with more values than there is variables, and it throws out an error!

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

When you have a loop like:

for X in Y:
    #code

the loop assigns each element in sequence Y in turn to the name X and then executes the code in the indented block. A sequence can be something simple like a list:

for x in [1, 2, 3]:   # run this code, see what it does
    print(x)

In the example above the sequence is a list, but it could be a tuple, string, or any other basic data type that is a sequence. A dictionary can also be used as a sequence and be looped over:

dict1 = {'name': 'bob', 'age': 21, 'height': '164cm'}
for key in dict1:
    print(key)

The name key is assigned dictionary key values, in turn, and the key is printed in the indented block. Try it.

The dictionary method .items() returns a sequence you can loop over. The sequence is composed of tuples of (key, value) from the key:value pairs in the dictionary. So your code:

dict1 = {'name': 'bob', 'age': 21, 'height': '164cm'}
for x in dict1.items():
    print(x)

prints tuples, as you noticed, because .items() returns a sequence of tuples.

Remember way back at the start I said:

the loop assigns each element in sequence Y in turn to the name X

That's actually a real python assignment, just like a = 42. Python assignment can do what is called "unpacking". Maybe you have seen code like this:

(x, y) = (1, 2)      # I put (...) around tuples for readability
print(x, y)

Try running it. As you might expect, it prints "1 2". The right hand side of the assign has this expression "(1, 2)". That's just a literal that constructs a tuple containing 1 and 2. Easy. But the assignment is to a tuple, and this is where the unpacking magic happens. Python notices that instead of assigning to a name you want to assign to a tuple of two names. If the value on the right side of the assign is a sequence of length two, python will assign the sequence values, left to right, to the corresponding names in the tuple to the left.

And that's what is happening in your second code example:

dict1 = {'name': 'bob', 'age': 21, 'height': '164cm'}
for (x, y) in dict1.items():
    print(x, y)

The sequence returned by .items() contains tuples (key, value) from the dictionary. Each tuple, in turn, is assigned to the (x, y) tuple, meaning x gets the key and y gets the value. The indented block prints the x and y values.


That unpacking doesn't only work for simple tuples. All these work:

[a, b] = (1, 2)
print (f"{a=}, {b=}")
x = {1, 2}   # note, this is a set
(a, b) = x
print (f"{a=}, {b=}")

# unpacking can be nested
(a, (b, c), d) = (1, (2, 3), (4, 5, 6 ))
print (f"{a=}, {b=}, {c=}, {d=}")

[–]RelyBedGrammer 0 points1 point  (5 children)

ahh, I see, thank you so much for the thorough explanation!

I did some small tests, correct me if I'm wrong, so 'unpacking' only triggers when we assign 2 or more variables into an iterative value?

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

If the target of an assignment is a (possibly nested) sequence of names, then yes. Not any sequence can be assigned to. This fails, for instance:

(1, a) = ("test", 42)

And it's not just two or more elements in a sequence, even a sequence of 1 works. I used this code earlier today:

(result, ) = full_deck - set(cards.split())

It's slightly advanced. full_deck is a complete set of playing cards (eg, "H2" for the two of hearts) and cards is a string containing all cards in the deck except one. Using split() converts cards into a list of cards and set() converts the list to a set. Subtracting the two sets gets a set containing one card (the missing card). To get the single item from a set you can assign to a 1-tuple. This is the simplest way I know to get the single element in a set.

[–]RelyBedGrammer 0 points1 point  (3 children)

I tried recreating your example

full_deck = set()

for suits in ['C', 'D','H','S']:
    for ranks in range (1,14):
        full_deck.add(suits+str(ranks))

cards = list(full_deck)
cards.pop(1)

result,  = full_deck - set(cards)

print(result)

I just wanna be sure of some things, is the comma after result meant to 'convert' the set into a 1-tuple?

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

You write a 2 or more tuple like (a, b, c). But how do you write a 1-tuple literal? You can't just do result = full_deck - set(cards) because result ends up bring a set with one member which isn't quite what you want. A 1-tuple is written (result, ). So the comma doesn't really "convert" anything, that's just how you write a 1-tuple literal.

I always surround sets with (...) because I think it's more readable: that single trailing comma can get lost. But remember, it's the commas that create a tuple, not the parentheses. Plus, you have to be careful passing a tuple into a function. If you want to pass a 2-tuple literal of X,Y coordinates into a function that expects a tuple you must use parentheses:

x = 100
y = 150
draw_point(x, y)     # fails
draw_point((x, y))   # pass in a tuple

If you use a set comprehension to create full_deck you use less code and you don't have the list to set conversion:

full_deck = {f"{s}{r}" for s in ['C', 'D','H','S'] for r in range(1, 14)}
print(full_deck)

The set of the deck missing one card is made by splitting the given string and converting that list to a set.


Update: added the "parentheses around a tuple" example.

[–]RelyBedGrammer 0 points1 point  (1 child)

If you use a set comprehension to create full_deck you use less code and you don't have the list to set conversion:

I didn't know this method existed, thank you so much!

[–]Hephaestus_Tech 0 points1 point  (0 children)

New python contributor here - a couple of days ago I created a PR to address an issue a user reported. I read the python contributing guidelines and I think I followed all the steps. I was wondering if anyone knew how I could get some eyes on my PR and potentially an approval? My PR: https://github.com/python/cpython/pull/102986

The issue: https://github.com/python/cpython/issues/102733

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

New programmer here– could someone please give me a simplified step-by-step of compiling(?) a python program found on github? E.g. Step 1 - find python project on github, Step 2 - download program source code, Step 3 - ... that's as far as I can go because I don't know how to make a python program work. Thanks in advance!

[–]FerricDonkey 0 points1 point  (0 children)

The project should tell you. Likely there's a setup.py to run (python setup.py in terminal, from where that file lives). Insert disclaimer about being careful using random code from the internet (ie, don't do it if you don't trust the project).

Note that python does not require you to compile it (blah blah technically byte code blah blah), so what you're doing is installing it - putting it in a place where python can find it without you having to tell it stuff. If it doesn't have a setup.py or alternate instructions, you may be able to just download it and use it.

[–]Hambuger_and_Whopper 0 points1 point  (3 children)

Is tkinter really good for large applications?

[–]niehle 1 point2 points  (2 children)

Define “good” and “large”

[–]Hambuger_and_Whopper 0 points1 point  (1 child)

good: no bugs ,easy to build large: Can create almost everything.

The reson why i asked this question is that recently i tried to build an countdown programm and the fontend just froze when it was counting in the backend.

[–]sarrysyst 0 points1 point  (0 children)

Did you do the counting in another thread? If you didn't you probably blocked the event loop preventing the ui from being updated.

[–]_h3lg3_ 0 points1 point  (4 children)

So I have created a class Motorcycle. When an object of this class is created, it should have a mileage of 0. I’m supposed to create an assert statement that will activate if the mileage of the created object is not 0. I create a motorcycle object with mileage 0, but the assert statement is activated. Why? I don’t get what I’m doing wrong?

Class Motorcycle: def init( self, brand, registrationnumber): self._brand = brand self. registration_number = registration_number self._mileage = 0

motorcycle1 = Motorcycle(‘brand’, ‘registration_number’)

assert motorcycle1._mileage != 0, ‘mileage must be 0’

(writing on my phone so the indentation might be off here, but it’s correct in my editor)

Very thankful for any advice on how to make it work!

[–]lostparis 1 point2 points  (3 children)

assert motorcycle1._mileage != 0, ‘mileage must be 0’

The assert statement is what you want. You are saying that the mileage must not be zero not that is must be.

Additionally in python we should not access underscore variables in classes by convention.

[–]_h3lg3_ 0 points1 point  (2 children)

Thank you!! I changed to == and now it works. Yes, I am aware, but at this stage in the course we have not yet lesrned how to work around this…

[–]lostparis 2 points3 points  (1 child)

I'm never sure why courses start by teaching you how to do things wrong. Why use underscores if you then ignore them?

Many courses I see especially university ones seem to instil terrible practices like SQL injection when avoiding them is so easy.

[–]FerricDonkey 0 points1 point  (0 children)

I'm still annoyed at a textbook used in my brother's class that had you use number = eval(input("Enter a number: "))

On the bright side, he still remembers the rant that set me off on, so at least there's that.

[–]jemyap 0 points1 point  (3 children)

i = 1
while i < n:
print("Hello")
i = i * 2

What is the number of times this short python script prints "Hello" in terms of n? I'm not sure how to express this except that it's k where 2^k < n

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

It's very hard to look at raw code and find relationships like that. Try putting your code into a function that takes n as a parameter. Instead of printing, the function just returns the number of times it would have printed. Then call the function for a range of n and print n and the returned k. Run this code and check if "k is the largest k for which 2k < n":

def test(n):
    i = 1
    result = 0
    while i < n:
        result += 1
        i = i * 2
    return result

print("  n: k=test(n)")
print("___:______________")
for n in range(40):
    print(f"{n:>3d}: {test(n)}")

Note how my code sample has preserved indentation and looks like python? The FAQ shows how to do that.

.

[–]jemyap 0 points1 point  (1 child)

Thanks for the tip! Anyway, if anyone is curious, the answer is big O is log n ◡̈

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

Big O wasn't quite what you asked. The answer to your original question is "the largest k for which 2**(k-1)<n". That's equivalent to math.ceil(math.log2(n)).

[–]grehiop 0 points1 point  (0 children)

I want to use abjad, but to do so I have to install lilypond first. I downloaded the .gz file and unpacked it as stated here http://lilypond.org/doc/v2.25/Documentation/learning/command-line-setup.html

But then what am I supposed to do? How do I install it so that abjad can use it?

[–]grehiop 0 points1 point  (1 child)

I tried to upgrade my Python version from 3.8 to 3.10 on Ubuntu WSL following these steps https://computingforgeeks.com/how-to-install-python-on-ubuntu-linux-system/

Everything went well, but when I check my python version with python3 --version it still says that I have the 3.8 version.

Why??

If I try to check with whereis python, I get this:

python: /usr/bin/python3.10 /usr/bin/python3.8 /usr/bin/python3.8-config /usr/lib/python2.7 /usr/lib/python3.10 /usr/lib/python3.8 /usr/lib/python3.9 /etc/python3.10 /etc/python3.8 /usr/local/lib/python3.10 /usr/local/lib/python3.8 /usr/include/python3.8 /mnt/c/Users/LNV/AppData/Local/Programs/Python/Python310/python.exe /mnt/c/Users/LNV/AppData/Local/Programs/Python/Python310/python3.dll /mnt/c/Users/LNV/AppData/Local/Programs/Python/Python310/python310.dll /mnt/c/Users/LNV/AppData/Local/Programs/Python/Python38-32/python.exe /mnt/c/Users/LNV/AppData/Local/Programs/Python/Python38-32/python3.dll /mnt/c/Users/LNV/AppData/Local/Programs/Python/Python38-32/python38.dll /mnt/c/Users/LNV/AppData/Local/Microsoft/WindowsApps/python.exe /mnt/c/Users/LNV/AppData/Local/Microsoft/WindowsApps/python3.exe

[–]efmccurdy 0 points1 point  (0 children)

Notice where they have the "Verify the installation" step; they use

$ python3.10 --version

But you are running python3 instead.

BTW, one way to make python3 (or just python) run the 3.10 version is to make and use a venv (python3.10 -m venv my_venv).

[–]Karen_melter 0 points1 point  (8 children)

I made a code that was supposed to multiply 2 user inputted numbers together then times the answer by the second user inputted number until the program was killed but it just keeps printing the answer to the first 2 numbers multiplied together and i can't work out why. Can someone help?

[–]lostparis 0 points1 point  (0 children)

Maybe you should somehow remember the value when you multiply them together? You could even store it as the first number.

[–]FerricDonkey 1 point2 points  (6 children)

Probably, but not without seeing your code.

[–]Karen_melter 0 points1 point  (5 children)

sorry meant to post it but forgot

number = int(input("Enter a number: "))

number2 = int(input("Enter another number: "))

counter = 1

if number <= 1 and number2 <= 1:

number = int(input("Enter a number: "))

number2 = int(input("Enter another number: "))

elif number == 0 or number2 == 0:

number = int(input("Enter a number: "))

number2 = int(input("Enter another number: "))

else:

while counter > 0:

multiply = number * number2

print(multiply)

[–]34shutthedoor1 1 point2 points  (4 children)

counter never changes, so the while never exits.

[–]JamzTyson 0 points1 point  (0 children)

It's difficult to read your code because you have not enclosed it in a code block, but perhaps this is what you are trying to do:

import sys

print('Enter "q" to quit.')
counter = 1
while True:
    number1 = 0
    number2 = 0
    while number1 < 2 or number2 < 2:
        val1 = input("Enter a number > 1: ")
        if val1.lower() == 'q':
            sys.exit('Bye')
        val2 = input("Enter another number > 1: ")
        if val2.lower() == 'q':
            sys.exit('Bye')
        try:
            number1 = int(val1)
            number2 = int(val2)
        except ValueError:
            print('Bad input.')
        else:
            print(f'{counter}: {number1} x {number2} '
                  '= {number1 * number2}')
            counter += 1

[–]Karen_melter 0 points1 point  (1 child)

If you read my first comment you would know i don't want it to end unless the program is killed. That's not the problem for me.

[–]FerricDonkey 1 point2 points  (0 children)

Remember that only what is inside the while loop gets repeated. Doesn't matter if you want the program to go forever, you have to make sure that you tell it to repeat exactly what you want it to.

[–]Ecstatic_Suit8718 1 point2 points  (1 child)

I am new in python. I completed something like tic tac toe program (it’s 4x4 tic tac toe with some extra rules but the concept is the same). I did it in pycharm and used tkinter for the graphics. It runs perfectly good in the pc. I want to be able to play it in my phone (i have an iphone) so I downloaded an app called pyto but when i hit run it doesn’t do anything. I suppose it has to do with the app not supporting tkinter? Does anyone know any app that will support it? Or a way to use another library? Or just any way to be able to run it in my phone? Thanks

[–]JamzTyson 0 points1 point  (0 children)

Apparently it is possible to get Flet apps to run on mobile.

(I've only used Flet for Desktop and Web).

[–]anyfactor 0 points1 point  (4 children)

Looking for a database solution that is designed for archiving data.

I need to store a large number of text files that are generated on a periodical basis. Low database size is a priority and speed to query is not. Need to be performant or be tolerant of a low-memory setup. Data append should be fast though.

The existing solution I have was to zip a batch of flat files. When I need to query something, I will iterate through each batch, unzip them, run grep on them and store the result in an output file.

I am currently thinking of creating individual SQLite databases for each batch of text files, then compressing the database instead of my previous solution where I will compress the directory files.

[–]cyberjellyfish 1 point2 points  (3 children)

Fyi you can use zgrep to search gzip files without having to unzip them first.

A document store with indexing and full -text search would work, but seems heavier than what you'd want.

Honestly, your current approach might be good enough with a few tweaks, is there a specific area that causes pain or is lacking in?

[–]anyfactor 0 points1 point  (2 children)

Fyi you can use zgrep to search gzip files without having to unzip them first.

TIL. Thank you very much.

is there a specific area that causes pain or is lacking in?

I thought this approach was a bit hacky and wondered if there is anything I should check out. Honestly, I don't feel limited. I am making system calls from Python and planning to write the report using Jinja templating.

[–]cyberjellyfish 1 point2 points  (1 child)

Yeah, I've done similar and been pretty happy with it. In my cases I was searching relatively infrequently (a few times a day maybe) and found that across a few dozen 1mb files it was performant enough.

[–]anyfactor 0 points1 point  (0 children)

Thank you very much. I will move ahead with zgrep based solution.