Coding For Dummies
Book image
Explore Book Buy On Amazon

Every programming language has its own conventions, like curly braces in JavaScript or opening and closing tags in HTML. Python generally uses less punctuation than other programming languages you may have previously tried. Some sample code is included here:

first_name=raw_input("What's your first name?")
first_name=first_name.upper()
if first_name=="NIK":
    print "You may enter!"
else:
    print "Nothing to see here."

These examples are written for Python 2.7. There are two popular version of Python currently in use — Python 2.7 and Python 3. Python 3 is the latest version of the language but it is not backwards-compatible, so code written using Python 2.7 syntax does not work when using a Python 3 interpreter. Initially, Python 2.7 had more external libraries and support than Python 3, but this is changing.

If you ran this code it would do the following:

  • Print a line asking for your first name.

  • Take user input (raw_input(What’s your first name?)) and save it to the first_name variable.

  • Transform any inputted text into uppercase.

  • Test the user input. If it equals “NIK,” then it will print “You may enter!” Otherwise it will print “Nothing to see here.”

For now, as you look at the code, notice some of its styling characteristics:

  • Less punctuation: Unlike JavaScript, Python has no curly braces, and unlike HTML, no angle brackets.

  • Whitespace matters: Statements indented to the same level are grouped together. In the example above, notice how the if and else align, and the print statements underneath each are indented the same amount. You can decide the amount of indentation, and whether to use tabs or spaces as long as you are consistent. Generally, four spaces from the left margin is considered the style norm.

    See Python style suggestions on indentation, whitespaces, and commenting.

  • Newlines indicate the end of statements: Although you can use semi-colons to put more than one statement on a line, the preferred and more common method is to put each statement on its own line.

  • Colons separate code blocks: New Python programmers sometimes ask why using colons to indicate code blocks, like the one at the end of the if statement, is necessary when newlines would suffice. Early user testing with and without the colons showed that beginner programmers better understood the code with the colon.

About This Article

This article is from the book:

About the book author:

Nikhil Abraham is the CFO of Udacity, an education company that teaches technology skills that help launch or advance a career. Prior to joining Udacity, Nik worked at Codecademy where he taught beginning coders across a variety of professions. He is also author of Coding For Dummies and Getting a Coding Job For Dummies.

This article can be found in the category: