Thursday, April 16, 2015

Syntax

Python script starts with the line

#!/usr/bin/python3


/usr/bin/python3 is the path of the python interpreter



Whitespaces:

In python, block of  codes are manintained using whitespaces. Unlike other programming language where { } are used to represent the block of codes.

Generally 4 spaces are used to represent the block of codes.

Ex:
#!/usr/bin/python3

def test():
    print ("Line1:This shows first line of the block")
    print ("Line2:This shows second line of the block")
print ("Line3:This line is out of the block ")

test()

In above example Line3 print statement is out of test() function since it doesnt start with four spaces


Comments:

In python, comment starts with pound sign #.

Ex:

# This code executes when n < 0


Assignment:

A value is assigned to a variable using =

Ex:
var1=56
var2="Hello World"

Here var1 is assigned with integer value 56 and var2 with string "Hello World"

You can assign multiple variable at once

Ex:
var3, var4 = 66, 77

Conditionals:

If you have to compare datas and then display the result  conditionals are used.

if, elif, else

Ex for if

v1,v2=3,4
if v1<v2:
    print("v2 is greater")

Ex for else

v1,v2=7,4
if v1<v2:
    print("v2 is greater")
else:
    print("v1 is greater")

Ex for elif

v1,v2=7,7
if v1<v2:
    print("v2 is greater")
elif v1>v2:
    print("v1 is greater")
else:
    print("v1 is equal to v2")

Conditional expression:
Compare in one line and display

Ex:
v1, v2=5,3
ans="v1 is greater" if v1>v2 else "v2 is greater"
print(ans)

No comments:

Post a Comment