List of Cool Python Syntax

As someone whose background is mostly in Java and C/C++, the following list is what I like about Python syntax (the list is growing as I learn more about Python).

Notes from Reading the Introduction to Python

http://docs.python.org/2/tutorial/introduction.html
1. Can display raw string or display the string as is.

print(r'my file is in c:\')
print("""\
Usage: thingy [OPTIONS]
     -h                        Display this usage message
     -H hostname               Hostname to connect to
""")

2. String can be indexed

newStr = "python"
newStr[1] #print 'y'

3. multiple assignment

a,b = 0,1

4. indentation is Python’s way of grouping statements

5. Get rid of newline and assume newline unless “end=” attribute is used

print(b, end=',')

6 super easy way to prompt user for input

x = int(input("Please enter an integer: "))

 

Notes on Control Flow

http://docs.python.org/2/tutorial/controlflow.html
1. Instead of {…}, use :

In Java

if (x < 0){
    System.out.println("Negative changed to zero");
}else if (x==0){
    System.out.println("Zero");
}else{
    System.out.println("More");
}

In python

if x < 0:
    print "Negative changed to zero"
else if x==0:
    print "Zero"
else:
    print "More"

2. Can modify the sequence you are iterating

No such syntax in Java

Python

for w in words[:]:
    if len(w) > 6:
        words.insert(0,w)

Notes on Python Strings

1. Python strings are immutable

Comments

No comments yet. Why don’t you start the discussion?

Leave a Reply