Python Statements

Statements:

Statements are instructions or piece of codes that Python interpreter can execute. We have already seen two kinds of statements: print and assignment. There are other kinds of statements like if statement, for statement, while statement etc.

When you type a statement, the interpreter executes it and displays the result, if something is there. If you write a script it usually contains a sequence of statements. If there is more than one statement, the results appear one at a time as the statements execute one by one.

print(100)
x = 200
y=400
z=x+y
print(z)

Try it Yourself

 

Multi-line statement

In Python, end of a statement is marked by a newline character. But You can write a statement with multiple lines using character (\). Check the following example.

st = "I " + "am" + " Mr." + \
" X."+" I live in " \
"city Y."

print(st)

Try it Yourself

 

Line continuation is implied inside parentheses ( ), brackets [ ] and braces { } in Python. This is called explicit line continuation. For example, you can write the above multi-line statement as the following code.

st = ("I " + "am" + " Mr." +
" X."+" I live in "
"city Y.")

print(st)

Try it Yourself

 

In Python, end of a statement is marked by a newline character. But You can write a statement with multiple lines using character (\). Check the following example. You can use [ ] and { } for the same purpose described above.

st = ["I " + "am " + "Mr. " +
" X."+" I live in "+
"city Y"]
print(st)

You can write multiple statements in a single line using semicolons, as following example.

x= 100; y = 200; c = x*y

print(c)

Python : Indentation

One of the most distinctive features of Python is its use of certain indentation style to mark blocks of code. Once you are wrting python code just be careful of few things:

  • In Python white spaces are important!
  • The indentation is important!
  • If you write program that is not correctly indented shows either errors or does not give result what you want!
  • Python is case sensitive!
  • You can’t safely mix tabs and spaces in Python

Normally, we use tabs or four whitespaces for indentation.

smallest_so_far = 50
for the_num in [9, 41, 12, 3, 74, 15] :
    if the_num < smallest_so_far :
        smallest_so_far = the_num
print (smallest_so_far)
Try it Yourself

 

In Python, if you don’t want to care about indentation at all then write the inner block chunk of code all in one line. Check the following example where two versions of if statement given below, and all are perfectly fine to do exactly the same thing. But it is always best to have indentation for keeping your code neat and clean and making more readability.

i=10
if 1 + 1 == 12: 
    print("xyz") 
    x=100 
    print(x)
else: 
    print("abc") 
    x=200 
    print(x)
i=10
if 1 + 1 == 12: print("xyz"); x=100; print(x)
else: print("abc");x=200; print(x)
Try it Yourself

 

Variable Names and Keywords

Operators and Expressions