Python syntax

Make sure you have installed a python interpreter on your computer and working fine.
when you write a python program there are a number of things that are used correctly.

Python indentation

Python does not use curly braces to inclose code or block of a statement like C, C++

Python uses indentation to inclose code or block of code.

Example 1:

if(country=="USA"):

print("Welcome to USA")

 

Note:

The number of spaces depends upon programmer but there must be at least one space.

 

Example 2:

for n in range(1,11):

print(n)

 

Python variables

In python, we don't need to declare a variable, python use variable in the concepts of declaring and initialize together.

as we learned on C, C++, Java, there was mandatory to declare a variable before initializing them or use variables in the program.

Declare and initialize python variables

# as can see variable declaration and initialization being together. 

country="USA"
salary=12000.89
age=40
areYouHungry=True

Note:

As you can see in the above variable declaration, we do not use a semicolon(;) to terminate a syntax like C, C++, and Java
Python does not use a semicolon (;) to terminate the line of code or syntax.

Print python variables

To print python variables print() function is used.

Example 1: String variable

country="USA"
print("My favorite country is "+country)

Note:

As you can see we use + operator to concat string message("My favorite country is") with the variable country.

Example 2: an integer variable

age=22
print("Your age is "+str(age)+" You are so young")

Note:
we are using str() typecasting function to convert an integer variable to string integer.

Example 3: decimal variable

pi=3.14
print("PI has value"+ str(pi))

Example 4: boolean variable

areYouHungry=True
print(areYouHungry)

 

Print variable value without concating or using + operator, using comma(,) operator

age=22
print("Your age is ",age)

Note:
when we use, comma operator there we no need to typecast variable 

Formatting output or use of string format() method to format output

product="Jeans"
quantity=6
rate=1800
total=quantity*rate
# we want to display output as "6 Jeans cost at rate 1800 is 10800"
print("{} {} cost at rate {} is {}".format(quantity,product,rate,total))

Note:

As we use of curly brackets corresponding variables values will be displayed as given in the format method.

Post written by: Hemant Singh
© 2020 - 2020 All rights are reserved