Register a SA Forums Account here!
JOINING THE SA FORUMS WILL REMOVE THIS BIG AD, THE ANNOYING UNDERLINED ADS, AND STUPID INTERSTITIAL ADS!!!

You can: log in, read the tech support FAQ, or request your lost password. This dumb message (and those ads) will appear on every screen until you register! Get rid of this crap by registering your own SA Forums Account and joining roughly 150,000 Goons, for the one-time price of $9.95! We charge money because it costs us money per month for bills, and since we don't believe in showing ads to our users, we try to make the money back through forum registrations.
 
  • Post
  • Reply
Mycroft Holmes
Mar 26, 2010

by Azathoth
been a while since I've done python, so I'm getting errors. Says I have an illegal syntax error after the first if statement

code:
import sys
# variables
coursesList = []


# loop
ask = str(input("Enter A to add course, D to drop course, and E to exit:")
if ask is "A" or ask is "a":
    course = str(input("Enter course to add:"))
    if course in coursesList:
        print("You are already registered in that course")
        ask = str(input("Enter A to add course, D to drop course, and E to exit:")
    else:
        coursesList.append(course)
        coursesList.sort()
        print("Course added")
        print("Courses registered:" + coursesList)
        ask = str(input("Enter A to add course, D to drop course, and E to exit:")
elif ask is "D" or ask is "d":
    course = str(input("Enter course to add:"))
    if course in coursesList:
        print("Course dropped")
        coursesList.remove(course)
        coursesList.sort()
        print("Courses registered:" + coursesList)
        ask = str(input("Enter A to add course, D to drop course, and E to exit:")
    else:
        print("You are not registered in that course")
        ask = str(input("Enter A to add course, D to drop course, and E to exit:")
elif ask is "E" or ask is "e":
    sys.exit()
else:
    print("Please input a valid command")
    ask = str(input("Enter A to add course, D to drop course, and E to exit:")

Adbot
ADBOT LOVES YOU

Bad Munki
Nov 4, 2008

We're all mad here.


On my phone but you’re missing a second close parens?

QuarkJets
Sep 8, 2008

A bunch of lines are missing a closing paren

Use an IDE. Try pycharm

Mycroft Holmes
Mar 26, 2010

by Azathoth

Bad Munki posted:

On my phone but you’re missing a second close parens?

:eng99:

Mycroft Holmes
Mar 26, 2010

by Azathoth
n/m

Loezi
Dec 18, 2012

Never buy the cheap stuff

Mycroft Holmes posted:

been a while since I've done python, so I'm getting errors. Says I have an illegal syntax error after the first if statement

code:
import sys
# variables
coursesList = []


# loop
ask = str(input("Enter A to add course, D to drop course, and E to exit:")
if ask is "A" or ask is "a":
    course = str(input("Enter course to add:"))
    if course in coursesList:
        print("You are already registered in that course")
        ask = str(input("Enter A to add course, D to drop course, and E to exit:")
    else:
        coursesList.append(course)
        coursesList.sort()
        print("Course added")
        print("Courses registered:" + coursesList)
        ask = str(input("Enter A to add course, D to drop course, and E to exit:")
elif ask is "D" or ask is "d":
    course = str(input("Enter course to add:"))
    if course in coursesList:
        print("Course dropped")
        coursesList.remove(course)
        coursesList.sort()
        print("Courses registered:" + coursesList)
        ask = str(input("Enter A to add course, D to drop course, and E to exit:")
    else:
        print("You are not registered in that course")
        ask = str(input("Enter A to add course, D to drop course, and E to exit:")
elif ask is "E" or ask is "e":
    sys.exit()
else:
    print("Please input a valid command")
    ask = str(input("Enter A to add course, D to drop course, and E to exit:")

You are missing a closing parenthesis on the 6th line, at the least.

Other things:
1) input() already returns a string, calling str(input()) does nothing of value.
2) Use == rather than "is" as a general rule. The behaviour of "is" is in many cases (E: not) what you would want. There are very few exceptions where "is" as opposed to == is what you want (e.g. "if value is None" is preferred over "if value == None"). For example:
code:
>>> a = 1000
>>> a is 999 + 1
<stdin>:1: SyntaxWarning: "is" with a literal. Did you mean "=="?
False
>>> a == 999 + 1
True
E: I'm an idiot and missed a "not" in the second point

CarForumPoster
Jun 26, 2013

⚡POWER⚡

QuarkJets posted:

Use an IDE. Try pycharm

A million times this. This should never be a thing you have to worry about.

lazerwolf
Dec 22, 2009

Orange and Black
Also you can use string functions on the input to save yourself from having to check both cases for a given letter value.

code:
if ask.upper() == “A”: do stuff

QuarkJets
Sep 8, 2008

You can also do cool poo poo with dictionary assignment if you're willing to breakup your code a bit into functions

Python code:
def drop_course(my_list):
    # Drop a course
    ...

def add_course(my_list):
   # Add a course
    ...

def exit(my_list):
    print(f'Final course list: {my_list}')
    sys.exit()

def main():
    course_list = []
    while True:
        ask = input("Enter A to add course, D to drop course, and E to exit:").upper()
        command = {'A': add_course, 'D': drop_course, 'E': exit}.get(ask)
        if command is None:
            print('Please input a valid command')
        else:
            command(course_list)
Splitting up your code into functions is good practice, when you're looking at your code later it'll be easier to read if it's broken up into concise functions that have clear intentions. Nested if statements are fine and work, but this is a case where functions really make a lot of sense (e.g. one function to add courses, one to drop, one to exit the application, and then you can use this nice dictionary assignment to map inputs to function calls in 2 lines instead of having a bunch of distinct calls to input())

Da Mott Man
Aug 3, 2012


I would also turn it into a class object so you could reuse it later for multi-person scheduling.

Python code:
class CourseList:
    def __init__(self):
        self.course_list = []

    def drop_course(self):
        # Drop a course
        ...

    def add_course(self):
        # Add a course
        ...

    def exit(self):
        print(f'Final course list: {self.course_list}')
        sys.exit()

def main():
    courses = CourseList()
    while True:
        ask = input("Enter A to add course, D to drop course, and E to exit:").upper()
        command = {'A': courses.add_course, 'D': courses.drop_course, 'E': courses.exit}.get(ask)
        if command is None:
            print('Please input a valid command')
        else:
            command()

if __name__ == '__main__':
    main()
Very basic example but something like that.

Da Mott Man fucked around with this message at 07:19 on Aug 31, 2021

Loezi
Dec 18, 2012

Never buy the cheap stuff

lazerwolf posted:

Also you can use string functions on the input to save yourself from having to check both cases for a given letter value.

code:
if ask.upper() == “A”: do stuff

Interesting, in that I've always been in the "normalize strings to lower case" camp. I wonder if there are e.g. regional differences, or tendencies based on what programming language one first learned.

12 rats tied together
Sep 7, 2006

Python stdlib has str.casefold for this purpose, that way you don't have to care about which direction the casing goes.

CarForumPoster
Jun 26, 2013

⚡POWER⚡

12 rats tied together posted:

Python stdlib has str.casefold for this purpose, that way you don't have to care about which direction the casing goes.

:aaaaa::aaa::aaaaa::aaa::aaaaa:

I can’t believe I never knew this. I have always compared the .upper(), and have that in our style guide, simply because I didn’t know the better answer.

I work with web scraped data from court websites in many jurisdictions with no consistency. This is great.

Loezi
Dec 18, 2012

Never buy the cheap stuff

12 rats tied together posted:

Python stdlib has str.casefold for this purpose, that way you don't have to care about which direction the casing goes.

The python stdlib description makes it sound like "case down and then keep pounding it further down" which I would personally classify as "casing down". But reading the actual unicode standard, it seem to have some caveats along the lines of "for some special cases, like Cherokee letters, instead case up".

But in any case (:haw:) isn't it he same degree of "you don't have to care" as with tolower() and toupper() if you transform both sides with those as well?

OnceIWasAnOstrich
Jul 22, 2006

Loezi posted:

But in any case (:haw:) isn't it he same degree of "you don't have to care" as with tolower() and toupper() if you transform both sides with those as well?

Sure, if you only ever use ASCII/English.

Python code:
>>> ss = "wissen"
>>> eszet = "wißen"
>>> ss==eszet
False
>>> ss.lower()==eszet.lower()
False
>>> ss.casefold()==eszet.casefold()
True

Gin_Rummy
Aug 4, 2007
I have a music synthesizer app I created, which pulls up a GUI off of a single .py file, and I am trying to figure out the best way to port it into a webpage. From what I understand, Flask will take the return values of Python functions and whatnot I feed it then return it to a webpage... but if my app doesn't really have a return value, I can't use Flask, right? Do I need to just rebuild my app entirely in another language like Javascript, or can I use more advanced functionality of Flask/another framework to translate my app?

D34THROW
Jan 29, 2012

RETAIL RETAIL LISTEN TO ME BITCH ABOUT RETAIL
:rant:
What the gently caress am I doing wrong here?
Python code:
1  def save_report(document_data: dict):
2     """
3     Writes the document data to a JSON file for potential processing
4     at another time.
5 
6     :param dict document_data: The dictionary containing the document
7     data to dump to a JSON file.
8     """
9     json_string = json.dumps(document_data, ensure_ascii=False, indent=2)
10    # Check the report type and generate the prefix.
11    report_type = document_data["report_type"]
12    if (report_type == "stormprot_sqft"):
13        prefix = ""
14    filename = build_save_path() + build_filename(prefix, 
15        document_data["job_no"], document_data["job_name"], ".json")
16    log_info(f"Saving line_data to file {filename}")
17    with open(filename, 'w') as outfile:
18        json.dump(json_string, outfile)
19        log_info("Data saved.")
Here's the stack trace.
code:
Traceback (most recent call last):
  File "C:\Users\<redacted>\Documents\pyproj\WhiteUtilGUI\src\guiQt.py", line 229, in save_data
    save_report(line_data)
  File "C:\Users\<redacted>\Documents\pyproj\WhiteUtilGUI\src\savereport.py", line 90, in save_report
    report_type = document_data["report_type"]
TypeError: 'bool' object is not subscriptable
That's line 12 above. I originally had it as "if (document_data["report_type"] == "stormprot_sqft") but changed it after that started throwing an error.

Data Graham
Dec 28, 2009

📈📊🍪😋



Whatever you’re passing in has the value True or False.

Bad Munki
Nov 4, 2008

We're all mad here.


Do a print or log on json_string, what's that say it is?

D34THROW
Jan 29, 2012

RETAIL RETAIL LISTEN TO ME BITCH ABOUT RETAIL
:rant:

Bad Munki posted:

Do a print or log on json_string, what's that say it is?

Data Graham posted:

Whatever you’re passing in has the value True or False.

Dumped json_string to debug.txt and there is exactly one thing in there: "false".

I found it. It was in the caller. Instead of passing self.line_data to save_report() it was just passing line_data...which was passing it a False for some reason, instead of None or whatever. Thank you, never would have figured it out myself. :doh:

death cob for cutie
Dec 30, 2006

dwarves won't delve no more
too much splatting down on Zot:4

Gin_Rummy posted:

I have a music synthesizer app I created, which pulls up a GUI off of a single .py file, and I am trying to figure out the best way to port it into a webpage. From what I understand, Flask will take the return values of Python functions and whatnot I feed it then return it to a webpage... but if my app doesn't really have a return value, I can't use Flask, right? Do I need to just rebuild my app entirely in another language like Javascript, or can I use more advanced functionality of Flask/another framework to translate my app?

I mean, depending on what the app is doing, you can just pass the data into a function that does your synthesis stuff, and if it's just creating a sample and storing it on disk or whatever Flask can just return a redirect to whatever page you started at. I'm imagining something like a sequencer/live synthesis, though, and that you'd probably want to just reimplement in JS if you want it to be an actual website... if you're just using Flask because you don't like any of the Python GUI toolkits, though, it can just run a local server and do whatever.

DoctorTristan
Mar 11, 2006

I would look up into your lifeless eyes and wave, like this. Can you and your associates arrange that for me, Mr. Morden?

D34THROW posted:

it was just passing line_data...which was passing it a False for some reason, instead of None or whatever

This means that the name line_data has been defined as False somewhere in your code. It sounds like you didn’t (deliberately) do that, but are you importing any modules using the pattern from foo import *?

Gin_Rummy
Aug 4, 2007

Epsilon Plus posted:

I mean, depending on what the app is doing, you can just pass the data into a function that does your synthesis stuff, and if it's just creating a sample and storing it on disk or whatever Flask can just return a redirect to whatever page you started at. I'm imagining something like a sequencer/live synthesis, though, and that you'd probably want to just reimplement in JS if you want it to be an actual website... if you're just using Flask because you don't like any of the Python GUI toolkits, though, it can just run a local server and do whatever.

So I have already put together a rough GUI in PyQT and have a working "local" app. I run scipy functions to generate waves and play them real-time with planned sliders and modulation effects to allow adjustments as my sequences play out.

Really I'm just trying to get an idea on the best way to turn it into a web-app, where you load up "www.website.com/mysynth.html" or whatever, and the GUI is there in front of you as I coded it locally in Python. If Flask affords me a way to do that, then great... but if I have to reimplement in JS, so be it; I just don't have the expertise to know one way or the other.

Data Graham
Dec 28, 2009

📈📊🍪😋



GUI platforms are all super different, and web UI constructs are even more different from those. It sounds like what you're talking about would have made a great big grin crack across the faces of some people in a Sun conference room in 1995, because what you're describing is basically what Java Applets promised. And we saw what it took to make those even barely sorta-work.

I'd say your best bet is to rebuild the GUI in HTML/JS/CSS. It'll bear little to no resemblance code-wise to your PyQT app, but it'll be "native".

Gin_Rummy
Aug 4, 2007

Data Graham posted:

GUI platforms are all super different, and web UI constructs are even more different from those. It sounds like what you're talking about would have made a great big grin crack across the faces of some people in a Sun conference room in 1995, because what you're describing is basically what Java Applets promised. And we saw what it took to make those even barely sorta-work.

I'd say your best bet is to rebuild the GUI in HTML/JS/CSS. It'll bear little to no resemblance code-wise to your PyQT app, but it'll be "native".

I gotcha. So could I leverage the Python from the actual wave generator/sequencer portion onto a JS GUI, or am I looking at redoing my entire "app?"

wolrah
May 8, 2006
what?

D34THROW posted:

Thank you, never would have figured it out myself. :doh:
To help you know where to look in the future, this part
code:
report_type = document_data["report_type"]
TypeError: 'bool' object is not subscriptable
was telling you that document_data was a boolean (True/False) and thus the subscript (bracketed key) didn't make sense.

Data Graham
Dec 28, 2009

📈📊🍪😋



Gin_Rummy posted:

I gotcha. So could I leverage the Python from the actual wave generator/sequencer portion onto a JS GUI, or am I looking at redoing my entire "app?"

This feels like the "front end" / "back end" distinction coming into play. Typically you would have the core of your app as-is in Python if it works well, and it would feed its output via an API to the JS front-end which only handles presentation.

The API is just a way of encapsulating and exchanging data; so in practice for your purposes I would imagine your app receives user interactions via the GUI elements and produces sounds in Python, and what that would look like is your HTML/JS button-presses and the like would generate HTTP GET and POST calls (probably using JSON encapsulation) to endpoints in a Flask app wrapped around your Python core, and those endpoints would feed into the code that fiddles with the waveforms and such. And the endpoints would also respond to the GUI with JSON data about the state of the app, what the waveforms are like, whatever you want to display.

I imagine it might also be possible to rebuild the entire core of your app in pure Javascript, which would eliminate this whole separation-of-concerns deal and all this complexity. But, well, that gets into how much you want to code in JS instead of Python...

susan b buffering
Nov 14, 2016

Gin_Rummy posted:

I gotcha. So could I leverage the Python from the actual wave generator/sequencer portion onto a JS GUI, or am I looking at redoing my entire "app?"

If you care about the latency between the UI and the actual sound generating parts of the synth then you'll probably want to rewrite the whole thing in JS. The Web Audio API actually has some pretty decent building blocks for audio synthesis, so it probably won't be as tough as you think.

Gin_Rummy
Aug 4, 2007
Thanks to both of you! I have no problem redoing it in JS, as I've just been waiting for an opportunity/project to finally drive me towards learning JS anyways. I'll probably start going down that path and see where it takes me.

Gin_Rummy fucked around with this message at 01:48 on Sep 2, 2021

CarForumPoster
Jun 26, 2013

⚡POWER⚡
Y’all are nuts saying rebuild it in JS. Assuming the compute time for this is 10sec or less, Plotly dash single page app deployed to heroku. Easy peasy, don’t even need to ditch your QT GUI if you do it right, just import the function. Use boto3 to upload to S3.

Check the last page of my previous posts ITT. I wrote out exactly how to do this. You’ll have a deployed hello world web app that runs a function in 15 minutes for free. Then you add your code.

If your function takes a while, or tour audio files are big, this gets harder as you are hard limited to 30sec.

CarForumPoster fucked around with this message at 04:15 on Sep 2, 2021

punished milkman
Dec 5, 2018

would have won
Can anyone point me to some impressive open source Python projects that are using modern Python features (eg type hints, dataclasses, whatever)? I want to get better at coding and I feel like having something built by smart people as a reference point would really help.

QuarkJets
Sep 8, 2008

I thought the whole point of flask was not having to write your app in javascript, have I been led astray?

accipter
Sep 12, 2003
I recently discovered pyenv with virtual environments and it seems pretty amazing. It is pretty nice because you can configure directory specific environments. It also can mix conda and pip based environments. I found these two webpages helpful:
- https://akrabat.com/creating-virtual-environments-with-pyenv/
- https://realpython.com/intro-to-pyenv/#virtual-environments-and-pyenv
I should note that I am using linux and success on windows might be different.

susan b buffering
Nov 14, 2016

CarForumPoster posted:

Y’all are nuts saying rebuild it in JS. Assuming the compute time for this is 10sec or less, Plotly dash single page app deployed to heroku. Easy peasy, don’t even need to ditch your QT GUI if you do it right, just import the function. Use boto3 to upload to S3.

Check the last page of my previous posts ITT. I wrote out exactly how to do this. You’ll have a deployed hello world web app that runs a function in 15 minutes for free. Then you add your code.

If your function takes a while, or tour audio files are big, this gets harder as you are hard limited to 30sec.

What the gently caress are you talking about? A synthesizer is real-time audio. If you’re talking about seconds then you’re in a completely different universe than the op.

Gin_Rummy
Aug 4, 2007

skull mask mcgee posted:

What the gently caress are you talking about? A synthesizer is real-time audio. If you’re talking about seconds then you’re in a completely different universe than the op.

Also this is mainly a learning exercise for myself. Just cobbling together a solution isn't so much what I'm interested in, as I am really just trying to properly learn to how to code with and implement my code into frameworks.

CarForumPoster
Jun 26, 2013

⚡POWER⚡

skull mask mcgee posted:

What the gently caress are you talking about? A synthesizer is real-time audio. If you’re talking about seconds then you’re in a completely different universe than the op.

Yea I guess I didn’t understand what the requirements of a synthesizer were. Socially appropriate reaction btw.

susan b buffering
Nov 14, 2016

CarForumPoster posted:

Yea I guess I didn’t understand what the requirements of a synthesizer were. Socially appropriate reaction btw.

Lol maybe don’t open your post with “y’all are nuts” when making assertions about a domain you have no knowledge of if you’re looking for a polite response.

death cob for cutie
Dec 30, 2006

dwarves won't delve no more
too much splatting down on Zot:4

QuarkJets posted:

I thought the whole point of flask was not having to write your app in javascript, have I been led astray?

Flask handles the back end. If you wanna do something fancy on the client ('fancy' meaning anything more than puke out a template and some static files), that's gonna be JavaScript.

Or, you know, something else. Like Brython. (which is... JavaScript when you get down to it)

skull mask mcgee posted:

Lol maybe don’t open your post with “y’all are nuts” when making assertions about a domain you have no knowledge of if you’re looking for a polite response.

:agreed:

If we were talking 'synthesizer' like 'speech synthesizer', just generating samples, a simple web app would be fine. If you're looking to do some live knob-tuning or whatever like you would with a VST or a real-deal instrument, even something like a connection via a socket is gonna be dogshit. Like, it's possible, but...

Gin_Rummy posted:

Also this is mainly a learning exercise for myself. Just cobbling together a solution isn't so much what I'm interested in, as I am really just trying to properly learn to how to code with and implement my code into frameworks.

Good news - if you want, you can still get Flask involved in here. It might be overkill, but maybe you forsee a future where you want to save patches or sequences to the database for later access from another machine?

spiritual bypass
Feb 19, 2008

Grimey Drawer

QuarkJets posted:

I thought the whole point of flask was not having to write your app in javascript, have I been led astray?

Yes. Flask is a Python web server framework. Code that runs inside the browser needs to be written separately either in Javascript or in a language that compiles to Javascript.

For a synth, the big question is whether you want it to be interactive (mostly in-browser) or to render sounds to be played back later (mostly server-side)

Adbot
ADBOT LOVES YOU

Gin_Rummy
Aug 4, 2007

rt4 posted:

Yes. Flask is a Python web server framework. Code that runs inside the browser needs to be written separately either in Javascript or in a language that compiles to Javascript.

For a synth, the big question is whether you want it to be interactive (mostly in-browser) or to render sounds to be played back later (mostly server-side)

Definitely both, but emphasis on the former as my primary focus. Sounds like I can develop a bit of back-end development skills by working on the former, though?

  • 1
  • 2
  • 3
  • 4
  • 5
  • Post
  • Reply