Python basics

Posted in Articles

Tweet This Share on Facebook Bookmark on Delicious Digg this Submit to Reddit

Below is a list of Python basic syntax.   See also Python tutorial for PHP Developers.

comments in Python starts with #

print(‘Hello World’)
print(“Hello World”)

Python 3 has 31 keywords:
and del from not while
as elif global or with
assert else if pass yield
break except import print
class nonlocal in raise
continue finally is return
def for lambda try

In Python 2, they didn’t have nonlocal.  But they did have exec.

Two number data types: int() and float()

type(5) will return <type ‘int’>

type(5.0) will return <type ‘float’>

Casting works like …

int(3.8) will return 3

float(2) will return 2.0

arithmetic operators for exponentiation is **

+= works

In Python 2, if one operand is float, answer is float.

But integer division goes like …

1 / 3 returns 0 (it rounds down)

-7 / 2 returns -4

In Python 3,

7 / 2 returns 3.5

7 // 2 returns 3

-7//3 returns -3

String Concatenation operator is + (just like in Javascript)

‘Hello’*4 returns HelloHelloHelloHello

Variable Names

can not start with a number.

multiple words joined by _ by convention

Functions

def conversion(a,b):
return answer;

Boolean Operators

None, True, False, not, and, or

Comparison Operators

>, <, >=, <=, ==, !=, is, is not

<> works for backwards compatibility, and not recommended.

if statements:

if suchandsuch:
do_this();
elif or_such:
print “hi”;
else:
do_that();