Sie sind auf Seite 1von 38

AN INTRO TO

PYTHON
PROGRAMMING
A Beginners Guide to the Python Programming Language

TABLE OF
CONTENTS

Introduction
Math
Variables
While Loops
For Loops
If Statements
If Else Statements
If Elif Statements
Functions
Function Parameters
Global and Local Variables

INTRODUCTION

When you think of user friendly programming languages, the first


programming language that should come to the mind is Python.
Python has a highly interactive and easy to learn structure and can
be used to do almost anything you might need. Python is
considered the perfect language for a beginner in the world of
programming. Python can be easily integrated with C, C++ or JAVA
and it provides an ease of use unparalleled in programming.

The use of English words for performing operations and easier to


understand syntactical construction as compared to other
languages has made Python an instant hit among the programming
community (even Google relies heavily on it). We will be
discussing various functions and operations that are useful in the
language of Python programming, and what better way to start
than describing through basic mathematical functions.

MATH

Remember the good old days of C programming when writing a


simple function to add two numbers would take around 10-15 line
of code? Now add all the mathematical operations to it,
multiplication, division, subtraction, all in one. Thats not it; now
imagine if the numbers were all in different formats, some float,
some normal integers, some double. Can you think what length of
code will it take to derive a correct mathematical result with these
constraints? Well, actually, wait, save the answer, what if I tell you
that you can do each of these operations in just one single line and
yes you can do it using the Python language.

Can we perform the mathematical calculations in the print


statement? No? Well, now we can. As we mentioned in the
introduction of this book, the power of Python to simplify various
operations is amusing and highly efficient. Building on that, the
print statement is not just a way to display content; even it has
evolved to something better. Let us have a look at an example to
understand better.

Eg:

The output of the above program in Python is:

All we need to do it put the numbers inside the print statement


and Python performs the calculations on its own. Further, if the
numbers are floating point numbers, or if one of the numbers is a
floating point number, we do not have to convert an integer value
into float by putting in a 0 after the decimal.

Now before we conclude this chapter about mathematical


operations in Python, we are going to discuss performing the
square and cube operation. We do not need the math.h header nor
do we have to import the math class, all we have to do is write a
simple print command and the square or cube of a number is
generated.

Eg:

Note:
The first statement squares the integer 4 while the second
statement cubes the integer. However; it is important to note that
the following statement is equivalent to writing 4*4 or 4*4*4 as the
number after the * symbol in the expression give the power of the
number before it.

VARIABLES

In our previous chapter on Python, we discussed how


mathematical functions could be easily performed using a simple
print statement in Python. The user friendliness and amazing
dynamic data type availability and checking make it possible to do
even the complex operations with utmost efficiency and ease. In
this particular chapter, we will be discussing about a more basic
and fundamental aspect of computer programming that is a
common and necessary element of all programming languages; the
variables. As we all know, variables are used to store values which
can then be used for operations and calculations. A variable allows
the user to minimize the time spent on hard coding each and every
line of the program. Assigning values to the variable gives the
programmer the chance to easily use the same value at multiple
locations of the program.

How are variables declared in Python?


Declaring a variable in Python is far easier and structured as
compared to any other object oriented programming language that
you might have used. All we have to do is write the name of the
variable and assign values to that variable. Unlike other
programming languages like C, C++; we do not to declare the
variable before we assign values to it. Let us, with the help of an
example, understand the process of assigning values to a variable
in Python.

Eg:

Output:

The same code when written in C would have required the


following statements.

Eg:

You can clearly notice the difference in the length of the code
between C and Python. This code was just for printing a value in a
variable and still it had a prominent difference; now imagine the
difference for a code that involves more complex functions and
operations.

As we discussed, in python, the variable and its values can also be


directly used in any other variable for performing calculations or
operations. We will now demonstrate the same using the example
we have discussed above.

Eg:

Output:

There are a few things that we must keep in mind regarding


variables to ensure that we do not encounter any error while
working with variables on Python.

1. The name of the variable could be anything that starts with a


character; however it should not start with a number. The
name of the variable can begin with an underscore.
2. Strings are declared inside either single or double quotations.
However; it is better to use double quotations if your text
includes apostrophe marks in it.
3. A floating point value is declared either as a = 3.5 or if it is
an integer value that you want to declare as a float, you can
write a = float(7)
9

4. Just in case you want your print statement to display some


text along with the value in a variable, then in such a case, the
print statement in Python looks similar to the print statement
used in C programming language.

Eg:

The text comes inside the double quotes and the variable name
after the end of the quotation marks. A % sign must precede the
name of the variable and a formatter (%d in this case) must be
written with the text inside the print command. We will learn
more about variables, formatters and their use as we move to the
next chapter in this intro to Python Programming.

10

WHILE LOOPS

Having discussed variables and mathematical functions in the last


two chapters, we will now move towards the part of Python that
forms the core for performing all the operations. It is highly
probably that you might already know about flow control
statements, but given their importance, we are going to discuss
each flow control statement in detail. Flow control statements are
basically loops aimed at performing a particular set of operation for
a period. Writing condition for lets say 100 integers knowing that
the operation to be performed on each one of them is the same is
both ineffective and time consuming. Therefore we need a flow
control statement that can customize our code and group all the
elements together and then write the operation to be performed
for the group instead of doing it for individual elements. To deal
with the repetitive nature of any code or program, we can use
either the for loop or the while loop. However; if the operation to
be performed in each case is the same, while loop is a better
alternative than the for loop. We will discuss more about the for
loop in the upcoming chapters.

11

There are quite a few interesting points to note about the while
loop. First and foremost, a while loop provides a condition and as
long as that condition holds true, performs a specified operation.
The while loop is essentially used to optimize a given code and to
ensure the perfect use of flow control statements in it, therefore it
has a few similarities to both, the IF statement and the FOR
statement.
Eg:

As it is quite clear in the example given above, the while loop


performs the same operation upon a variable until a given
condition holds true. The while keyword is used to initiate a while
loop and the : tells Python that you are going to start the loop
now.
Note:
The condition included inside the while statement can be more than one.
As described in the example, the statement condition = condition +1 is the
same as condition += 1. The choice of statement depends on what the coder
is comfortable with.
We can also decrement the value of the variable in the loop according to the
requirement of the problem and the values desired in the program.

12

Comments and Infinite loop


There are two ways of writing a comment on Python, the first one
is by using the # symbol before the text. However; the # symbol
can only be used for single line comments and for multiple line
comments we must include the comment lines inside triple quotes
() and the same to end the comments.
Infinite loops are things that you should avoid in your code as they
do not give the desired results and in codes that are used for
running applications; an infinite loop may have catastrophic
effects. Knowledge of how an infinite loop occurs is the best
possible way of avoiding its occurrence in the code.
Along with its utility in simple Python codes, While loop is used
extensively in cases where a particular data is to be fetched from a
database. Names of people above a certain age or other related
data can be fetched with ease and accuracy from a big database
using the while loop. However; unlike other programming
languages, using while loop in Python requires the programmer to
structure his/her code very precisely and accurately and the
possibilities of an error, especially in the case of beginners is quite
high. Therefore, if you are just starting with Python, we would
recommend you to prefer for loop during your initial days, until
you are comfortable with the language.

13

FOR LOOPS

In the end of our last chapter, a brief introduction about the


similarity between the While loop and the For Loop was given.
Since we have already discussed about the while loop and how it
functions in python, there cannot be a better way to highlight
those similarities in detail, than by learning the for loop itself.

Both the while loop and the for-loop are used to execute a given
operation for a specified number of time. In most of the cases,
while loop and for loop are interchangeable and the choice
depends upon how comfortable a user is with each one of them.
As we mentioned in the chapter on while loop, for a beginner in
python, it is better to prefer for loop over while, however; learning
both the flow control statements and getting a good grip of them is
extremely essential to get better at any programming language,
including Python.

14

How is the for loop executed?


If there is a fixed number of times any operation needs to be
executed, then in such cases the number of execution cycle of an
operation does not depend on any condition and while loop will be
of little help. Therefore, embedding the more versatile FOR loop
is a better option as it gives the number of times of execution of an
operational cycle in the loop initialization step itself.
Python follows a structure that is very similar to writing codes in
simple English language and therefore, if you have prior experience
of working on languages such as C, C++ or Java, you might loop
find the Python execution of the for-loop to be a little different.
However; if your basics are strong and if you are one of those who
believe in understanding the logic rather than simply mugging up
the rules, then you will find Pythons execution of the for-loop to
be much easier than the others.
Eg 1:

15

Eg 2:

As you will notice, from the two examples, writing a Python


for loop is very simple and straight forward. You do not
have to import packages, mention header files, echo useless
statements, write 10-15 lines of code before you could reach
the actual function. In many ways, Python does what a
function does in all the other programming languages, with
the only difference being that Python does not need the
build up to the function and the function calls. Further, you
will notice that writing a code on Python is as easy and
effortless as writing an algorithm on a piece of paper. If you
know the logic behind it, python will make sure that
keywords and syntax does not create any hindrance for
your ideas.
Note:
1. The use of colon (:) after the statement that involves the for keyword is
absolutely crucial and critical to ensure that the for loop executes exactly
how it is supposed to.
2. You will notice that despite giving (1,11) as inputs to range, the console only
printed number from 1 to 10. The reason behind that is the range does not
include the end of it and therefore it can be compared to the < less than
symbol in for loops used in other languages.

16

IF STATEMENTS

If you will ask a programmer about one flow control statement that
he uses the most and is the most comfortable with, more often
than not the answer would be If Statement. The if statement
finds great application in codes ranging from printing a simple
series to big applications used in our day to day life. The if
statement is also used alongside other flow control statements to
ensure that the operation inside them are carried precisely the way
they are intended to be.

The if statement can be executed along with the else keyword


with the latter used for operational statements that do not satisfy
the condition inside the if statement. However; in this chapter, we
are going to concentrate only on the if statement and leave the
else and the elseif part to the upcoming chapter on these intro to
Python Programming for Beginners.

17

When should we execute the if statements in Python?


While working on Python and writing the code for different
applications, we will come across situations where a different
operation must be performed for different cases. For instance,
certain application or banking procedures do not allow users under
the age of 18. Therefore, after the user enters his/her age in the
banks system, message saying you can use our services; if the age
is above 18, similarly, otherwise a message saying You are not old
enough to use this service, must appear on the website. Achieving
success with such a problem without the if flow control
statement can be slow, time consuming and frustrating, both for
the user and the programmer.

Eg:

18

Those of you who already have experience with programming


might feel that why are we writing these if statements again and
again when we can simply write the else keyword. Well off course
we can use the while keyword but since this chapter is about the if
keyword you might have to wait a little before we jump towards
the end of the road.

Note:
1. As described in the chapter, you cannot use the = sign to compare the
values of two variables. The comparison operator in computer programming
is denoted by the == sign while the = is used for assignment operator.
2. Unlike in the case of languages such as C, C++ or Java, Pythons internal
processing of code is so strong that you do not have to write multiple
conditions with a AND or OR separator. You can simply write all the
conditions in the same line and Python will process the answer for you.

Eg:

19

IF ELSE STATEMENTS

How is if else executed in Python?


The execution of a if else statement in Python is quite similar to
the if statement that we discussed in the previous chapter. In fact,
the if else statement is actually an upgrade to the if statement,
with the latter giving the program more sense and structure. In
layman terms, when we give a condition for a if statement to
execute, the operation inside the if block is executed when the
condition is satisfied. But, what happens when the condition is not
satisfied? This is where the else statement comes in play. The else
statement covers the situation when the condition for the if
statement does not hold true. I know what you are thinking, Why
should I use the else statement when I can give another if
condition? As we have already mentioned, using an else condition
gives more sense and structure to a Python code. However, from a
more technical perspective, using consecutive if statements means
that the compiler needs to check for conditions for each one of
them, thus the performance of the Python code takes a toll. The
else statement gives a more performance savvy solution as it is
automatically executed when the if condition does not hold true.

20

Eg:

Output:

As you can notice, the condition in the if statement does not hold
true and therefore the control jumps to the else statement and the
print statement inside it is displayed on the console. Before we
knew about the else statement, we were using another if
statement to execute the same program, with the else statement,
the program becomes a lot more organized and faster.

21

Note:
1. There are a few things that you must keep in mind while using the if else
statement in your Python code. To start with, one thing that we have
regularly cautioned the beginners in Python about; the proper use of colon
(:) in your code and especially after the statements that lead to a flow
control loop.
2. The other important thing that many programmers miss, is the legitimate
use of the else statement. An else statement is only valid for the condition
that is directly precedes it and therefore any statement before that holds no
control over the functioning of the operation inside the else statement. To
explain it in a better way, let us have a look at this example.

Eg:

Output:

22

As you can notice, the else statement is executed for the condition
in the 2nd if statement and not for the 1st if statement and therefore
you will see the following output in the console. This highlights
another point that the condition in the if statement and the
operation to be performed by the if block and the else block must
be accurate and logical in sense to deliver the desired results on the
console.

23

IF ELIF STATEMENTS

Following on the if, else and the if else statement, in this chapter
we are going to talk about the ifelifelse statements in Python.
The inclusion of the elif condition might be a little new for all the
beginners in Python as they might feel that programming
languages such as C, C++ do not really require or have the elif
statement, but actually elif is just a shorter way of writing elseif.
Having already discussed about the other flow control statements,
in this chapter, we will pay more attention towards the elif part
and the whole combination of flow control statements.

How is elif different from else?


The biggest difference between an else statement and a elif
statement is that while the latter allows you to check multiple
condition statements and execute a particular block of code as
soon as the condition written inside holds true, else statement can
only come in operation when the condition inside the if statement
does not hold true.

Even though both elif and the else statements are optional in a
Python code, a big difference is the number of elif or the else
statements that allowed for a specified block of code. While we can
24

at most have one else statement following an if condition, there is


no such restriction on the elif condition and we can have as many
elif as we want.

Many people often confuse elif with consecutive if statement


execution, however; taking the performance and optimization of
the program into consideration, an elif statement is much better
than the consecutive if statements. It is because consecutive if
require conditions to be checked for each one of them, however;
the operation inside an elif statement is only executed when the if
and the elif statements above it inside a block are not executed.

Eg:

25

Output:

As you can see in the above example, only the part of the code that
satisfies a condition runs while all other conditions after the
successful part of the code are neglected. Once a condition holds
true, the control breaks out of the block and all the conditions after
that elif part hold no significance in the final output on the
console.

Or, And and Break command:


The or keyword is used to insert more than one condition in a
flow control statement. The and keyword is also used to insert
more than one condition in a flow controls statement, however;
both or and and have contrasting effects. While a or keyword
specifies that any one of the listed conditions must hold true, and
keyword means that all the conditions specified must be true to
run the operation in the if statement.

The break statement is used to break the flow of commands in a


code and jump the control to a different place, often to the place
from where the block started executing. The break statement is
used in programs involving big application where a variety of
applications can be performed on each click.
26

FUNCTIONS

It is quite understandable that beginners always shy away from


using functions in their codes and often prefer writing large
number of lines in a program to grouping the functionalities into
different functions. Functions is no doubt a great utility in
computer programming and its advantages are much more than
reducing the line of code and making the program more
presentable and structured. Before, we discuss why we should use
functions and how to use functions in Python, let us talk about the
points that make functions such an important and integral part of
any program.
1. Disintegrates huge problems into smaller pieces from where
the platform of the whole program or application can be laid.
2. Enables reuse of the code in case of programs where a same
set of operation is required to be performed on different
inputs.
3. Building on the point above, functions ensure that there is no
duplicity in the code and unnecessary lines are avoided with
its help.
4. From a security point of view, grouping the code into
different functions ensures that the important information or
code structure is not exposed and also the chances of a fault
in the functioning of the program is less.
27

For any programming language, a function specifies that block of


code which can be used anywhere in the program given it has been
declared in the same program. From a more practical perspective,
imagine you have been given the task of writing a Python program
that calculates the number of alphabets in a string that is entered
by the user, but ignore any integer values that come in between.
No doubt we can achieve such a program without using functions
as well, but imagine how many lines of code it would take and the
number of flow control statements. It is get quite messy and
debugging such a program would be a painful task. However; if we
are using functions, we could easily write different code for a string
with only alphabets and the one with integers in it as well and put
them in different functions. Now finding the set of code which is
not working and correcting the error in it is easy and faster.

Eg:

28

Points to Ponder:
1. There are a few important points to note about using function in Python.
First of all, declaring a Python function is a little different from how
functions are declared in other programming languages. To declare a
function, we must use the keyword def before the name of the function in
the declaration part to tell Python that you intend to start a function
declaration.
2. Since we have mentioned this numerous times in the previous chapters, it
goes without saying that using the colon (:) symbol is necessary and critical
to the correct execution of the Python code.
3. Once you have declared the function and its operation, the next thing is
making the function call. A function call is typically giving a green signal to
the Python that now is the time to execute the operation inside the
function.
4. To make a function call, we just have to type the name of the function
followed by the open and closed parenthesis. We can even call a function
inside any other function like it is done in the example above or we can call
it anyplace else on the same program.

29

FUNCTION PARAMETERS

In the previous chapter on this intro to Python Programming for


Beginners, we discussed about functions and their implementation
in Python. In this chapter we are going to move forward with our
discussion on functions and include the different variations that
one can use while implementing them in Python.

Parameterized Functions can be executed in Python just like they


are executed in any other programming language. The arguments
are passed to the function as parameters and the same are then
used in the operations performed by the function. The arguments
that are passed as parameters, act as variables inside the functions
domain and these variables are then assigned values on which
calculations or operations are done inside the function to deliver
desired results. In some cases, the arguments passed to the
parameters are values themselves and the same can be used for the
operations inside the functions. The number of parameters that
can be passed to a Python function as arguments is not limited to a
number.

30

Note:
1. Even though there is no restriction on the number of arguments passed to a
Python function, it is important to keep in mind that Python can process
only as many number of parameters as the arguments passed to it. In other
words, if you pass three arguments and then initialize values for more than
these three arguments in the function, then Python will not run and show
an error.
2. The values to be given to a parameter that is passed to a function muse be
carefully assigned in case of functions with multiple parameters. Any
discrepancy in this part will not be detected and the Python program will
run but show an output on the console that is not desired.

Eg:

In the above example, it is evident that the values passed to the


function call are same in number as the number of parameters
mentioned in the function definition. The arguments are passed as
values which are then used to perform calculations inside the
function.

31

Since making sure that the number of arguments in function call


are the same as number of parameters in function definition can be
both tricky and unnecessary in programs that involve a lot of
arguments, Python gives the programmers a brilliant way of
avoiding the pain of writing every function parameter even if they
do not intend to use each one of them. Assigning default values to
the function allows the programmer the privilege to later change to
values of only the parameter that he wants to modify without
editing the other values.

Eg:

Above, you will note that the arguments passed to the function by
the name website, are then set as default by saving them to a
variable. This new variable can then later be used anytime to assign
a new value of edit the current value in the function parameter. It
should be noted that even though this saves a lot of time and
effort, such an operation is not feasible in case your program has
numerous function calls and definitions as setting defaults for each
one of them will affect the performance and speed of the program.
32

GLOBAL AND LOCAL VARIABLES

If you have some sort of experience in working on programming


languages such as Java, C or C++, it will not be a surprise to know
that you found the whole concept of global and local variables a bit
confusing at first. In fact, more than 50% of beginners in any
programming language find the global and local variable
differentiation a bit difficult to digest. However; just like any other
programming concept, global-local variables also seem pretty easy
to implement once you understand how Python processes and
works with these variables. Since Python has taken the whole
concept of Object Oriented Programming to a new level whole
together, it reflects on the basic concepts such as global-local
variables as well and you will notice that Pythons understanding of
this concept is a little different from how other programming
languages read them.

33

Eg:

In the above example, it is pretty clear that the variable x is the


global variable while the variable z is a local variable to the
function example. It can be noted that global variables are defined
outside any function in the program while the local variables are
restricted by the boundaries of the function it is defined in.

Since it is much easier to understand the concept of global and


local variables, when it is explained using working examples.
Therefore, this blog post will involve a few more examples than
usual and it is recommended that the readers try out the examples
on their systems to notice the difference.

34

Since local variables are restricted by the domain of a function,


they cannot be directly used in any other function, however the
global variables can be accessed in anywhere in the scope of the
program. So how can we use the global variables in any function of
the program?

Eg:

In the above example, the variable x is used inside the function


example2(). There are a few things to note about using global
variables inside any other function.

35

Note:
1. First and the most important point about using global variables is that their
values cannot be altered. Since global variable are available to the entire
length of the program, their value remains the same as the one initialized at
the beginning. Therefore, an operation such as
x +=1 is not valid if x is a global variable. You can however do this using a
global keyword, the same will be discussed later in the blog post.
2. However; you can use the global variable in any calculation and assign the
value of the calculation to a new variable. This statement can be verified in
the example where global variable x is used to perform an addition
calculation and then the value is assigned to the local variable y.

Using the global variable inside a function can also be achieved by


using the global keyword. However; use of the global keyword
can create problems in the performance of the program in case of
big applications and use of the global keyword is subjected to the
type of program you are creating.

Eg:

36

Thank you for reading!


We invite you to share your thoughts and reactions

Das könnte Ihnen auch gefallen