You are on page 1of 33

History of Python

 Python
is not new language; in fact it was released by its designer, Guido Van Rossum, in
February 1991​ while working for CWI also known as Stichting Mathematisch Centrum.

Many of Python's features originated from an interpreted language called ABC. Rossum
wanted to correct some of ABC's problems and keep some of its features.​ At the time he was
working on the Amoeba distributed operating system group and was looking for a scripting
language with a syntax like ABC but with the access to the Amoeba system calls, so he decided
to create a language that was generally extensible.

Since he had some experience with using Modula-2+, he decided to talk with the designers of
Modula-3. Modula-3 is the origin of the syntax and semantics used for exceptions, and some
other Python features. ​In 1989, during the Christmas holidays, he decided to give it a try and
design a language which he later called Python.

Just in case you're wondering how the language got its name, well it's not from those
dangerous reptiles. Python actually got is name from a BBC comedy series from the
seventies "Monty Python's Flying Circus". The designer needed a name that was short,
unique, and slightly mysterious. Since he was a fan of the show he thought this name was
great.

Python 2.0 was released on 16 October 2000​ with many major new features, including a
cycle-detecting garbage collector and support for Unicode.

Python 3.0 was released on 3 December 2008.​ It was a major revision of the language that is
not completely backward-compatible. Many of its major features were backported to Python
2.6.x and 2.7.x version series

Introduction to Python

​ ython​ is a general-purpose interpreted, interactive, object-oriented, and high-level


P
programming language.

​It was created by Guido van Rossum during 1985- 1990.

​ ython is a high-level general purpose programming language that offers multiple paradigms
P
like object-orientation, and structural and functional programming for software development.

​ Python is a cross-platform programming language, which means that it can run on multiple
platforms like Windows, macOS, Linux, and has even been ported to the Java and .NET virtual
machines. It is free and open-source.
​ ​ Many large companies use the Python programming language include NASA, Google,
YouTube, BitTorrent, etc.

​ ​ Python programming is widely used in Artificial Intelligence, Natural Language Generation,


Neural Networks and other advanced fields of Computer Science.

What can Python do?

● Python can be used on a server to create web applications.


● Python can be used alongside software to create workflows.
● Python can connect to database systems. It can also read and modify files.
● Python can be used to handle big data and perform complex mathematics.
● Python can be used for rapid prototyping, or for production-ready software development.

Why Python?

● Python works on different platforms (Windows, Mac, Linux, Raspberry Pi, etc).
● Python has a simple syntax similar to the English language.
● Python has syntax that allows developers to write programs with fewer lines than some
other programming languages.
● Python runs on an interpreter system, meaning that code can be executed as soon as it is
written. This means that prototyping can be very quick.
● Python can be treated in a procedural way, an object-orientated way or a functional way.

As we know python is ​a general-purpose ​interpreted​, interactive, object-oriented, and high-level


programming language.

​So what do you mean by interpreted

We generally write a computer program using a high-level language. A high-level language is


one that is understandable by us, humans. This is called source code.

However, a computer does not understand high-level language. It only understands the program
written in 0's and 1's in binary, called the machine code.

To convert source code into machine code, we use either a compiler or an interpreter.

Both compilers and interpreters are used to convert a program written in a high-level language
into machine code understood by computers. However, there are differences between how an
interpreter and a compiler works.

Interpreter​:

​Translates program one statement at a time.


I​ nterpreters usually take less amount of time to analyze the source code. However, the overall
execution time is comparatively slower than compilers.

​No intermediate object code is generated, hence are memory efficient.

​Programming languages like JavaScript, Python, Ruby use interpreters.

Compiler​:

​Scans the entire program and translates it as a whole into machine code.

​ ompilers usually take a large amount of time to analyze the source code. However, the overall
C
execution time is comparatively faster than interpreters

​ enerates intermediate object code which further requires linking, hence requires more
G
memory.

​Programming languages like C, C++, Java use compilers.

Interpreter Compiler

Scans the entire program and translates it as a


Translates program one statement at a time.
whole into machine code.

Interpreters usually take less amount of time to Compilers usually take a large amount of time
analyze the source code. However, the overall to analyze the source code. However, the
execution time is comparatively slower than overall execution time is comparatively faster
compilers. than interpreters.

Generates intermediate object code which


No intermediate object code is generated, hence
further requires linking, hence requires more
are memory efficient.
memory.

It keeps translating program until first error is A compiler generates the error message only
found, so debugging becomes much easier with after it scans complete program so debugging is
interpreter. comparatively harder.

Programming languages like JavaScript, Programming languages like C, C++, Java use
Python, Ruby use interpreters. compilers.

Features of Python

The Python programming language is one of the richest languages. In this Python tutorial, we
will discuss several features of Python:

● Easy-to-learn​ − Python has few keywords, simple structure, and a clearly defined
syntax. This allows the student to pick up the language quickly.
● Easy-to-read​ − Python code is more clearly defined and visible to the eyes.
● Easy-to-maintain​ − Python's source code is fairly easy-to-maintain.
● Interactive Mode​ − Python has support for an interactive mode which allows interactive
testing and debugging of snippets of code.
● Free and Open Source-​The language and its source code are available to the public for
free; there is no need to buy a costly license.
● Portable-​Since it is open-source, you can run Python on Windows, Mac, Linux or any
other platform. Your programs will work without needing to the changed for every
machine.
● Extendable​ − You can add low-level modules to the Python interpreter. These modules
enable programmers to add to or customize their tools to be more efficient.
● Databases​ − Python provides interfaces to all major commercial databases.
● GUI Programming-​You can use it to develop a GUI (Graphical User Interface). One
way to do this is through ​Tkinter​.
● Large Library-​Python provides you with a large standard library. You can use it to
implement a variety of functions without needing to reinvent the wheel every time. Just
pick the code you need and continue. This lets you focus on other important tasks.
Python's bulk of the library is very portable and cross-platform compatible on UNIX,
Windows, and Macintosh.

Python Applications

Python is easy to pick-up even if you come from a non-programming background. You can look
at the code and tell what’s going on. ​Talking of Python applications​, some of the cool things
that you can do with Python are –

● Build a website
● Develop a game
● Perform Computer Vision (Facilities like face-detection and color-detection)
● Implement Machine Learning (Give a computer the ability to learn)
● Enable Robotics
● Perform Web Scraping (Harvest data from websites)
● Perform Data Analysis
● Automate a web browser
● Perform Scripting
● Perform Scientific Computing
● Build Artificial Intelligence

Python​ isn’t limited to these applications. If you’ve ever used services from brands like
YouTube, Dropbox, and Netflix, then you’ve been a consumer of Python. The
search-engine ​Google​ also made great use of the language in its initial stages.

How to Install Python on Windows

Installing Python
Step 1)​ To download and install Python visit the official website of
Python ​https://www.python.org/downloads/​ and choose your version.

Currently we are using ​Python version 3.4.2


Step 2)​ Once the download is complete, run the exe for install Python. Now click on Install
Now.
Step 3)​ You can see Python installing at this point.
Step 4)​ When it finishes, you can see a screen that says the Setup was successful. Now click on
"Close".

(How to run program in python this is just for your understanding)

When Python is installed, a program called ​IDLE​ is also installed along with it. It provides
graphical user interface to work with Python.

1. Open IDLE, copy the following code below and press enter.
print("Hello, Python!")

2. To create a file in IDLE, go to ​File > New Window ​(Shortcut: Ctrl+N).


Write Python code and save (Shortcut: Ctrl+S) with .py file extension like: hello_python.py or
my_first_python_program.py

print("Hello, World!")
3. Go to ​Run > Run module​ (Shortcut: F5) and you can see the output. Congratulations,
you’ve successfully run your first Python program.

As we know python is interpreted language there are two ways we can use interpreter.

In Python, there are two ​basic modes​ for running code​:


● Interactive mode
● Script mode

Interactive mode:
​ Interactive mode is a command line shell which gives immediate feedback for each statement,
while running previously fed statements in active memory.
​ As new lines are fed into the interpreter, the fed program is evaluated both in part and in
whole.
​ Interactive mode allows you to test out and see what Python will do.
​The​’>>> ’​is Python's way of telling you that you are in interactive mode.
​ In interactive mode what you type is immediately run.
​For example if you type 1+1 in. Python will respond with 2.

​ if you type same code in script mode ,you will get no output at all. In script mode an
expression all by itself has no visible effect.

Script Mode:
​ Interpreter prompt is good to run the individual statements of the code. However, we cannot
write the code every-time on the terminal.

​We need to write our code into a file which can be executed later.

​ The script mode is the mode where the scripted and finished ​.py​ files are run in the Python
interpreter.
Program runs on Interpreter :

Interactive Mode Script Mode


Interactive mode is a command line shell The script mode is the mode where the scripted
which gives immediate feedback for each and finished ​.py​ files are run in the Python
statement, while running previously fed interpreter.
statements in active memory.
In interactive mode we lose the code once the In script mode we can write our code into a file
shell prompt is closed. which can be executed later.
If you need to ​write​ a long piece If you need to ​write​ a long piece
of ​Python​ code or your ​Python script​ spans of ​Python​ code or your ​Python script​ spans
multiple files, ​interactive mode​ is not multiple files, we do it in script mode.
recommended.
The result is returned immediately after After writing your code, you can run it by
pressing the enter key. clicking "Run" then "Run Module" or simply
press F5.
In script mode, you are provided with a direct Editing is not possible in interactive mode.
way of editing your code.

DEBLIGGING​:

While writing the program, there might be chances of having mistakes, errors in the code, the
programming errors are called as bugs and the process of tracking them down is called as
debugging.
Three kinds of errors can occur in a program: ​syntax errors, runtime errors, and semantic
error​. It is useful to distinguish between them in order to track them down more quickly.
Syntax Errors
The syntax is nothing but the specified structure and rules of writing the program. If we
violate any rule or structure of code then syntax error is raised by the interpreter. If there is any
syntax error anywhere in your program, Python displays an error message.
In above example the variable ‘my no’ is written wrong as there should not be a space in the
declaration so interpreter displayed the invalid syntax message.

Runtime Errors:
The runtime error does not appear until after the program has started running, These
errors are also called exceptions because they usually indicate that something wrong has
happened. The appearances of runtime error are less as very few times this kind mistake is
happened by developer.

Semantic Errors
The sematic error is also referred as logical error. It is related to meaning of block or statement,
if there is a semantic error in your program, it will run without generating error messages, but it
will not give desired result. It will show same unexpected output or error message. Specifically,
it will do what you told it to do. To find out semantic errors can be tricky because it requires you
to work backward by looking at the output of the program and trying to figure out where is
something gone wrong.

EXPERIMENTAL DEBUGGING​:
​The one who is able to debug, is a good developer. One of the most important required skills in
programmer is debugging.
​Although it can be frustrating, debugging is one of the most intellectually rich, challenging,
and interesting parts of programming.
​Debugging is an experimental science. Once you have an idea about what is going wrong, you
modify your program and try again, If your hypothesis (guess) was correct, then you can predict
the result of the modification, and you take a step closer to a working program.
​If your hypothesis was wrong, you have to come up with a new one, In experimental
debugging programmer looks back his or her code carefully to find out the loophole or to find
out chances to make more enhancements in program.
​Here programmer has to give steady attention to code and its output, There might be situation
where multiple times developer has to reframe the code to get the desired output.
​In simple words experimental debugging is nothing but trial and error basis work or research
and development work.
FORMAL AND NATURAL LANGUAGES
​Natural languages​ are the languages people speak, such as Hindi, English, Marathi, Spanish,
and French.
​They were not designed by people; they evolved timely and naturally.

​Formal languages​ are languages that are designed by people for specific applications.
​For example, the notation that mathematicians use is a formal language that is particularly
good at denoting relationships among numbers and symbols.
​Chemists use a formal language to represent the chemical structure of molecules. And most
importantly: Programming languages are formal languages that have been designed to express
computations.
​The Formal languages have a tendency to have strict rules about syntax. For example, 5 + 5 =
10 is a syntactically correct mathematical statement, but 5 = 512 is not
​The formal and natural languages have many similar features; still there are some significant
differences as given below:
● Ambiguity (not clear): Natural languages are full of ambiguity, which people deal with
by using contextual clues and other information. Formal languages are designed to be
nearly or completely unambiguous; more clearly stated which means that any statement
has exactly one meaning, regardless of context.
● Redundancy (inessentiality): In order to make up for ambiguity and reduce
misunderstandings, natural languages employ lots of redundancy. As a result, they are
often verbose, Formal languages are less redundant and more concise.
● Literalness: Natural languages are full of phrases and representations. Formal languages
mean exactly what they say. It is hard for people to bear with formal languages who grow
up speaking a natural language, In some ways, the difference between formal and natural
language is like the difference between poetry and theory.

Programs​ :The meaning of a computer program Is unambiguous and literal, and can understood
entirely by analysis or the tokens and structure

THE DIFFERENCE BETWEEN BRACKETS, PARENTHESES AND BRACES.

• ​Brackets []
​Generally brackets are used to Index into an array.
​It also used to define mutable data types such as lists, list comprehensions and for indexing
/lookup/slicing.
• ​Parenthesis ( )
​Parentheses are used for two purposes: to control the order of operations in an expression, and
to supply parameters to a constructor or method.
​In python it is used to define tuples, order of operations, generator expressions, function calls
and other syntax.
• ​Braces {}
​The braces generally are used to group statements and declarations.
​The contents of class or interface are enclosed in braces.
​Braces are used to group the statements in if statement, a loop, or other control structures.
It means braces used to specify the scope of logical block of statements.
​In python the braces are also used to create dictionaries or sets.

Values and types:

​A value is one of the most basic things in any program works with.
​A ​value​ is one of the fundamental things ​ ​ like a letter or a number ​ ​ that a program
manipulates.
​A value may be characters i.e. ‘Hello, World!’ or a number like 1,2.2 ,3.5 etc
​These values belong to different ​types​: 2 is an integer, and ​'Hello, World!'​ is a ​string​, so-called
because it contains a "string" of letters.

If you are not sure what type a value has, the interpreter can tell you.

>>> type(​'Hello, World!'​)


<type ​'str'​>
>>> type(17)
<type ​'int'​>
>>> type(3.2)
<type ​'float'​>

Not surprisingly, strings belong to the type str and integers belong to the type int and numbers
with a decimal point belong to a type called float, because these numbers are represented in a
format called ​floating-point​.

Variables:
​Variables are nothing but reserved memory locations to store values. This means that when you
create a variable you reserve some space in memory.
​Based on the data type of a variable, the interpreter allocates memory and decides what can be
stored in the reserved memory.
​Therefore, by assigning different data types to variables, you can store integers, decimals or
characters in these variables.
​In Python we don't need to declare a variable before using it. We simply assign a value to a
variable and it will exist.
​We don't even have to declare the type of the variable.
​This is handled internally according to the type of value we assign to the variable.
>>>s=2
>>>t=3.14
>>>st="abc"
Variable Names and Keywords
​Naming variables is one of the most difficult tasks In computer programming.
​When you are naming variables, think hard about the names.
​Try your best to make sure that the name you assign your variable is accurately descriptive and
understandable to another reader.
​Sometimes that other reader is yourself when you revisit a program that you wrote months or
even years earlier.
​Programmers generally choose names for their variables that are meaningful for the document
what the variable is used for.
The rules for naming the variables in​ ​Python
• Variables names must start with a letter or an underscore, such as
Ex.
sname
sname_
• The remainder of your variable name may consist of underscores.
Ex.
y123
v2y
yii_g
• ​Names are case sensitive​, sname, SNAME, and sName are each a different variable.

​ ariable names can be arbitrarily long. They can contain both letters and numbers, but they
V
have to begin with a letter.
​It is legal to use uppercase letters, but it is a good idea to begin variable names with a
lowercase letter.
Keywords​ : are predefined; reserved words used in programming that have special meaning. If
the occurrence of keyword is found to the interpreter in the statement then the predefined
operation related to that keyword Is executed first. The Keywords are part of the syntax and they
cannot be used as an identifier (variable name).
For example
>>> if = 45
SyntaxError invalid syntax Because If is one of Python's keywords.

Statements

A statement is an instruction that the Python interpreter can execute. We have seen two kinds of
statements: print and assignment.

When you type a statement on the command line, Python executes it and displays the result, if
there is one. The result of a print statement is a value. Assignment statements don't produce a
result.

A script usually contains a sequence of statements. If there is more than one statement, the
results appear one at a time as the statements execute.
For example, the script

print 1
x=2
print x

produces the output

1
2

Note: the assignment statement produces no output.

Python Data Types

Data types are the classification or categorization of data items.


It represents the kind of value that tells what operations can be performed on a particular data.
Since everything is an object in Python programming, data types are actually classes and
variables are instance (object) of these classes.
Following are the standard or built-in data type of Python:
● Numeric
● Sequence Type
● Boolean
● Set
● Dictionary

Python has the following standard or built-in data types:

Numeric
​A numeric value is any representation of data which has a numeric value. Python identifies
three types of numbers:
● Integer:​ Positive or negative whole numbers (without a fractional part)
● Float:​ Any real number with a floating point representation in which a fractional
component is denoted by a decimal symbol or scientific notation
● Complex number:​ A number with a real and imaginary component represented as x+yj.
x and y are floats and j is -1(square root of -1 called an imaginary number)

Boolean
​Data with one of two built-in values ​True​ or ​False​. Notice that 'T' and 'F' are
capital. ​true​ and ​false​ are not valid booleans and Python will throw an error for them.

Sequence Type

​ sequence is an ordered collection of similar or different data types. Python has the following
A
built-in sequence data types:

● String​: A string value is a collection of one or more characters put in single, double or
triple quotes.
● List​ : A list object is an ordered collection of one or more data items, not necessarily of
the same type, put in square brackets.
● Tuple​: A Tuple object is an ordered collection of one or more data items, not necessarily
of the same type, put in parentheses.

Dictionary
​A dictionary object is an unordered collection of data in a key:value pair form. A collection of
such pairs is enclosed in curly brackets.

For example: ​{1:"Steve", 2:"Bill", 3:"Ram", 4: "Farha"}

type() function

Python has an in-built function ​type()​ to ascertain the data type of a certain value. For example,
enter ​type(1234)​ in Python shell and it will return ​<class 'int'>​, which means 1234 is an integer
value. Try and verify the data type of different values in Python shell, as shown below.
Type Conversion

​The process of converting the value of one data type (integer, string, float, etc.) to another data
type is called type conversion.
​sometimes we need to assign value of one data type to another type variable,in this situation we
need to do type casting.
​Python provides some build in conversion functions.
● int()- It converts string and floating point to integer.
>>> int('125')
125
>>> int(3.14)
3
● float –It convert string integer to floating point.
>>> float('11.77')
11.77
>>> float(3)
3.0
● str():It coverts integer, float, list, tuple, dictionary to string.
>>> str(3.14)
'3.14'
>>> str([1,2,3])
'[1, 2, 3]'
>>> str(5)
'5'
● list():It converts string, tuple, dictionary to list.
>>> list('xyz')
['x', 'y', 'z']
>>> list((1,2,3))
[1, 2, 3]
● tuple():It converts string, list to tuple.
>>> tuple('xyz')
('x', 'y', 'z')
>>> tuple([1,2,3])
(1, 2, 3)

Python Operators
The operator can be defined as a symbol which is responsible for a particular operation between
two operands. Operators are the pillars of a program on which the logic is built in a specific
programming language. Python provides a variety of operators, which are described as follows.

o Arithmetic operators
o Comparison operators
o Assignment Operators
o Logical Operators
o Bitwise Operators
o Membership Operators
o Identity Operators

Python Operators

The operator can be defined as a symbol which is responsible for a particular operation
between two operands. Operators are the pillars of a program on which the logic is built in a
specific programming language. Python provides a variety of operators, which are described
as follows.

o Arithmetic operators
o Comparison operators
o Assignment Operators
o Logical Operators
o Bitwise Operators
o Membership Operators
o Identity Operators
Arithmetic Operators

Arithmetic operators are used to perform arithmetic operations between two operands. It
includes + (addition), - (subtraction), *(multiplication), /(divide), %(reminder), //(floor
division), and exponent (**) operators.

Consider the following table for a detailed explanation of arithmetic operators.

Operator Description

+ (Addition) It is used to add two operands.


For example
>>>a = 20
>>>b = 10
>>> a+b
>>>30

- (Subtraction) It is used to subtract the second operand from the first operand. If the
first operand is less than the second operand, the value results
negative. For example
>>>a = 20
>>>b = 10
>>> a-b
>>>10

/ (divide) It returns the quotient after dividing the first operand by the second
operand. For example
>>>a = 20
>>>b = 10
>>> a/b
>>>2.0

* It is used to multiply one operand with the other. For example,


(Multiplication >>>a = 20
) >>>b = 10
>>> a*b
>>>200

% (reminder) It returns the reminder after dividing the first operand by the second
operand. For example
>>>a = 20
>>>b = 10
>>> a%b
>>>0

** (Exponent) It is an exponent operator represented as it calculates the first operand


power to the second operand.
>>>2**3
>>>8

// (Floor It gives the floor value of the quotient produced by dividing the two
division) operands.
>>>7//2
>>>3

Comparison operator
Comparison operators are used to comparing the value of the two operands and returns Boolean
true or false accordingly. The comparison operators are described in the following table.

Operator Description

== If the value of two operands is equal, then the condition becomes true.

!= If the value of two operands is not equal, then the condition becomes true.

<= If the first operand is less than or equal to the second operand, then the condition
becomes true.

>= If the first operand is greater than or equal to the second operand, then the
condition becomes true.

> If the first operand is greater than the second operand, then the condition
becomes true.

< If the first operand is less than the second operand, then the condition becomes
true.

Example
>>> a=10
>>> b=20
>>> a==b
False
>>> a>b
False
>>> a<b
True
>>> a>=b
False
>>> a<=b
True

Bitwise Operators
The bitwise operators perform bit by bit operation on the values of the two operands.

Operator Description

& (binary If both the bits at the same place in two operands are 1, then 1 is copied to the
and) result. Otherwise, 0 is copied.

| (binary The resulting bit will be 0 if both the bits are zero; otherwise, the resulting bit
or) will be 1.

^ (binary The resulting bit will be 1 if both the bits are different; otherwise, the resulting
xor) bit will be 0.

~ It calculates the negation of each bit of the operand, i.e., if the bit is 0, the
(negation) resulting bit will be 1 and vice versa.

>>> s=2 #0010


>>> t=4 #0100
>>> s&t
0
>>> s^t
6
>>> s|t
6
>>> ~s
-3
Logical Operators
The logical operators are used primarily in the expression evaluation to make a decision. Python
supports the following logical operators.

Operator Description

and If both the expression are true, then the condition will be true.

If a and b are the two expressions,

a → true,

b → true

a and b → true.

or If one of the expressions is true, then the condition will be true.

If a and b are the two expressions,

a → true,

b → false

=> a or b → true.

not If an expression ​a​ is true, then not (a) will be false and vice versa.

Membership Operators
Python membership operators are used to check the membership of value inside a Python data
structure. If the value is present in the data structure, then the resulting value is true otherwise it
returns false.

Operator Description

in It is evaluated to be true if the first operand is found in the second operand (list,
tuple, or dictionary).
not in It is evaluated to be true if the first operand is not found in the second operand
(list, tuple, or dictionary).

>>> s=[1,2,3,4]
>>> 4 in s
True
>>> s not in s
True

Identity Operators
The identity operators are used to decide whether an element certain class or type.

Operator Description

is It is evaluated to be true if the reference present at both sides point to the same
object.

is not It is evaluated to be true if the reference present at both sides do not point to the
same object.

Precedence of Python Operators:

​The combination of values, variables, operators, and function calls is termed as an expression.
The Python interpreter can evaluate a valid expression.

For example:

>>> 5 - 7
-2
Here 5 - 7 is an expression. There can be more than one operator in an expression.

​To evaluate these types of expressions there is a rule of precedence in Python. It guides the
order in which these operations are carried out.​
​Operator precedence​ determines the grouping of terms in an expression and decides how an
expression is evaluated.
​Certain ​operators​ have higher ​precedence​ than others; for example, the
multiplication ​operator​ has a higher ​precedence​ than the ​subtraction​ operator​.
For Example:
# Multiplication has higher precedence
# than subtraction
>>> 10 - 4 * 2
2
But we can change this order using parentheses () as it has higher precedence than multiplication.

# Parentheses () has higher precedence


>>> (10 - 4) * 2
12
​The operator precedence in Python is listed in the following table. It is in descending order
(upper group has higher precedence than the lower ones).

Operators Meaning

() Parentheses

** Exponent

+x​, ​-x​, ​~x Unary plus, Unary minus, Bitwise NOT

Multiplication, Division, Floor division,


*​, ​/​, ​//​, ​%
Modulus

+​, ​- Addition, Subtraction

<<​, ​>> Bitwise shift operators

& Bitwise AND

^ Bitwise XOR

| Bitwise OR

==​, ​!=​, ​>​, ​>=​, ​<​, ​<=​, ​is​, ​is not​, ​in​, ​not in Comparisons, Identity, Membership operators

not Logical NOT

and Logical AND

or Logical OR
Python input():
​Developers often have a need to interact with users, either to get data or to provide some sort of
result.
​Most programs today use a dialog box as a way of asking the user to provide some type of
input. ​ ​Python provides us with inbuilt functions to read the input from the keyboard.
​The input() method reads a line from input, converts into a string and returns it.

The syntax of input() method is:


input([prompt])

input() Parameters

The input() method takes a single optional argument:


• prompt (Optional) - a string that is written to standard output (usually screen) without
trailing newline

Return value from input()


The input() method reads a line from input (usually user), converts the line into a string by
removing the trailing newline, and returns it.
Example
Use the prompt parameter to write a message before the input:
x = input('Enter your name:')
print('Hello, ' + x)

Comments in Python:

​ he comments are nothing but self-describing text that helps programmer to get the
T
information about code block.
​With comments, you can remind yourself what a specific portion of the code does and make
your code more accessible to other developers.
​Since comments are written inside a file that is going to be executed, Python needs some way
to determine that the text you write is a comment, and not a command that needs to be executed.
​You can mark a text as a comment in TWO ways
1. ​The hash-mark sign​ (#) - Text that appears after the # sign will be defined a, a comment and
will not be executed.
Ex.
# This is a comment.
print ("Hello world!')
# This is another comment.

2. ​The three double quotes​ (""") - If you need to comment out a longer multiline text, you can
use three double quotes. Python will treat all text inside the three quotes as a comment
Ex.
"""
This is our first program.
It prints the text Hello world!
"""
print (Hello world!')

Python Conditional statements

​There are situations in real life when we need to make some decisions and based on these
decisions, we decide what should we do next.
​ Similarly situations arises in programming also where we need to make some decisions and
based on these decisions we will execute the next block of code.

Decision making statements in programming languages decides the direction of flow of program
execution. Decision making statements available in python are:

if statement
if..else statements
nested if statements
if-elif ladder

if statement :

​if statement is the most simple decision making statement.


​It is used to decide whether a certain statement or block of statements will be executed or not
i.e if a certain condition is true then a block of statement is executed otherwise not.

Syntax:

if condition:
# Statements to execute if
# condition is true

Here, condition after evaluation will be either true or false.


​if statement accepts boolean values – if the value is true then it will execute the block of
statements below it otherwise not. We can use condition with bracket ‘(‘ ‘)’ also.

Note: ​As we know, python uses indentation to identify a block. So the block under an if
statement will be identified as shown in the below example:

if condition:
statement1
statement2

# Here if the condition is true, if block


# will consider only statement1 to be inside
# its block.

Example:

i =​ ​10
if​ ​(i > 15):
print​ ​("10 is less than 15")
print​ ​("I am Not in if")

Output:

I am Not in if
As the condition present in the if statement is false. So, the block below the if statement is not
executed.

if- else:

​ he if statement alone tells us that if a condition is true it will execute a block of statements
T
and if the condition is false it won’t. But what if we want to do something else if the condition is
false. ​ ​Here comes the else statement. We can use the else statement with if statement to
execute a block of code when the condition is false.

Syntax:

if (condition):
# Executes this block if
# condition is true
else:
# Executes this block if
# condition is false

Example:
n = int(input("Enter number"))
if (n%2==0):
print (n," is even")
print ("i'm in if Block")
else:
print (n,"i is odd")
print ("i'm in else Block")
print ("i'm not in if and not in else Block")

Output
Enter number 6
6 is even
i'm in if Block
i'm not in if and not in else Block

nested-if (if within if):

A nested if is an if statement that is the target of another if statement. Nested if statements means
an if statement inside another if statement. Yes, Python allows us to nest if statements within if
statements. i.e, we can place an if statement inside another if statement.

Syntax:

if (condition1):
# Executes when condition1 is true
if (condition2):
# Executes when condition2 is true
# if Block is end here
# if Block is end here

Example:
year = int(input("Enter a year: "))
if (year % 4) == 0:
if (year % 100) == 0:
if (year % 400) == 0:
print(year,"is a leap year")
else:
print(year,"is not a leap year")
else:
print(year,"is a leap year")
else:
print(year,"is not a leap year")

Output:
Enter a year: 2020
2020 is a leap year

if-elif-else ladder:

​Here, a user can decide among multiple options.


​The if statements are executed from the top down.
​ As soon as one of the conditions controlling the if is true, the statement associated with that if
is executed, and the rest of the ladder is bypassed.
​ If none of the conditions is true, then the final else statement will be executed.
Syntax:-

if (condition):
statement
elif (condition):
statement
else:
statement

Example:
num1 = int(input("Enter the number"))
num2 = int(input("Enter the number"))
num3 = int(input("Enter the number"))
if(num1>num2 and num1>num3):
print(num1,'is greater')
elif(num2>num1 and num2>num3):
print(num2,'is greater')
else:
print(num3,'is greater')

Python While Loops:

​In Python, While Loops is used to execute a block of statements repeatedly until a given
condition is satisfied.
​When the condition becomes false, the line immediately after the loop in the program is
executed.
​While loop falls under the category of indefinite iteration. Indefinite iteration means that the
number of times the loop is executed isn’t specified explicitly in advance.

Syntax:
while expression:
statement(s)

Control statements

​Using loops in Python automates and repeats the tasks in an efficient manner.
​But sometimes, there may arise a condition where you want to exit the loop completely, skip
an iteration or ignore that condition.
​These can be done by loop control statements. Loop control statements change execution from
its normal sequence.
​When execution leaves a scope, all automatic objects that were created in that scope are
destroyed.
​ Python supports the following control statements.

● Continue statement
● Break statement
● Pass statement

Break statement
Break statement in Python is used to bring the control out of the loop when some external
condition is triggered. Break statement is put inside the loop body (generally after if condition).

Break-statement-python

Syntax:
Break

Example:
# Python program to
# demonstrate break statement

s = 'welcometopython'
# Using for loop
for letter in s:

print(letter)
# break the loop as soon it sees 't'
if letter == 't':
break

print("Out of for loop")


print()

Output:
welcomet
Out of for loop

In the above example, the for loops is iterating the string ‘welcometopython’and as soon as they
encounter the character ‘t’, the if condition becomes true and the flow of execution is brought out
of the loop.

Continue statement:
​Continue is also a loop control statement just like the break statement.
​continue statement is opposite to that of break statement, instead of terminating the loop, it
forces to execute the next iteration of the loop.
​As the name suggests the continue statement forces the loop to continue or execute the next
iteration.
​When the continue statement is executed in the loop, the code inside the loop following the
continue statement will be skipped and the next iteration of the loop will begin.
Syntax:
Continue

Example:
1. Consider the situation when you need to write a program which prints the number from 1 to 10
and but not 6. It is specified that you have to do this using loop and only one loop is allowed to
use.
Here comes the usage of continue statement. What we can do here is we can run a loop from 1 to
10 and every time we have to compare the value of iterator with 6. If it is equal to 6 we will use
the continue statement to continue to next iteration without printing anything otherwise we will
print the value.

# Python program to
# demonstrate continue
# statement

# loop from 1 to 10
for i in range(1, 11):

# If i is equals to 6,continue to next without printing


if i == 6:
continue
else:
# otherwise print the value of i
print(i, end = " ")

Output:

1 2 3 4 5 7 8 9 10
The continue statement can be used with any other loop also like while in a similar way as it is
used with for loop above.

2.Printing names of students who are not in defaulters list

students={1:'megha',2:'ajay',3:'sumit',4:'sunil',5:'priyanka',6:'amruta',7:'shailesh'}
defaulter=[3,5,7]

for k,v in students.items():


if k in defaulter:
continue
else:
print(k,' ',v)

3. Printing roll numbers of students who are not in defaulters list


list=[1,2,3,4,5,6,7,8,9,10]
defaulter=[5,7,9]

for i in list:
if i in defaulter:
continue
else:
print(i)
Python pass Statement :
​The pass statement is a null statement. But the difference between pass and comment is that
comment is ignored by the interpreter whereas pass is not ignored.
​The pass statement is generally used as a placeholder i.e. when the user does not know what
code to write so user simply places pass at that line.
​Sometimes, pass is used when the user doesn’t want any code to execute. So user simply places
pass there as empty code is not allowed in loops, function definitions, class definitions, or in if
statements. So using pass statement user avoids this error.

Syntax:

pass

Example 1: Pass statement can be used in empty functions

def fun()
pass
Example 2: pass statement can also be used in empty class

class geekClass:
pass

Example 3: pass statement can be used with conditional statements

a = 10
b = 20

if(a<b):
pass
else:
print("b<a")

Example 4: another example in which the pass statement get executed when the condition is true

list =['a', 'b', 'c', 'd']

for i in list:
if(i =='a'):
pass
else:
print(i)
Output:

b
c
d

QUESTIONS

1. Write short note on Python and ways to use Python interpreter


2. Write a note on Python and its history.
3. Explain compiler and interpreter.
4. What is python and explain features of Python.
5. Explain debugging and types of error in Python.
6. Write short note en formal and natural languages.
7. Give difference between Brackets, Parentheses and Braces.
8. Write short note on values and types in Python.
9. Write short note of variables and naming in Python.
10. List and explain any 10 keywords in Python.
11. Write short note on Python Data Types.
12. How to achieve type conversion in Python?
13. Explain Operators in Python with suitable example.
14. How to achieve input in Python?
15. Explain types of comments in Python.
16. Write short note on conditional statement in python.
17. Write short note on looping statement in python.
18. Explain Control Statement in python.

You might also like