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.
 
  • Locked thread
namaste friends
Sep 18, 2004

by Smythe
I highly recommend using the free version of pycharm. It will edit your code and make it pep8 compliant.

Adbot
ADBOT LOVES YOU

theguyoncouch
May 23, 2014

EAT THE EGGS RICOLA posted:

Use actual words, don't put compound statements on one line, get rid of most of the comments (your code should self-document for something this simple), put the declarations on separate lines, and join your string like this:

code:
rotated_phrase = []
for letter in phrase:
    (...rotate letter...)
    rotated_phrase.append(rotated_letter)
return ''.join(rotated_phrase)
It's way more efficient than computing, storing, and discarding a new string every time you add to it.

edit:


aag, that too

so i tried to change what you meant. I'm just not sure on the code you added since i've never used it, i'm not sure exactly how to implement it. but from what i read it seems you append the new letter to the list per loop and once ending the loop you .join the list turning into a string before print i'm guessing.

Well my modified code came out as such:

code:
def cipher(words): 								
    new_char   = ""
    new_phrase = [] 
    for char in words:							
        uppercase_check = char.isupper()		
        letter = ord(char.lower())                      
        letter += shift
        if letter > 122: letter -= 26                   #checks to see if ASCII goes over the 'z'
        elif letter < 97: letter += 26                  #checks to see if ASCII goes under the 'a'
        if char.isalpha(): 						
            if uppercase_check == True: letter -= 32    #reverts letter back to capitalized state
            new_char = chr(letter)      			
        else: new_char = char					
        new_phrase.append(new_char)
    return ''.join(new_phrase)								
words = input("Phrase input: ")
shift = int(input("Shift input: "))	
print("result: " + cipher(words))

qntm
Jun 17, 2009

HardDisk posted:

Don't use tabs. Use spaces, preferably 4.

Set your tab size to a single space, then indent using four tabs.

EAT THE EGGS RICOLA
May 29, 2008

Yes, the code I posted is to build a list with your final string as elements, then to just join that list once instead of building a new string every time you add a character.

Ignoring anything else, this is what you get when you inspect this code with pycharm:
code:
def cipher(words):
    new_char   = ""                                     # you don't use this new_char anywhere (you use the next one), and the spacing is off
    new_phrase = []
    for char in words:                                  
        uppercase_check = char.isupper()
        letter = ord(char.lower())
        letter += shift
        if letter > 122: letter -= 26                   # compound statement in one line
        elif letter < 97: letter += 26                  # compound statement in one line
        if char.isalpha():
            if uppercase_check == True: letter -= 32    # comparison to True should be 'if cond is True:' or 'if cond:
            new_char = chr(letter)
        else: new_char = char                           # compound statement in one line
        new_phrase.append(new_char)
    return ''.join(new_phrase)
words = input("Phrase input: ")
shift = int(input("Shift input: "))
print("result: " + cipher(words))

theguyoncouch
May 23, 2014
okay so final edit for learning purposes this is what i ended up with.

code:
def cipher(words):                                    
    new_phrase = []
    for char in words:                                  
        uppercase_check = char.isupper()
        letter = ord(char.lower())
        letter += shift
        if letter > 122:                    #Preventing ASCII from over 'z'
            letter -= 26                   
        elif letter < 97:                   #Preventing ASCII from under 'a'
            letter += 26                  
        if char.isalpha():
            if uppercase_check is True: 
                letter -= 32    
            new_phrase.append(chr(letter))
        else: new_phrase.append(char)                          
    return ''.join(new_phrase)
words = input("Phrase input: ")
shift = int(input("Shift input: "))
print("result: " + cipher(words))

Thermopyle
Jul 1, 2003

...the stupid are cocksure while the intelligent are full of doubt. —Bertrand Russell

You also need some blank lines for readability. I can't think of the studies right now to quote, but something like this:

Python code:
def cipher(words):                                    
    new_phrase = []

    for char in words:                                  
        uppercase_check = char.isupper()

        letter = ord(char.lower())
        letter += shift

        if letter > 122:                    #Preventing ASCII from over 'z'
            letter -= 26                   
        elif letter < 97:                   #Preventing ASCII from under 'a'
            letter += 26      
            
        if char.isalpha():
            if uppercase_check is True: 
                letter -= 32
    
            new_phrase.append(chr(letter))
        else: 
            new_phrase.append(char)                          

    return ''.join(new_phrase)

good jovi
Dec 11, 2000

'm pro-dickgirl, and I VOTE!

theguyoncouch posted:

okay so final edit for learning purposes this is what i ended up with.

code:
def cipher(words):                                    
    new_phrase = []
    for char in words:                                  
        uppercase_check = char.isupper()    #  Instead of defining `uppercase_check`, just say `if char.isupper()` below.
        letter = ord(char.lower())
        letter += shift
        if letter > 122: 
            letter -= 26                   
        elif letter < 97:
            letter += 26                  
        if char.isalpha():
            if uppercase_check is True: 
                letter -= 32    
            new_phrase.append(chr(letter))
        else: new_phrase.append(char)        # put a newline after the colon.                   
    return ''.join(new_phrase)
words = input("Phrase input: ") 
shift = int(input("Shift input: "))
print("result: " + cipher(words))

see comments in code

theguyoncouch
May 23, 2014

good jovi posted:

see comments in code

you're completely correct i never modify char so that should totally work. and yeah i didn't notice. at first i was trying to compress my code into as little lines as possible but i guess that just leaves a mess unless you know what you're looking at.

EAT THE EGGS RICOLA
May 29, 2008

theguyoncouch posted:

you're completely correct i never modify char so that should totally work. and yeah i didn't notice. at first i was trying to compress my code into as little lines as possible but i guess that just leaves a mess unless you know what you're looking at.

Because python is so whitespace dependent, avoiding putting compound statements on one line is really important because it improves readability by a huge amount.

Literally Elvis
Oct 21, 2013

I suppose it's easy to hear people brag about how they did x thing in y lines of code. But from what you guys have said, line count is really only a consideration when it's way larger than you think it should be (indicating the need for optimization)?

EAT THE EGGS RICOLA
May 29, 2008

Low line count doesn't matter at all in professional programming. All that matters is how easy something is to read and modify/extend/maintain.

You read a lot about people proud that they deleted a hundred lines of code and replaced them with 20 lines, but that's usually because the initial code was repetitive and inefficient, not because 20 lines is inherently better than 100.

Space Kablooey
May 6, 2009


Thermopyle posted:

You also need some blank lines for readability. I can't think of the studies right now to quote, but something like this:

Python code:
def cipher(words):                                    
    new_phrase = []

    for char in words:                                  
        uppercase_check = char.isupper()

        letter = ord(char.lower())
        letter += shift

        if letter > 122:                    #Preventing ASCII from over 'z'
            letter -= 26                   
        elif letter < 97:                   #Preventing ASCII from under 'a'
            letter += 26      
            
        if char.isalpha():
            if uppercase_check is True: 
                letter -= 32
    
            new_phrase.append(chr(letter))
        else: 
            new_phrase.append(char)                          

    return ''.join(new_phrase)
It's an issue with theguyoncouch's code, but shift isn't being defined in this function, it really should be a parameter.



qntm posted:

Set your tab size to a single space, then indent using four tabs.

The best option, IMO, is to set tabs to convert to four spaces.

good jovi
Dec 11, 2000

'm pro-dickgirl, and I VOTE!

The best best option is not to argue about tabs vs spaces. Pep8 recommends 4 spaces and most python programmers try to follow pep8. Please let that be the end of it.

Hed
Mar 31, 2004

Fun Shoe
What's the preferred way to install Py3.4 on OS X these days? Brew installs 3.3 by default. I'm trying to get my virtualenvs as easy as it is on my Ubuntu boxes.

Should I just install the official binaries and symlink /usr/bin/local then pyvenv my way to enlightenment?

Symbolic Butt
Mar 22, 2009

(_!_)
Buglord

good jovi posted:

The best best option is not to argue about tabs vs spaces. Pep8 recommends 4 spaces and most python programmers try to follow pep8. Please let that be the end of it.

It doesn't matter but if you're a beginner not too used to forced indentation, using only spaces is a lot less confusing. From me it's a strong recommendation, people complain a lot about this aspect of python BECAUSE they mix tabs and spaces.

With that said theguyonthecouch seemed to be doing well at consistently using only tabs.

Hed posted:

What's the preferred way to install Py3.4 on OS X these days? Brew installs 3.3 by default. I'm trying to get my virtualenvs as easy as it is on my Ubuntu boxes.

Should I just install the official binaries and symlink /usr/bin/local then pyvenv my way to enlightenment?

I like Anaconda. It sets up stuff like numpy and scipy in the least painful way.

good jovi
Dec 11, 2000

'm pro-dickgirl, and I VOTE!

Hed posted:

What's the preferred way to install Py3.4 on OS X these days? Brew installs 3.3 by default. I'm trying to get my virtualenvs as easy as it is on my Ubuntu boxes.

Should I just install the official binaries and symlink /usr/bin/local then pyvenv my way to enlightenment?

I've always been happy with the official binary installers. I believe they put symlinks in /usr/bin/local themselves, but I just keep my PATH updated to make it explicit.

EAT THE EGGS RICOLA
May 29, 2008

good jovi posted:

The best best option is not to argue about tabs vs spaces. Pep8 recommends 4 spaces and most python programmers try to follow pep8. Please let that be the end of it.

You should basically just do this unless you're working with some legacy code that uses tabs or weird spacing, I think.

QuarkJets
Sep 8, 2008

Superior indenting is to use tabs that expand to 3 spaces

BigRedDot
Mar 6, 2008

Hed posted:

What's the preferred way to install Py3.4 on OS X these days? Brew installs 3.3 by default. I'm trying to get my virtualenvs as easy as it is on my Ubuntu boxes.

Should I just install the official binaries and symlink /usr/bin/local then pyvenv my way to enlightenment?

Python 3.4 (or 3.3 or 2.7 or 2.6 or all of the above) environments are super easy to create with conda (the package manager for Anaconda).

BeefofAges
Jun 5, 2004

Cry 'Havoc!', and let slip the cows of war.

theguyoncouch posted:

okay so final edit for learning purposes this is what i ended up with.

code:
if uppercase_check is True: 

You don't need to do this. You can just do:

code:
if uppercase_check:

EAT THE EGGS RICOLA
May 29, 2008

BeefofAges posted:

You don't need to do this. You can just do:

code:
if uppercase_check:

I almost always just do "if condition:", but it can be okay to do "if condition is True:" if it improves readability (which it doesn't in this case).

thegasman2000
Feb 12, 2005
Update my TFLC log? BOLLOCKS!
/
:backtowork:
I am in the learning stages if Python. Has anyone with any experience done the code academy python course? It seem solid but I don't want to complete it if it's teaching bad habits to generally not up to scratch. I like the instant compiler aspect and the saving function of the site so I can do an hour here or there.

I ultimately want to move this knowledge over to swift but that's a long way off as I am struggling enough as it is.

namaste friends
Sep 18, 2004

by Smythe

thegasman2000 posted:

I am in the learning stages if Python. Has anyone with any experience done the code academy python course? It seem solid but I don't want to complete it if it's teaching bad habits to generally not up to scratch. I like the instant compiler aspect and the saving function of the site so I can do an hour here or there.

I ultimately want to move this knowledge over to swift but that's a long way off as I am struggling enough as it is.

Think of learning to program as an iterative process. There's a lot to learn and it might be better to quickly pick up concepts and then refine them later with all the correct patterns. As you work on more projects, you'll pick up tips and tricks from colleagues around you. The o'reilly book on advanced Python is quite good after you've played with Python for a couple months.

Malcolm XML
Aug 8, 2009

I always knew it would end like this.

EAT THE EGGS RICOLA posted:

I almost always just do "if condition:", but it can be okay to do "if condition is True:" if it improves readability (which it doesn't in this case).

Those are semantically different things

namaste friends
Sep 18, 2004

by Smythe
'is' in python is not really the same is '==', correct?

Dominoes
Sep 20, 2007

thegasman2000 posted:

I am in the learning stages if Python. Has anyone with any experience done the code academy python course? It seem solid but I don't want to complete it if it's teaching bad habits to generally not up to scratch. I like the instant compiler aspect and the saving function of the site so I can do an hour here or there.

I ultimately want to move this knowledge over to swift but that's a long way off as I am struggling enough as it is.
I learned the basics of Python through the Code academy tutorial.

Suspicious Dish
Sep 24, 2011

2020 is the year of linux on the desktop, bro
Fun Shoe

Cultural Imperial posted:

'is' in python is not really the same is '==', correct?

It's not.

EAT THE EGGS RICOLA
May 29, 2008

You're of course right, that's what I get for posting while tired/busy.

FoiledAgain
May 6, 2007

Cultural Imperial posted:

'is' in python is not really the same is '==', correct?

I think that if x is y, then x == y, and if id(x)==id(y) then x is y. There is a unique True, a unique False, and a unique None, so either comparison works, e.g. x==None and x is None should do the same thing. Also, this probably only the case with built-in objects. If you've made your own class, then the behaviour of == depends on the __eq__ method.

Hammerite
Mar 9, 2007

And you don't remember what I said here, either, but it was pompous and stupid.
Jade Ear Joe
It should really be a syntax error to have a file that mixes tabs and spaces for indentation.

Lysidas
Jul 26, 2002

John Diefenbaker is a madman who thinks he's John Diefenbaker.
Pillbug

Hammerite posted:

It should really be a syntax error to have a file that mixes tabs and spaces for indentation.

It is.

EDIT: It's specifically a TabError, which is a subclass of SyntaxError.

Lysidas fucked around with this message at 00:09 on Jul 5, 2014

Hammerite
Mar 9, 2007

And you don't remember what I said here, either, but it was pompous and stupid.
Jade Ear Joe

Lysidas posted:

It is.

EDIT: It's specifically a TabError, which is a subclass of SyntaxError.

No it isn't. This file runs without any errors:

code:
def fart ():
	print("fart")

def butt ():
    print("butt")

fart()
butt()

Lysidas
Jul 26, 2002

John Diefenbaker is a madman who thinks he's John Diefenbaker.
Pillbug

Hammerite posted:

No it isn't. This file runs without any errors:

Ah, forgot about that. A TabError is only raised on execution or import when they're on adjacent lines. Resetting the indent stack to 0 prevents the exception. Good point.

Hammerite
Mar 9, 2007

And you don't remember what I said here, either, but it was pompous and stupid.
Jade Ear Joe

Lysidas posted:

Ah, forgot about that. A TabError is only raised on execution or import when they're on adjacent lines. Resetting the indent stack to 0 prevents the exception. Good point.

Well, this also works:

code:
def fart (x):
	if x == 0:
	    print("fart")

fart(0)
fart(1)
I'm not sure I'm being very clear. I am saying that if at least one line in the file contains, amongst its leading whitespace, at least one tab character, and at least one line in the file contains, amongst its leading whitespace, at least one space character, then that should be a syntax error.

BeefofAges
Jun 5, 2004

Cry 'Havoc!', and let slip the cows of war.

Run python with the -tt argument to get errors for mixed tabs/spaces.

https://docs.python.org/2/using/cmdline.html#cmdoption-t

Hmm, did they get rid of this in 3.x?

BeefofAges fucked around with this message at 10:09 on Jul 5, 2014

tef
May 30, 2004

-> some l-system crap ->

theguyoncouch posted:

okay so final edit for learning purposes this is what i ended up with.

code:
def cipher(words):                                    
    new_phrase = []
    for char in words:                                  
        uppercase_check = char.isupper()
        letter = ord(char.lower())
        letter += shift
        if letter > 122:                    #Preventing ASCII from over 'z'
            letter -= 26                   
        elif letter < 97:                   #Preventing ASCII from under 'a'
            letter += 26                  
        if char.isalpha():
            if uppercase_check is True: 
                letter -= 32    
            new_phrase.append(chr(letter))
        else: new_phrase.append(char)                          
    return ''.join(new_phrase)
words = input("Phrase input: ")
shift = int(input("Shift input: "))
print("result: " + cipher(words))

instead of readability, let's look at structure

- You have a bunch of magic numbers in your code
- You have a flag "uppercase_check", which is really more "is_uppercase". It might be easier to duplicate code a little than to have a flag variable.
- You should really pass in shift as a variable too. I tend to go with things like "n" when it's just a number

Anyway, you could try and decompose it into smaller chunks, splitting things like the rotation operation from the handling for upper and lower case letters.

code:
def rot_n(string, n):
    A,Z = ord("A"), ord("Z")
    a,z = ord("a"), ord("z")
    
    def rotate(x, lower, upper):
        r = upper - lower + 1
        return ((x - lower + n) % r) + lower

    def rotate_char(char):
        if a <= char <= z:
            return rotate(char, a, z)
        elif A <= char <= Z:
            return rotate(char, A, Z)
        else:
            return char

    chars = (rotate_char(ord(c)) for c in string)

    return "".join(chr(c) for c in chars)

Hammerite
Mar 9, 2007

And you don't remember what I said here, either, but it was pompous and stupid.
Jade Ear Joe

BeefofAges posted:

Run python with the -tt argument to get errors for mixed tabs/spaces.

https://docs.python.org/2/using/cmdline.html#cmdoption-t

Hmm, did they get rid of this in 3.x?

I found it surprisingly difficult to find information on this, but according to this mailing list page https://mail.python.org/pipermail/python-3000/2008-June/013990.html the option was removed because it's now the default behaviour. Anyway, it isn't strict enough, as I say. I was running the code samples in my previous posts in Python 3.

Crosscontaminant
Jan 18, 2007

Cultural Imperial posted:

'is' in python is not really the same is '==', correct?
I forced myself to understand this because it keeps coming up and a surprising number of people don't get it or only partially get it.

x == y if x and y have the same value, as determined by comparison magic (which includes looking for __eq__/__cmp__ methods and so on).
x is y if x and y are the same object (i.e. id(x) == id(y)). Integers between -5 and 256 and short strings are cached, which is what tends to confuse people.

if butt == None is unsafe, because butt might be a naughty object whose __eq__ method returns True when compared with None.

QuarkJets
Sep 8, 2008

When it comes to testing None, True, and False, always use "is" when comparing to None and just use the actual boolean value of your object instead of comparing to True or False

Adbot
ADBOT LOVES YOU

Squack McQuack
Nov 20, 2013

by Modern Video Games
I'm new to Python and programming in general. I just finished my first program - a game created with Python 2.7, Pyglet, and Cocos2D. I'm having two major problems.

1. Since I'm new to programming, I never considered the game running its update functions at different rates on different computers. One of my classes contains the main game's sprites. The update function for this class applies gravity when the sprite is jumping. On my computer, this was applied 60 times per second. I tested on another computer though, and it seems to be applied at a much faster rate, which results in the sprite barely jumping off the ground.

2. I want to convert this game to an exe file so others can play it. I did this using PyInstaller, and got the exe file to run successfully on my own computer. I ran into trouble on another computer, though. The game runs but there's a weird graphical glitch - there's one sprite that is displayed as a white block.

  • Locked thread