Basic Syntax of Python

Download as pdf or txt
Download as pdf or txt
You are on page 1of 21

Basic Syntax and Hello World!

program in Python
In this Lesson we will try to understand the syntax of
python programming. Although, syntax is something that
you will understand as you will see more and more
programs and examples, but there are a few things that
you must know before hand.

Python Syntax Rules

1. Python is case sensitive. Hence a variable with


name
yoyostudytonight is not same as yoYoStudytonight

2. For path specification, python uses forward slashes.


Hence if you are working with a file, the default path
for the file in case of Windows OS will have
backward slashes, which you will have to convert to
forward slashes to make them work in your python
script.
For window's path C:\folderA\folderB relative python
program path should be C:/folderA/folderB
3. In python, there is no command terminator, which
means no semicolon ; or anything.
So if you want to print something as output, all you
have to do is:

print ("Hello, World!")

4. In one line only a single executable statement


should be written and the line change act as
command terminator in python.
To write two separate executable statements in a
single line, you should use a semicolon ; to separate
the commands. For example,

print ("Hello, World!") ; print ("This is second line")

5. In python, you can use single quotes '', double


quotes "" and even triple quotes ''' """ to represent
string literals.
6. word = 'word'

7. sentence = "This is a one line sentence."

8. para = """This is a paragraph

which has multiple lines"""

9. In python, you can write comments in your program


using a # at the start. A comment is ignored while the
python script is executed.

10. # this is a comment

11. print ("Hello, World!")

12. # this is a

# multiline comment

13. Line Continuation: To write a code in multiline


without confusing the python interpreter, is by using
a backslash \ at the end of each line to explicitly
denote line continuation. For example,
14. sum = 123 + \

15. 456 + \

789

Expressions enclosed in ( ), [ ] or { } brackets don't


need a backward slash for line continuation. For
example,

vowels = ['a', 'e', 'i',

'o', 'u']

16. Blank lines in between a program are ignored by


python.

17. Code Indentation: This is the most important


rule of python programming. In programming
language like Java, C or C++, generally curly
brackets { } are used to define a code block, but
python doesn't use brackets, then how does python
knows where a particular code block ends. Well
python used indentation for this.
It is recommended to use tab for indentation,
although you can use spaces for indentation as well,
just keep in mind that the amount of indentation for a
single code block should be same.

if True:

print ("Yes, I am in if block");

# the above statement will not be

# considered inside the if block

the correct way would be,

if True:

# this is inside if block

print ("Yes, I am in if block")

Also, the following code will give error, as the


statements are differently indented:

if True:

# this is inside if block


print ("Yes, I am in if block")

# this will give error

print ("me too")

again, the correct way to do so is to keep all the


statements of a particular code block at same
indentation.

if True:

# this is inside if block

print ("Yes, I am in if block")

print ("me too")

So these are some basic rules that you must know so that
it becomes easier for us to learn various concepts of
python programming in the coming tutorials.

First Python Program

We already shared the first python program with you


while learning the syntax. Yes, we were not joking, it's
just one single line, nothing above it, nothing below it. To
print Hello, World! on screen, all you have to do is:

print ("Hello, World!")

You can write and execute this code in IDLE, or you can
save this code in a python code file, name it test.py(you
can name it anything, just keep the extension of the file
as .py).
To run the test.py python script, open IDLE, go to the
directory where you saved this file using the cd command,
and then type the following in command prompt or your
terminal:

python test.py

Copy
This will execute the python script and will show you the
output in the line below.
From the next tutorial we will start learning the various
concepts of python programming language.
Python Numbers and built-in Math Functions
In this section, we will be learning about Numbers and
various Math functions available in python language. In
Numbers, we will see some of the most commonly used
math operators that we can use to perform various
operations on the numbers in python. Under Math
functions section, we will learn about some shortcuts
(called functions), which are very helpful in calculating
some of the complex mathematical expressions
like power, sine/cosine, factorials etc. So, let's begin. We
recommend keeping the IDLE open, while reading, so
that you can practice and learn simultaneously.

Numbers

In Python we have 6 basic mathematical operators, they


are:

1. Addition
2. Subtraction
3. Multiplication
4. Division
5. Modulo
6. Power
Most of you must be familiar with all of the above
operators except for the modulo operator. Don't worry we
will explain it. Let's start from the beginning.

Addition

As you might have guessed it's just simple addition of


numbers. In order to test the operator, just go to IDLE and
type a number, then addition sign +, and then another
number to add to the first number. Press Enter. This must
look like this.
Example: Taking 8 and 19 as example,

>>> 8+19

27

On pressing return(or enter), the answer will appear just


below the code line. And this is how the output will be
displayed, all the time - just below your code line. As
you'll hit the enter key, output will appear in the line
below.
Don't stop with this example, try using the addition
operator with other numbers. Try number with decimal
places, like 4.5 + 5.5 and so on.

Subtraction

Just like addition, subtraction has the same syntax. Just


change the operator to -. Again, pick some random
numbers and try.
Example: We took 89.33 and 23.67, which gave the
output 65.55.

Multiplication

Same again! Just change the operator to *, also known as


an asterisk. You do know that it's used for multiplication,
right? Go ahead and try it in you IDLE.
Example: Take any two numbers and multiply them
using the * operator, just like we did below.
Division

Use / sign this time. And try with random


numbers. Caution: If you're a beginner, you might find
some difficulty in this one. How? Let's see. Let's take
some integer numbers (numbers without decimal)
like 16 and 2, and divide them.

>>> 16/2

Very well. Next, try with 15 and 2. What do you expect


the answer would be? Well, according to proper
mathematics the answer should obviously be 7.5, but if
you actually try this in IDLE, the answer will turn out to
be 7. This happened, because if we perform any
mathematical operation on an integers then the answer
would be an integer. In our case, 15 and 2 both are
integers, hence, our answer is 7, as the answer has to be
an integer.
You might be wondering if it had to be an integer, why it
turned out to be 7 and why not any other integer number.
Well, that is because the answer is determined as the
closest, smaller integer to the original answer. In our case,
the original answer is 7.5, thus the nearest integer to it is 7
and 8, and since we have to pick the smaller one; 7 is
picked as the answer. In mathematics, it is also known
as floor function (it's there in Python too).
Now talking about the solution to the above problem, all
you have to do is, convert any one of the integers(that you
want to divide) into decimal, i.e. write 15.0 instead of 15
and/or 2.0 instead of 2.

Power

This mathematical operator is not usually found in


common programming languages. In fact, Python is the
only language we know which does have an operator for
this. In rest of the languages, they use some pre-defined
functions (shortcut as we mentioned before) to calculate
this. Getting to the point, just put two asterisks
like ** between any two numbers. Example, to
calculate 2 to the power 10, you have to write:

>>> 2**10

1024
With that, we now know about all the commonly used
mathematical operators of python. Now you can try to
combine multiple operators and use them to form one
expression. We will recommend using brackets so that
python can understand what you want as the answer, i.e.
instead of writing 2-9.0/2, write 2-(9.0/2).
Remember BODMAS, how a mathematical expression
with multiple operators is solved in mathematics.

Modulo

Modulo operator is denoted by % percentage sign. If you


are familiar with the computer programming world,
chances are you already know this function. In case you
don't, no need to worry. You know division, right? Then
you know what remainder is, correct? This Modulo
operator, when used with two operands, returns
the remainder as the answer. Here are some quick
examples.
12%2 = 0, since 2 perfectly divides 12.
13%2 = 1, since dividing 13 with 2 leaves 1 as remainder.
19%5 = 4, because, again, 19/5 leaves 4 as the remainder.
It is used in pretty much the same way as it has been
explained here.

To see all the Math operators covered above, live in


action, click on the Live Example button,
And that concludes the numbers section. Let's dive into
math's function now.

Math Functions in Python

As you learn more about python, you might decide to


create a scientific calculator for a project or anything. For
that, along with simple mathematical operations, you will
have to evaluate some complex mathematical operations
as well, like trigonometric operations, logarithmic
operations etc. Forget about the calculator, there can be
various situations where you might need these functions.
Like a software for civil engineers to calculate various
parameters of any structure that they are building, or any
aerospace software - where they need various kinds of
calculations about satellite trajectory, shuttle trajectory
and what not. In a nutshell, the complex mathematical
operations are used in various real life programs and
softwares, hence you must know about them.
Now in Python, some nice guys have already created code
pieces (libraries) for almost every mathematical function.
We can use these codes without any hesitation and the
plus point is, we won't have to re-write it again. Forget
about rewriting, we don't even have to know what the
complete code is. We only need a few key information to
be able to use these readymade code pieces.
Alright, so unofficially function part had already begun.
We'll learn about functions in detail in later chapter, thus
we'll keep this one short.
Function can be described as a piece of code that may or
may not take some value(s) as input, process it, and then
finally may or may not return any value as output.

As you can see in the figure above, here input x is given


to a function f and it is giving some value f(x) as the
output. Although in general programming world,
depending upon the purpose of the function, input and
output are completely optional. But for a mathematical
function, it's very important to have both.
For example, in the trignometric function sin(x), there
must be some value of x in order to calculate and return
the answer, and that pretty much establish why
mathematical functions have both input and output.
In python, there are two types of pre-defined functions.
 Inbuilt functions: These are the functions which
doesn't require any other(external) code file (known
as, Modules or Library Files). These are a part of
the python core and are just built within the Python
compiler hence there is no hassle of importing these
modules/libraries in our code.
 The second type of functions require some external
files(modules) in order to be used. The process of
using these external files in our code is
called importing. So all we have to do is import the
file into our code and use the functions which are
already written in that file.
It's time to try some of the functions. Let's begin with
power functions.

Power - pow(x,y)

I know what you might be thinking. We just tried that,


didn't we? Well, we did saw something that can calculate
power, but it was an operator and this one is an inbuilt
function (yes, the first type). So, with that just consider
this one as an alternative way to calculate power.
Since this one is an inbuilt function, you don't need to
import any other library files (or modules), hence it's
pretty easy to implement.
Since power function will be needing two
numbers(inputs) to perform the operation,
i.e. base and exponent, hence we will have to provide
two numbers to the function. Go ahead, open the IDLE
and write:

>>> pow(3,2)

Copy
Now let's analyse what we did and what will happen.
First, we wrote pow, which is simply the name of the
function that we are trying to call. This will tell the
python compiler to look out for an inbuilt function
named pow and discover what it can do. Next, within the
brackets we wrote two numbers separated with a comma,
i.e. 3 and 2. Here the first number 3 is base and the
second number 2 is an exponent, and we are trying to
calculate 32.
Once the python compiler has ensured that all the syntax
(the grammar of programming) is correct, it will look for
the implementation of the function pow and use it to
find 32. So as you might have expected, the output would
be:

With that, we now know, how a function is called.


Especially for math functions, we can generalise it as
following:

>>> functionName(input1, optionalInput2,


optionalInput3, ...)

Copy
The values inside brackets that had been separated by
commas, which we mentioned to you as input to
functions, are called Arguments. As in pow(x,
y) example given above, 3 and 2 were the arguments.
There can be any number of arguments in a function. And
as we discussed earlier, for a mathematical function there
usually is at least one argument present. Let's see some
another inbuilt mathematical functions.

Absolute - abs(x)
Absolute function, also known as Modulus (not to be
confused with Modulo), returns the non-negative value
of the argument value. Therefore, absolute value of any
non-negative number is the same, while for negative
numbers, their positive value is returned.
Example: absolute value of -3 will be 3, absolute value
of -8.74 will be 8.74 and so on.
Syntax:

>>> abs(-99.99)

Since -99.99 is a negative number, it's positive


counterpart will be the output, i.e. 99.99.

Now let's try some functions where we have to import


some modules(or library files).

Sine - sin(x)

Since we know sine is a trigonometric function, hence it


accepts only one value as an argument, i.e. x. Here x
should be in radians, so you better not confuse it with
a degree. As we mentioned before we won't be able to use
this function directly. If you do, you might get an error,
something like this, which will say name sin is not
defined.

This is because the compiler doesn't know what it is


supposed to do when it encounters sin() function, as we
have not defined this function but we are trying to use it.
So, in order to use it, we will have to import
python's math module which consists the implementation
of the sin() function, which will guide the python
compiler to understand what to do when sin() is called.
What we are about to do is called importing a
module and it's most oftenly done to use already
available ready-made functions. Importing a module
takes just one extra line:

>>> import math

Hit enter, and you're done. Now in order to use


the sin() function, go to a new line and type:

>>> math.sin(3.14159)

Since 3.14159 is approximately the value of π hence the


answer would be near to zero.
As you can see after math.sin(3.14159) statement, the
answer returned was something like 2.653589335273e-6,
it might seem a little messy but it is an equivalent
representation of 2.653589335273 × 10^-6,
or 0.000002653589335273.
Because of approximation in the value of π, the answer
too just got deviated a little bit from 0, but you can see the
value is almost zero. And at the same time, you can see
how accurate the results are.
Now of course there are several other functions available
inside math module, like floor() (floor function; We
mentioned this one in division
operator), exp() (Exponential
function), log() (Logarithmic function), sqrt() (Square
root) and a lot more. You can check out the list, their
syntax, number of arguments accepted and everything at
Python's official website - Mathematical Functions.
Python has a manual on their website where you can see
all the functions listed with all the details. This manual is
called

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy