Python tutorial part 17 :- python if else statements

Python If Else Statements


 

The If statement is used to test specified condition and if the condition is true, if block executes, otherwise else block executes.The else statement executes when the if statement is false.

 

Python If Else Syntax

 

if(condition):  False  

             statements  

    else:   True  

              statements  

 



 

Example-

 

year=2000  


if year%4==0:  

    print  "Year is Leap"  

else:  

    print "Year is not Leap"  

Output:

Year is Leap

 

Python tutorial part 16 :- python if statements

Python If Statements


 


The Python if statement is a statement which is used to test specified condition. We can use if statement to perform conditional operations in our Python application. The if statement executes only when specified condition is true. We can pass any valid expression into the if parentheses.

 

There are various types of if statements in Python.

if statement


if-else statement


nested if statement


 

Python If Statement Syntax

if(condition):  

   statements  

Python If Statement Example

a=10  


if a==10:  


        print  "Welcome to ApkZube"  


Output:

Welcome to ApkZube

Python tutorial part 15:- Python Comments

Python Comments


 


Python supports two types of comments:


 


1) Single lined comment:


In case user wants to specify a single line comment, then comment must start with ?#?


 


Eg:


# This is single line comment.  


 


2) Multi lined Comment:


Multi lined comment can be given inside triple quotes.


 


eg:


''''' This 


    Is 

    Multipline comment'''  

 


eg:


#single line comment  


print "Hello Python"  

'''''This is 

multiline comment'''  

 


Python tutorial part 14 :- python Operators

Python Operators


 

Operators are particular symbols that are used to perform operations on operands. It returns result that can be used in application.

 

Example

1.    4 + 5 = 9  


 

Here 4 and 5 are Operands and (+) , (=) signs are the operators. This expression produces the output 9.

 

Types of Operators

Python supports the following operators

Arithmetic Operators.


Relational Operators.


Assignment Operators.


Logical Operators.


Membership Operators.


Identity Operators.


Bitwise Operators.


 

Arithmetic Operators

The following table contains the arithmetic operators that are used to perform arithmetic operations.

 

Operators

Description

//

Perform Floor division(gives integer value after division)

+

To perform addition

-

To perform subtraction

*

To perform multiplication

/

To perform division

%

To return remainder after division(Modulus)

**

Perform exponent(raise to power)

 

Example

>>> 10+20  


30  

>>> 20-10  

10  

>>> 10*2  

20  

>>> 10/2  

5  

>>> 10%3  

1  

>>> 2**3  

8  

>>> 10//3  

3  

>>>  

 

Relational Operators

The following table contains the relational operators that are used to check relations.

 

Operators


Description


Less than

Greater than

<=

Less than or equal to

>=

Greater than or equal to

==

Equal to

!=

Not equal to

<> 

Not equal to(similar to !=)

 

eg:

>>> 10<20  


True  

>>> 10>20  

False  

>>> 10<=10  

True  

>>> 20>=15  

True  

>>> 5==6  

False  

>>> 5!=6  

True  

>>> 10<>2  

True  

>>>  

 

Assignment Operators

The following table contains the assignment operators that are used to assign values to the variables.

 

Operators


Description


=

Assignment

/=

Divide and Assign

+=

Add and assign

-=

Subtract and Assign

*=

Multiply and assign

%=

Modulus and assign

**=

Exponent and assign

//=

Floor division and assign

 

Example

1.    >>> c=10  


2.    >>> c  

3.    10  

4.    >>> c+=5  

5.    >>> c  

6.    15  

7.    >>> c-=5  

8.    >>> c  

9.    10  

10. >>> c*=2  

11. >>> c  

12. 20  

13. >>> c/=2  

14. >>> c  

15. 10  

16. >>> c%=3  

17. >>> c  

18. 1  

19. >>> c=5  

20. >>> c**=2  

21. >>> c  

22. 25  

23. >>> c//=2  

24. >>> c  

25. 12  

26. >>>  

 

Logical Operators

The following table contains the arithmetic operators that are used to perform arithmetic operations.

 

Operators


Description


and

Logical AND(When both conditions are true output will be true)

or

Logical OR (If any one condition is true output will be true)

not

Logical NOT(Compliment the condition i.e., reverse)

 

Example

a=5>4 and 3>2  


print a  

b=5>4 or 3<2  

print b  

c=not(5>4)  

print c  

Output:

1.    >>>   

2.    True  

3.    True  

4.    False  

5.    >>>  

 

Membership Operators

The following table contains the membership operators.

 

Operators


Description


in

Returns true if a variable is in sequence of another variable, else false.

not in

Returns true if a variable is not in sequence of another variable, else false.

 

Example

a=10  


b=20  

list=[10,20,30,40,50];  

if (a in list):  

    print "a is in given list"  

else:  

    print "a is not in given list"  

if(b not in list):  

    print "b is not given in list"  

else:  

    print "b is given in list"  

Output:

>>>   

is in given list  

is given in list  

>>>  

 

Identity Operators

The following table contains the identity operators.

 

Operators


Description


is

Returns true if identity of two operands are same, else false

is not

Returns true if identity of two operands are not same, else false.

 

Example

a=20  


b=20  

if( a is b):  

    print  a,b have same identity  

else:  

    print a, b are different  

b=10  

if( a is not b):  

    print  a,b have different identity  

else:  

    print a,b have same identity  

Output

>>>   

a,b have same identity  

a,b have different identity  

>>>  

 

Python tutorial part 13:- python Literals

Python Literals


 


Literals can be defined as a data that is given in a variable or constant.


Python support the following literals:


 


I. String literals:


String literals can be formed by enclosing a text in the quotes. We can use both single as well as double quotes for a String.


 


Eg:


"Aman" , '12345'


 


Types of Strings:


There are two types of Strings supported in Python:


a).Single line String- Strings that are terminated within a single line are known as Single line Strings.


 


Eg:


1.    >>> text1='hello'  


 


b).Multi line String- A piece of text that is spread along multiple lines is known as Multiple line String.


There are two ways to create Multiline Strings:


 


1). Adding black slash at the end of each line.


Eg:


>>> text1='hello\  


user'  

>>> text1  

'hellouser'  

>>>  

 


2).Using triple quotation marks:-


Eg:


>>> str2='''''welcome 


to 

SSSIT'''  

>>> print str2  

welcome  

to  

SSSIT  

>>>  

 


 


II.Numeric literals:


 


Numeric Literals are immutable. Numeric literals can belong to following four different numerical types.


 


Int(signed integers)

Long(long integers)

float(floating point)

Complex(complex)

Numbers( can be both positive and negative) with no fractional part.eg: 100

Integers of unlimited size followed by lowercase or uppercase L eg: 87032845L

Real numbers with both integer and fractional part eg: -26.2

In the form of a+bj where a forms the real part and b forms the imaginary part of complex number. eg: 3.14j

 


III. Boolean literals:


A Boolean literal can have any of the two values: True or False.


 


IV. Special literals.


Python contains one special literal i.e., None.


None is used to specify to that field that is not created. It is also used for end of lists in Python.


 


Eg:


>>> val1=10  


>>> val2=None  

>>> val1  

10  

>>> val2  

>>> print val2  

None  

>>>  

 


V.Literal Collections.


Collections such as tuples, lists and Dictionary are used in Python.


 


List:


List contain items of different data types. Lists are mutable i.e., modifiable.


The values stored in List are separated by commas(,) and enclosed within a square brackets([]). We can store different type of data in a List.


Value stored in a List can be retrieved using the slice operator([] and [:]).


The plus sign (+) is the list concatenation and asterisk(*) is the repetition operator.


 


Eg:


>>> list=['aman',678,20.4,'saurav']  


>>> list1=[456,'rahul']  

>>> list  

['aman', 678, 20.4, 'saurav']  

>>> list[1:3]  

[678, 20.4]  

>>> list+list1  

['aman', 678, 20.4, 'saurav', 456, 'rahul']  

>>> list1*2  

[456, 'rahul', 456, 'rahul']  

>>>  

 


Python tutorial part 12 :- Identifiers

Identifiers


 


Identifiers are the names given to the fundamental building blocks in a program.

 

These can be variables ,class ,object ,functions , lists , dictionaries etc.There are certain rules defined for naming i.e., Identifiers.

 

1.    An identifier is a long sequence of characters and numbers.

2.    No special character except underscore ( _ ) can be used as an identifier.

3.    Keyword should not be used as an identifier name.

4.    Python is case sensitive. So using case is significant.

5.    .First character of an identifier can be character, underscore ( _ ) but not digit.

 

Python tutorial part 11 :- python keywords

Python Keywords


 


Python Keywords are special reserved words which convey a special meaning to the compiler/interpreter. Each keyword have a special meaning and a specific operation. These keywords can't be used as variable. Following is the List of Python Keywords.

 

True


False


None


and


as


asset


def


class


continue


break


else


finally


elif


del


except


global


for


if


from


import


raise


try


or


return


pass


nonlocal


in


not


is


lambda


 


Python tutorial part 10 :- python variables

Python Variables


 


Variable is a name which is used to refer memory location. Variable also known as identifier and used to hold value.In Python, we don't need to specify the type of variable because Python is a type infer language and smart enough to get variable type.

 

Variable names can be a group of both letters and digits, but they have to begin with a letter or an underscore.It is recomended to use lowercase letters for variable name. Rahul and rahul both are two different variables.

 

Note - Variable name should not be a keyword.


 

Declaring Variable and Assigning Values

Python does not bound us to declare variable before using in the application. It allows us to create variable at required time.

 

We don't need to declare explicitly variable in Python. When we assign any value to the variable that variable is declared automatically.

 

The equal (=) operator is used to assign value to a variable.

 

Eg:



 

Output:

>>>   

10  

ravi  

20000.67  

>>>  

 

Multiple Assignment

Python allows us to assign a value to multiple variables in a single statement which is also known as multiple assignment.We can apply multiple assignments in two ways either by assigning a single value to multiple variables or assigning multiple values to multiple variables. Lets see given examples.

 

1. Assigning single value to multiple variables

 

Eg:

x=y=z=50  


print x  

print y  

print z  

Output:

>>>   

50  

50  

50  

>>>  

 

2.Assigning multiple values to multiple variables:

Eg:

a,b,c=5,10,15  


print a  

print b  

print c  

Output:

>>>   

5  

10  

15  

>>>  

 

The values will be assigned in the order in which variables appears.

 

Basic Fundamentals:

This section contains the basic fundamentals of Python like :

i)Tokens and their types.

ii) Comments

 

a)Tokens:

Tokens can be defined as a punctuator mark, reserved words and each individual word in a statement.


Token is the smallest unit inside the given program.


 

There are following tokens in Python:

Keywords.


Identifiers.


Literals.


Operators.


 

Tuples:

Tuple is another form of collection where different type of data can be stored.


It is similar to list where data is separated by commas. Only the difference is that list uses square bracket and tuple uses parenthesis.


Tuples are enclosed in parenthesis and cannot be changed.


 

Eg:

>>> tuple=('rahul',100,60.4,'deepak')  


>>> tuple1=('sanjay',10)  

>>> tuple  

('rahul', 100, 60.4, 'deepak')  

>>> tuple[2:]  

(60.4, 'deepak')  

>>> tuple1[0]  

'sanjay'  

>>> tuple+tuple1  

('rahul', 100, 60.4, 'deepak''sanjay', 10)  

>>>  

 

Dictionary:

Dictionary is a collection which works on a key-value pair.


It works like an associated array where no two keys can be same.


Dictionaries are enclosed by curly braces ({}) and values can be retrieved by square bracket([]).


 

Eg:

>>> dictionary={'name':'charlie','id':100,'dept':'it'}  


>>> dictionary  

{'dept''it''name''charlie''id': 100}  

>>> dictionary.keys()  

['dept''name''id']  

>>> dictionary.values()  

['it''charlie', 100]  

>>>  

 

Python tutorial part 9 : Hello world

Python Example


 

Python is easy to learn and code and can be execute with python interpreter. We can also use Python interactive shell to test python code immediately. A simple hello world example is given below. Write below code in a file and save with .py extension. Python source file has .pyextension.

 

hello.py

1.    print("hello world by python!")  

Execute this example by using following command.

1.    Python3 hello.py  

After executing, it produces the following output to the screen.

Output

hello world by python!

 

Python Example using Interactive Shell

Python interactive shell is used to test the code immediately and does not require to write and save code in file.

Python code is simple and easy to run. Here is a simple Python code that will print "Welcome to Python".

A simple python example is given below.

 

1.    >>> a="Welcome To Python"  


2.    >>> print a  

3.    Welcome To Python  

4.    >>>    

 

Explanation:

Here we are using IDLE to write the Python code. Detail explanation to run code is given in Execute Python section.


A variable is defined named "a" which holds "Welcome To Python".


"print" statement is used to print the content. Therefore "print a" statement will print the content of the variable. Therefore, the output "Welcome To Python" is produced.


 

Python 3.4 Example

In python 3.4 version, you need to add parenthesis () in a string code to print it.

 

1.    >>> a=("Welcome To Python Example")  


2.    >>> print a  

3.    Welcome To Python Example  

4.    >>>    

 

Python tutorial part 8 : setting python path

SETTING PATH IN PYTHON


 


Before starting working with Python, a specific path is to set.

 

Your Python program and executable code can reside in any directory of your system, therefore Operating System provides a specific search path that index the directories Operating System should search for executable code.


The Path is set in the Environment Variable of My Computer properties:


To set path follow the steps:


 

Right click on My Computer ->Properties ->Advanced System setting ->Environment Variable ->New

 

In Variable name write path and in Variable value copy path up to C://Python(i.e., path where Python is installed). Click Ok ->Ok.

 

Path will be set for executing Python programs.

1. Right click on My Computer and click on properties.

2. Click on Advanced System settings

3. Click on Environment Variable tab.

4. Click on new tab of user variables.

5. Write path in variable name.

6. Copy the path of Python folder.

7. Paste path of Python in variable value.

8. Click on Ok button:

9. Click on Ok button:

 

 

Python tutorial part 7 : python installation

HOW TO INSTALL PYTHON


 

To start with Python, first make sure that the Python is installed on local computer.

 

To install Python, visit the official site and download Python from the download section.

 

To install Python on Ubuntu operating system, visit our installation section where we have provided detailed installation process.

 

For Windows operating system, the installation process is given below.

 

1. To install Python, firstly download the Python distribution from www.python.org/download.


 

2. After downloading the Python distribution, double click on the downloaded software to execute it. Follow the following installtion steps.

   

Click the Finish button and Python will be installed on your system.

 

Python tutorial part 6 : applications area

Python Applications Area


 


Python is known for its general purpose nature that makes it applicable in almost each domain of software development. Python as a whole can be used in any sphere of development.

 

Here, we are specifing applications areas where python can be applied.

 

1) Web Applications

We can use Python to develop web applications. It provides libraries to handle internet protocols such as HTML and XML, JSON, Email processing, request, beautifulSoup, Feedparser etc. It also provides Frameworks such as Django, Pyramid, Flask etc to design and delelop web based applications. Some important developments are: PythonWikiEngines, Pocoo, PythonBlogSoftware etc.

 

2) Desktop GUI Applications

Python provides Tk GUI library to develop user interface in python based application. Some other useful toolkits wxWidgets, Kivy, pyqt that are useable on several platforms. The Kivy is popular for writing multitouch applications.

 

3) Software Development

Python is helpful for software development process. It works as a support language and can be used for build control and management, testing etc.

 

4) Scientific and Numeric

Python is popular and widely used in scientific and numeric computing. Some useful library and package are SciPy, Pandas, IPython etc. SciPy is group of packages of engineering, science and mathematics.

 

5) Business Applications

Python is used to build Bussiness applications like ERP and e-commerce systems. Tryton is a high level application platform.

 

6) Console Based Application

We can use Python to develop console based applications. For example: IPython.

 

7) Audio or Video based Applications

Python is awesome to perform multiple tasks and can be used to develop multimedia applications. Some of real applications are: TimPlayer, cplay etc.

 

8) 3D CAD Applications

To create CAD application Fandango is a real application which provides full features of CAD.

 

9) Enterprise Applications

Python can be used to create applications which can be used within an Enterprise or an Organization. Some real time applications are: OpenErp, Tryton, Picalo etc.

 

10) Applications for Images

Using Python several application can be developed for image. Applications developed are: VPython, Gogh, imgSeek etc.

 

There are several such applications which can be developed using Python

 

Python tutorial part 5 : python version

Python Version


 

Python programming language is being updated regularly with new features and supports.There are lots of updations in python versions, started from 1994 to current release.

A list of python versions with its released date is given below.

 

Python Version


Python 1.0

January 1994

Python 1.5

December 31, 1997

Python 1.6

September 5, 2000

Python 2.0

October 16, 2000

Python 2.1

April 17, 2001

Python 2.2

December 21, 2001

Python 2.3

July 29, 2003

Python 2.4

November 30, 2004

Python 2.5

September 19, 2006

Python 2.6

October 1, 2008

Python 2.7

July 3, 2010

Python 3.0

December 3, 2008

Python 3.1

June 27, 2009

Python 3.2

February 20, 2011

Python 3.3

September 29, 2012

Python 3.4

March 16, 2014

Python 3.5

September 13, 2015

Python 3.6

December 23, 2016

Python 3.6.4

December 19, 2017

 


Python tutorial part 4 : python history

Python History


 

Python laid its foundation in the late 1980s.


The implementation of Python was started in the December 1989 by Guido Van Rossum at CWI in Netherland.


In February 1991, van Rossum published the code (labeled version 0.9.0) to alt.sources.


In 1994, Python 1.0 was released with new features like: lambda, map, filter, and reduce.


Python 2.0 added new features like: list comprehensions, garbage collection system.


On December 3, 2008, Python 3.0 (also called "Py3K") was released. It was designed to rectify fundamental flaw of the language.


ABC programming language is said to be the predecessor of Python language which was capable of Exception Handling and interfacing with Amoeba Operating System.


Python is influenced by following programming languages:


ABC language.


Modula-3


 

Python tutorial part 3 : python features

Python Features


 

Python provides lots of features that are listed below.

 

1) Easy to Learn and Use

Python is easy to learn and use. It is developer-friendly and high level programming language.

 

2) Expressive Language

Python language is more expressive means that it is more understandable and readable.

 

3) Interpreted Language

Python is an interpreted language i.e. interpreter executes the code line by line at a time. This makes debugging easy and thus suitable for beginners.

 

4) Cross-platform Language

Python can run equally on different platforms such as Windows, Linux, Unix and Macintosh etc. So, we can say that Python is a portable language.

 

5) Free and Open Source

Python language is freely available at offical web address (https://www.python.org/).The source-code is also available. Therefore it is open source.

 

6) Object-Oriented Language

Python supports object oriented language and concepts of classes and objects come into existence.

 

7) Extensible

It implies that other languages such as C/C++ can be used to compile the code and thus it can be used further in our python code.

 

8) Large Standard Library

Python has a large and broad library and provide rich set of module and functions for rapid application development.

 

9) GUI Programming Support

Graphical user interfaces can be developed using Python.

 

10) Integrated

It can be easily integrated with languages like C, C++, JAVA etc.

 

Python tutorial part 2 : python introduction

Python is a general purpose, dynamic, high level and interpreted programming language. It supports Object Oriented programming approach to develop applications. It is simple and easy to learn and provides lots of high-level data structures.

 

Python is easy to learn yet powerful and versatile scripting language which makes it attractive for Application Development.

 

Python's syntax and dynamic typing with its interpreted nature, makes it an ideal language for scripting and rapid application development.

 

Python supports multiple programming pattern, including object oriented, imperative and functional or procedural programming styles.

 

Python is not intended to work on special area such as web programming. That is why it is known as multipurpose because it can be used with web, enterprise, 3D CAD etc.

 

We don't need to use data types to declare variable because it is dynamically typed so we can write a=10 to assign an integer value in an integer variable.

 

Python makes the development and debugging fast because there is no compilation step included in python development and edit-test-debug cycle is very fast.

 

Python tutorial part 1 : Introduction of python

Python tutorial provides basic and advanced concepts of Python. Our Python tutorial is designed for beginners and professionals.Python is a simple, easy to learn, powerful, high level and object-oriented programming language.

 

Python is an interpreted scripting language also. Guido Van Rossum is known as the founder of python programming.

 

Our Python tutorial includes all topics of Python Programming such as installation, control statements, Strings, Lists, Tuples, Dictionary, Modules, Exceptions, Date and Time, File I/O, Programs, etc. There are also given Python interview questions to help you better understand the Python Programming.


Prerequisite

Before learning Python, you must have the basic knowledge of programming concepts.

 

Audience

Our Python tutorial is designed to help beginners and professionals.

 

Problem

We assure that you will not find any problem in this Python tutorial. But if there is any mistake, please post the problem in contact on comment box ЁЯСИЁЯСИ

Quick Tech