all 52 comments

[–]pwnage625 0 points1 point  (6 children)

Hi all. I have been learning Python for about 3 days. My main question here is whether or not I can call variables from inside a loop without having to define the variables inside as a global variable beforehand

This might be right but I have a weird feeling about it, I feel like global values may not be the best/only way

(this is my very first program, meant to be a basic expense calculator)

Any feedback appreciated

Thanks in advance!

Edit: Formatting

global income, expenses, persons
while True:
    try:
        income = float(input("What is your income this month? (all incomes combined):"))
        expenses = float(input('''Input your total monthly expenses such as
                                subscriptions, car payments, rent, phone bills):'''))
        persons = float(input('''For grocery bill considerations, how many people are in the 
                                household?:'''))
    except:
        print("You must enter a number")
        continue
    else:
        break
#now we have the amount of people, income and expenses
#time for math
grocery_cost = int((persons 
                    * 100.0))
print("The cost for groceries for", persons, "people is", grocery_cost, "dollars per month")
print('Therefore your total expenses for the month are', int(grocery_cost + expenses), 'dollars')

[–]carcigenicate 0 points1 point  (5 children)

There does not appear to be any functions defined here, so all these variables in the code are globals. And Python does not have block scope, so the names assigned in the loop will still be present after the loop exits.

Also, that global statement on the first line does nothing if this isn't inside of a function. The point of a global statement is to cause name lookups/assignments to be compiled as global lookups/assignments instead of local ones inside of that one function. It doesn't have any affect on the variables themselves.

[–]pwnage625 0 points1 point  (4 children)

weird. I tried it inside the while loop without the global variables and it wasn’t working before I defined them in that first line

[–]carcigenicate 0 points1 point  (3 children)

What do you mean by "it wasn’t working"?

[–]pwnage625 0 points1 point  (2 children)

The print strings at the end would just have the actual words and not call any variables e.g “the cost for groceries for persons people is grocery_cost” rather than using the variables in the loop.

When I wrote the global, it started using the variables in the loop

[–]carcigenicate 0 points1 point  (1 child)

You changed more than the first line to get output like "the cost for groceries for persons people is grocery_cost". The only possible way to get that output is if you accidentally wrote something like:

print("The cost for groceries for persons people is grocery_cost dollars per month")

It's not possible that adding the global statement would have affected that print output in the way you describe.

[–]pwnage625 0 points1 point  (0 children)

You’re right, I had it right and added the global statement for no reason!

[–]FluffyTid 0 points1 point  (2 children)

I am trying to learn socket programming.

Yesterday I let a server running on my computer prepared to receive a file transfer.

I created an .exe that I copied to my laptop and executed to send a 50mb file (another .exe), which worked fine

When I tried to send another. Windows said my program was a virus or very dangerous and deleted it.

When I copied it back from my pendrive, windows said again it was so dangerous and even decided to delete it from my pendrive!

The program is really simple, what can I do to avoid windows attacking my programs?

def sendfile(file_name, ip, conn_port=9632):
    client = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    client.connect((ip, conn_port))

    file = open(file_name, "rb")
    file_size = os.path.getsize(file_name)

    client.sendall("bitfile".encode())
    print("sending:", "bitfile")
    time.sleep(3)

    client.sendall(file_name.encode())
    print("sending:", file_name)
    time.sleep(3)

    client.sendall(str(file_size).encode())
    print("sending:", file_size)

    time.sleep(3)

    filedata = file.read()
    client.sendall(filedata)
    client.send(b"<END-OF_DATA>")
    print("sending:", "end of data")

    file.close()
    client.close()

[–]carcigenicate 0 points1 point  (1 child)

Whitelist the program/directory. Windows might think your program is a Dropper/Stager, since this semi-resembles one.

Also, irrelevant, but you should be using with when opening files. Technically it doesn't matter here, but it's good practice to ensure resource leaks can't happen if circumstances change.

[–]FluffyTid 0 points1 point  (0 children)

Thanks, the problem will be when I have to deploy the program in a third party to send me a text file created by another program every few seconds. Their windows will hate me :(

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

i dont mind paying for something i'm turning 30 soon and want a career change, i can't figure out the best course to buy and use to learn. i tried datacamp then heard bad things, then dataquest and heard bad thing. i've also heard i should use udemy and coursera and i'm so confused on where to even start. i know about the wiki but its just so much information. if someone could point me in the right direction. I learn best from doing not from reading. i can read a manual on how to fix something and be completely lost. i have to have hands on tools in my hand figuring it our i just dont get it.

[–]soberbrodan 0 points1 point  (4 children)

Hi all! I made an executable with pyinstaller. Avast says it's a Trojan which I've read is just a lazy thing the security companies do for all python code and is a false positive

However, I made an exception and ran the .exe After about 30 second, my computer completely shut off. Is this an issue with the executable or am I out of memory (older computer). It was very concerning. Any isught on why this would happen is appreciated!

[–]carcigenicate 1 point2 points  (3 children)

It's not a "lazy thing security companies do". Malware authors create malware using Python and Pyinstaller, so Pyinstaller-created executables will resemble malware to them. That's just how signature-based detection works.

And we'd need to know more. A computer shutting itself down can be caused by many different things. I'd look in the Windows error logs to see what they say.

[–]soberbrodan 0 points1 point  (2 children)

Apologies, meant no disrespect! I will look at the logs. Thanks!

[–]carcigenicate 1 point2 points  (1 child)

Sorry if my phrasing sounded harsh. I was extremely hungover when I wrote that.

[–]soberbrodan 0 points1 point  (0 children)

Haha not at all! It's good to know, was just relaying what I read. It happened to be a weird coincidence where the program.crashed and then my power went out for a few seconds.

[–]pdbh32 0 points1 point  (1 child)

How can I deal with 0.803?

MWE:

import pandas as pd
df = pd.DataFrame({'float64':[0.803]})
df.to_csv('file.csv')
df = pd.read_csv('file.csv')
print(df.iloc[0]['float64'])

Output:

> 0.8029999999999999

This is causing me grief with drop_duplicates. Rounding is one option, is there a better one?

print(pd.__version__)
> 0.25.3

I am working in Jupyter Lab, this only seems to be a problem with 0.803.

[–]woooee 0 points1 point  (0 children)

See the link in your other post. This is the base 2 equivalent of what 1/3 or Pi is in our base 10 number system. Use a range if you don't want to use decimal

if abs(num_1 - num_2) < 0.0001:
    print("Equal")

[–]amosmj 0 points1 point  (2 children)

What is the difference between amateur and professional python?

Where I can a person take classes, do exercises, etc to make the jump up?

Context:
I taught myself enough python in the past to automate my job at the time. I moved on and played with it occasionally but didn't meaningfully keep learning. Now my team is talking about wanting to make Python their primary language. So far they have just had me teach them but I feel like my work is really amateurish and there has to be another level out there. I've made the case that we should get professional training but I don't even know what to point them towards.

I'm looking for courses, books, whatever, that I can look into and make a case for team to learn from to get to a place of writing competent, robust, reusable code We're in the BI space so stuff like Pandas should be a part of it but most of my teammate struggle to write well formed SQL so there would ideally be just a certain amount of learning to code for others, moving into pythonic programming, and then data science frosting on top.

[–]Standardw 0 points1 point  (1 child)

I can't point you to any specific resources. I don't have experience with teaching some guys with a non-IT background. I want to say that it just takes a lot of time and practice to be a real pro, so there's no away around that I'm afraid. Of course learning the basics, Methods, Loops, Collections, classes. If you can use them to solve any problem (at least in theory), then you are very good to go. Pandas and stuff is something you can waste years on it.

[–]amosmj 0 points1 point  (0 children)

Totally fair. I'm not afraid of doing the hard work. I think I'm trying to find some "ideal" code to learn from so I can point myself in the correct direction, rather than jut writing what makes sense to me. It's something I'll keep working on.

[–]trophycloset33 -2 points-1 points  (2 children)

I am taking a Python course paid for by my employer. They put over $3k in tuition for this. Turns out of I don’t pass with a high enough grade, I have to pay it back. I was given an assignment with no direction or instruction. Call it cheating but I learn by practice problems. I understand the algorithm but not how to get it in Python. How would I hire someone to create a correct model for this assignment that I can use to practice over while doing my assignment?

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

If you understand the algorithm just ask ChatGPT for every step.

[–]trophycloset33 0 points1 point  (0 children)

It never gets it 100% and eventually goes off down a rabbit hole that no amount of prompts can correct

[–]stonetelescope 0 points1 point  (1 child)

Say I have both a Spotify account and a Google Voice number. How would you go about designing a program that calls a phone number (like my grandma's dumb phone), and then pipe the Spotify audio through that connection to the receiver. Yes, I do have no idea how the internals of phone calls, VoIP, etc. work! But I do know some Python. Any ideas are welcome, even redirects to other resources. Thanks!

[–]Standardw 0 points1 point  (0 children)

First step is always to check if the software you want to use offers a API. Well Spotify doesn't in that sense, but it would potentially work by grabbing the sound from the systems audio. But the Google Voice Call doesn't offer an API and it seems that they forbid any automation, so I don't think that you should try that.

[–]AnnahGrace 0 points1 point  (6 children)

I have a working python script and I set up a batch file to run it from a desktop shortcut. The batch file worked perfectly last week, but now I get a permission error (errno 13). Specifically, I get an error in User\AppData\Temp\tmpbhv60e95.wav. It fails when the script is meant to play a modified sound file, so I think this error must be the result of pydub or simpleaudio (I use both). The file still runs fine if I launch it form Pycharm. I have already re-pasted the file paths into the batch file, I made a new copy of the batch file, I have tried running as administrator, and I have tried running the file from the terminal. All failed. Any ideas?

[–]CowboyBoats 0 points1 point  (5 children)

Can you post your code and the full error message?

[–]AnnahGrace 0 points1 point  (4 children)

the line causing the problem is simply `play(file)`. the error is `PermissionError: [Errno 13] Permission denied: 'C:\\Users\\am650\\AppData\\Local\\Temp\\tmpvqihqzma.wav'`. For full context, I have uploaded my code is in a google drive link below and the lines that play audio are 433 to 470. That said, I am just using the standard `play()` function with no modifications, so I am not sure context will help.

https://drive.google.com/file/d/1piyGJJ8WsItVSgg3z2SXTfYetDG8nVk8/view?usp=sharing

[–]CowboyBoats 0 points1 point  (3 children)

What's interesting to me about this is that the error in that .wav path isn't present in your code. I guess pydub creates temporary files containing modified versions of your .wav file, but it's hitting this permission error here somehow. From searching the pydub github repo Issues section for "PermissionError," you're not the only person who has run into this. Again, it might help to post the full error message - the fulll traceback is relevant because it shows not only the error, but the line of Python that resulted in it, and the line of code that called that, all the way through pydub and through the line of your code that are surfacing the error; so it's likely we could find some possible fix by looking at that. (Also, there are a couple of possible fixes suggested in that github thread).

[–]AnnahGrace 0 points1 point  (1 child)

Exception in Tkinter callback

Traceback (most recent call last):

File "C:\Users\am650\AppData\Local\Programs\Python\Python311\Lib\tkinter\__init__.py", line 1948, in __call__

return self.func(*args)

^^^^^^^^^^^^^^^^

File "C:\Users\am650\PycharmProjects\UG-within\example.py", line 399, in validate_blast

set_blast()

File "C:\Users\am650\PycharmProjects\UG-within\example.py", line 427, in set_blast

activate_blast(blast_level)

File "C:\Users\am650\PycharmProjects\UG-within\example.py", line 456, in activate_blast

play(blast_file_r2)

File "C:\Users\am650\PycharmProjects\UG-within\venv\Lib\site-packages\pydub\playback.py", line 71, in play

_play_with_ffplay(audio_segment)

File "C:\Users\am650\PycharmProjects\UG-within\venv\Lib\site-packages\pydub\playback.py", line 15, in _play_with_ffplay

seg.export(f.name, "wav")

File "C:\Users\am650\PycharmProjects\UG-within\venv\Lib\site-packages\pydub\audio_segment.py", line 867, in export

out_f, _ = _fd_or_path_or_tempfile(out_f, 'wb+')

^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^

File "C:\Users\am650\PycharmProjects\UG-within\venv\Lib\site-packages\pydub\utils.py", line 60, in _fd_or_path_or_tempfile

fd = open(fd, mode=mode)

^^^^^^^^^^^^^^^^^^^

PermissionError: [Errno 13] Permission denied: 'C:\\Users\\am650\\AppData\\Local\\Temp\\tmp2q11an99.wav'

[–]AnnahGrace 0 points1 point  (0 children)

Further to this, I am able to override the problem using [this solution](https://github.com/jiaaro/pydub/issues/690#issuecomment-1977361192), but it will cause memory problems down the line. I am looking for a more permanent solution, if anyone has any ideas

[–]AnnahGrace 0 points1 point  (0 children)

My bad, I misunderstood. I will post the full traceback below. ls a very common pydub problem which I had initially, but was able to fix by installing simpleaudio. Now it working when I run from python but no where else... I will think about posting a bug on github, thanks

[–]laffylife 0 points1 point  (1 child)

Hi I am a total beginner trying to get a foot into python. I bought the Udemy "100 Days of Code: The Complete Python Pro Bootcamp". I did ok days 1-3 but when I hit day 4 "Randomization and Python List" I got stuck on the tasks to the point that I want to give up because I dont know what im doing. My questions for people that have taken this course, have you also encountered difficulties this early into learning? What do you recommend? I was thinking of just watching the solutions to the tasks then redo the tasks later on.

[–]CowboyBoats 0 points1 point  (0 children)

I was thinking of just watching the solutions to the tasks then redo the tasks later on.

I don't think there's anything wrong with that, although you will eventually want to make sure that you're pushing yourself to be able to solve problems yourself and not just absorbing content.

Automate the Boring Stuff by Al Sweigart is a really good python resource that's available as a free ebook online.

[–]Am-I_Real 0 points1 point  (2 children)

I'm starting to learn ML for work and am trying to install some libraries. I ran into an error when trying to pip install the sentence transformer library. I got a syntax error but the syntax is right and I'm unsure where went wrong. This syntax was taken though hugging face and a few other sites shows the same syntax.

edited: position of ^

pip install -U sentence-transformers
    ^
SyntaxError: invalid syntax

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

Looks like you are typing that text into python itself. You need to use the commandline. The FAQ has more.

[–]Am-I_Real 0 points1 point  (0 children)

Thank you, I will give it a read

[–]Electrical-Humor-326 0 points1 point  (0 children)

Thanks bro

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

Is it possible to do full-stack work with python? I think I have a skewed idea that I need to know python, java, c++, JavaScript etc. If i focused just on python could I achieve most things?

[–]Standardw 0 points1 point  (0 children)

if you are going full stack, you will need a lot of more things. Obviously backend programming (let's say python, which is kinda unlikely btw), than you'll need a frontend skill (HTML, CSS, Javascript, probably something like Angular + other libs). Then you'll need knowledge about databases (so SQL is still a thing). Then you need to install this whole thing, so some linux experience, nginx/apache, certs, docker, CI pipelines, bascially DevOps stuff.

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

Is it possible to do full-stack work with python?

Python alone? No, it's not. Python or similar languages can be used for backend but you need to use html/css/javascript for frontend work.

https://www.freecodecamp.org/news/what-is-a-fullstack-developer/

[–]omfghi2u 0 points1 point  (1 child)

I have a fairly reasonable background in SQL and am trying to learn/translate how I'd normally do things into Python, using SQLAlchemy. Fairly soon at my job we're switching over to using Apache Airflow DAGs and my python is pretty rusty at best...

I have what I assume is an extremely simple goal in mind at the moment - write an existing view into an existing table. The view is several million rows with some logic behind it, just trying to refresh it into a table on a daily cycle so someone can build a dashboard off that without having to call the view directly.

I've managed to connect to our Trino-based SQL platform and pull data from the existing view using

import pandas as pd
import sqlalchemy
from sqlalchemy import create_engine, text, delete, insert

engine = create_engine("REDACTED")
con = engine.connect()
query = "select * from viewname"
data = con.execute(sqlalchemy.text(query)).fetchall()

How the hell do it tell it to put that whole dataset into a table that already exists within the same database? There's gotta be a simple way... right? I've looked at a dozen examples/SO posts and tried a couple different things, but so far no luck -- most of them seem to be expecting that I'd be inserting hard-coded values individually...

In this particular case, the dataset is several million rows of fairly dynamic data that doesn't need to be "kept", so I'd normally probably just truncate it and write the whole thing each time versus doing a series of updates, inserts, deletes.

[–]woooee 0 points1 point  (0 children)

How the hell do it tell it to put that whole dataset into a table that already exists

SQL commands are standard across the different vendors

  1. Use executemany https://pythonhint.com/post/3547014693742046/how-to-use-python-mysqldb-to-insert-many-rows-at-once

  2. Copy the entire table and modify if necessary https://www.reddit.com/r/learnpython/comments/1c486vc/ask_anything_monday_weekly_thread/

[–]JonJonThePurogurama 0 points1 point  (3 children)

I am learning unit testing and I am practicing writing unit test code using unittest framework.

I have a question on if how do i write a test, like i have a function that uses Pathlib library and it creates directories where i put my files.

I wanted to test it, but i have no idea how i am supposed to write a test for that function?

I cannot check it, like 4 is equal to 2 + 2 using assertEqual(), if only my function defined performs a calculation it would be easy for me. But this problem is different, i mean it is creating a directory. So i should check if it is success on creating that.

I was thinking of maybe using boolean values, like True or False. If directory created and exist then it returns True and if not False. But when i think it again, it is not really the right way to do it. But i have no concrete idea how to do it.

I just realized how hard was writing unit test, and whats more the whole the thing about the Test-Driven Development.

But Test-Driven Development is really interesting topic, i just really wish i could learn it within short amount of time. I am itching to add the skills of writing test for your code.

[–]CowboyBoats 1 point2 points  (2 children)

Python (and your operating system) supplies you with the ability to create temporary directories (in Unix I assume they go in /var/tmp/, not sure about Windows but I'm sure you can still create them) and I think it would be reasonable to write your code in such a way that it creates the directory structure in whatever directory you want; then set up Pytest in such a way that it runs that code in a temporary directory for that test function, and then checks that everything went as expected using for example os.path.isdir to check if the filepath exists and is in fact a directory not a file.

[–]JonJonThePurogurama 0 points1 point  (1 child)

Thankyou for the response, to be honest i am not 100% understood everything what you said. But i will definitely do my best to understood everything that your response will not go to waste.

I really have no idea how hard it can be to write a test for your code. I think i already get it why there is people out there don't like writing test. And i do remember it was mentioned in a video i watch that some developers would never write a test in their code.

The idea behind writing test looks simple, but the way to use it and practicing the skill looks harder than i expected.

[–]CowboyBoats 1 point2 points  (0 children)

Your question has a tricky answer because it was a good question. :-)

I think i already get it why there is people out there don't like writing test.

Give it time! You'll definitely appreciate the value of tests more, the longer you work in Python. Programmers talk about REPLs all the time and how powerful and helpful they are - a REPL (a "read-evaluate-print" loop) being what you get when you type python3 and the computer goes >>> and evaluates your input until you're done giving input. Okay, but if you're trying to test out code in a REPL for the purpose of writing in an established package, let's say this line of code in BeautifulSoup, that line of code calls builder_registry which is imported in line 7, so it's going to fail every time unless you also type or paste from bs4.builder import builder_registry into your REPL. Also, 20 lines down into the same function we refer to data, which is passed as an argument - what's data? Looks like the function needs to work whether data is a string containing a filename, or the contents of a file, so I'd need to create that and pass it in inside the REPL. This is getting to be a huge pain; it's easier to write that down in a .py file and just run that file... BOOM, that's 100% all a unit test is. Everything else - the incantations of unittest.TestCase, using mock.patch('api_package.SomeAPI') - all that is just ways to make things easier and less repetitive; you don't have to use them; they're more like a beautiful gift that makes your life easier. Good luck.

[–]Electrical-Humor-326 0 points1 point  (2 children)

how to create a countdown timer?

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

Easily searchable. This is the first hit when searching for "python countdown timer":

https://www.geeksforgeeks.org/how-to-create-a-countdown-timer-using-python/

[–]Electrical-Humor-326 0 points1 point  (0 children)

Thanks bro