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
1. Can display raw string or display the string as is.

print(r'my file is in c:\')
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
1. Instead of {…}, use :

In Java

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

In python

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

2. Can modify the sequence you are iterating

No such syntax in Java


for w in words[:]:
    if len(w) > 6:

Notes on Python Strings

1. Python strings are immutable

Leave a Comment