You are on page 1of 5

What is a Python interpreter? What is called Python shell?

The Python interactive console (also called the


Python interpreter or Python shell) provides
Python is an interpreted programming programmers with a quick way to execute commands
language written by Guido van Rossum. We and try out or test code without creating a file.
call it an interpreted programming Python Indentation
language because it executes every Python- Python indentation refers to adding white space
based instructions line by line. before a statement to a particular block of code. In
another word, all the statements with the same space
It can understand Python syntaxes and to the right, belong to the same code block .
tokens written in a high-level language and
can make it understandable to the
computer. Python employs code modules,
which are convertible rather than having a
single long list of code that works for
functional programming languages.
The classic implementation of Python is called
"CPython."

Create a simple calculator


# Function to add two numbers
def add(num1, num2):
return num1 + num2
Example of Python Indentation
# Function to subtract two numbers • Statement (line 1), if condition (line 2),
def subtract(num1, num2): and statement (last line) belongs to the
return num1 - num2 same block which means that after
statement 1, if condition will be executed.
# Function to multiply two numbers and suppose the if condition becomes
def multiply(num1, num2): False then the Python will jump to the last
return num1 * num2 statement for execution.

# Function to divide two numbers


• The nested if-else belongs to block 2
which means that if nested if becomes
def divide(num1, num2):
False, then Python will execute the
return num1 / num2
statements inside the else condition.
print("Please select operation -\n" \ • Statements inside nested if-else belong to
"1. Add\n" \ block 3 and only one statement will be
"2. Subtract\n" \ executed depending on the if-else
"3. Multiply\n" \ condition.
"4. Divide\n")
Atom Python
It is a universal fact that Time does not pause for
# Take input from the user anyone, and we consistently have to upgrade tools in
select = int(input("Select operations form 1, order to keep up with this immeasurably rapid era.
2, 3, 4 :")) Software development is among the chief professions
that need the most resourceful environments for the
number_1 = int(input("Enter first number: ")) programmers to write the code and efficiently produce
number_2 = int(input("Enter second number: ")) software. Thus, it comes to the requirement of an
effective Text Editor and IDE (Integrated Development
Environment). With respect to Python Programming
if select == 1:
Language
print(number_1, "+", number_2, "=",
, Atom serves best in terms of IDE
add(number_1, number_2))
. Atom is a free and Open-Source Integrated
Development Environment specially designed
elif select == 2:
print(number_1, "-", number_2, "=", for Python developers in their endeavor.
subtract(number_1,
number_2)) Python Keywords and Identifiers
Keywords are some predefined and reserved words in
elif select == 3: python that have special meanings. Keywords are
print(number_1, "*", number_2, "=", used to define the syntax of the coding. The keyword
multiply(number_1, cannot be used as an identifier, function, and variable
number_2)) name. All the keywords in python are written in lower
case except True and False. There are 33 keywords in
elif select == 4: Python 3.7 let’s go through all of them one by one.
print(number_1, "/", number_2, "=", Identifier is a name used to identify a variable, function,
divide(number_1, class, module, etc. The identifier is a combination of
number_2)) character digits and underscore. The identifier should
else: start with a character or Underscore then use a digit.
print("Invalid input") The characters are A-Z or a-z, an Underscore ( _ ) , and
digit (0-9). we should not use special characters ( #,
@, $, %, ! ) in identifiers.
1. list=['John',678,20.4,'Peter']
2. list1=[456,'Andrew']
Python Literals 3. print(list)
4. print(list + list1)
Python Literals can be defined as data that is given in a
variable or constant. Dictionary:

Python supports the following literals: o Python dictionary stores the data in the key-value
pair.
1. String literals:
o It is enclosed by curly-braces {} and each pair is
separated by the commas(,).
String literals can be formed by enclosing a text in the
quotes. We can use both single as well as double quotes to
1. dict = {'name': 'Pater', 'Age':18,'Roll_nu':101}
create a string.
2. print(dict)

1. Ex "Aman" , '12345'
Tuple:
Numeric literals:

o Python tuple is a collection of different data-type.


Numeric Literals are immutable. Numeric literals can belong It is immutable which means it cannot be
to following four different numerical types. modified after creation.
o It is enclosed by the parentheses () and each
Int(signed integers)
element is separated by the comma(,).
Long(long integers)
float(floating point)
Complex(complex) Example

Boolean literals:
1. tup = (10,20,"Dev",[2,3,4])
2. print(tup)
A Boolean literal can have any of the two values: True or
False.
Set:

Example - Boolean Literals


o Python set is the collection of the unordered
dataset.
Special literals.
o It is enclosed by the {} and each element is
separated by the comma(,).
Python contains one special literal i.e., None.

Example: - Set Literals


None is used to specify to that field that is not created. It is
also used for the end of lists in Python.
1. set = {'apple','grapes','guava','papaya'}
2. print(set)
Example - Special Literals

1. val1=10
2. val2=None
3. print(val1)
4. print(val2)
V. Literal Collections.

ython provides the four types of literal collection such as


List literals, Tuple literals, Dict literals, and Set literals.

List:

o List contains items of different data types. Lists


are mutable i.e., modifiable.
o The values stored in List are separated by
comma(,) and enclosed within square brackets([]).
We can store different types of data in a List.

Example - List literals


Python Operators
Identity Operators
The operator can be defined as a symbol which is
responsible for a particular operation between two The identity operators are used to decide whether an
operands. Operators are the pillars of a program on element certain class or type.
which the logic is built in a specific programming
language. Python provides a variety of operators, which Is :- It is evaluated to be true if the reference present at
are described as follows. both sides point to the same object.

Arithmetic Operators is not:- It is evaluated to be true if the reference present


at both sides do not point to the same object.

Arithmetic operators are used to perform arithmetic Control Statements in Python


operations between two operands. It includes + Loops are employed in Python to iterate over a section
(addition), - (subtraction), *(multiplication), of code continually. Control statements are designed
/(divide), %(reminder), //(floor division), and exponent to serve the purpose of modifying a loop's execution
from its default behaviour. Based on a condition,
(**) operators.
control statements are applied to alter how the loop
executes. In this tutorial, we are covering every type of
Comparison operator control statement that exists in Python.
if Statements
Comparison operators are used to comparing the value
of the two operands and returns Boolean true or false The if statement is arguably the most used statement
accordingly. to control loops. For instance:

==,!=,>=,<=,>,< 1. # Python program to show how if statements


control loops
2.
Assignment Operators 3. n = 5
4. for i in range(n):
The assignment operators are used to assign the value 5. if i < 2:
of the right expression to the left operand. 6. i += 1
7. if i > 2:
=,+=,-=,*=,/=,%=**=,//= 8. i -= 2
9. print(i)
Break Statements
Bitwise Operators

In Python, the break statement is employed to end or


The bitwise operators perform bit by bit operation on remove the control from the loop that contains the
the values of the two operands. statement. It is used to end nested loops (a loop inside
another loop), which are shared with both types of
Python loops. The inner loop is completed, and control
& (binary and), | (binary or), ^ (binary xor), ~ (negation),
is transferred to the following statement of the outside
<< (left shift), >> (right shift) loop.

Logical Operators 1. # Python program to show how to control th


e flow of loops with the break statement
The logical operators are used primarily in the 2.
3. Details = [[19, 'Itika', 'Jaipur'], [16, 'Aman', 'Bi
expression evaluation to make a decision. Python
har']]
supports the following logical operators. 4. for candidate in Details:
5. age = candidate[0]
And, , or, not 6. if age <= 18:
7. break
8. print (f"{candidate[1]} of state {candidate[2
Membership Operators ]} is eligible to vote")
Continue Statements
In:- It is evaluated to be true if the first operand is found
in the second operand (list, tuple, or dictionary). When a Python interpreter sees a continue statement,
it skips the present iteration's execution if the condition
not in:- It is evaluated to be true if the first operand is is satisfied. If the condition is not satisfied, it allows the
not found in the second operand (list, tuple, or implementation of the current iteration. It is employed
dictionary). to keep the program running even when it meets a
break while being executed.

1. for l in 'I am a coder':


2. if l == ' ': 12. square = value ** 2
3. continue 4. print ('Letter: ', l) 13. squares.append(square)
Pass Statements 14. print("The list of squares is", squares)

If the condition is met, the pass statement, or a null While Loop


operator, is used by the coder to leave it as it is.
Python's pass control statement changes nothing and
moves on to the following iteration without stopping While loops are used in Python to iterate until a specified
the execution or skipping any steps after completing condition is met. However, the statement in the program
the current iteration. that follows the while loop is executed once the condition
changes to false.
1. for l in 'Python':
2. if l == 't':
Syntax of the while loop is:
3. pass
4. print('Letter: ', l)
else in Loop 1. while <condition>:
2. { code block }
The else statement is used with the if clause, as we 3. # Python program to show how to use a while lo
have previously learned. Python supports combining
the else keyword with the for and the while loop. After op
the code block of the loop, the else block is displayed. 4. counter = 0
After completing all the iterations, the interpreter will 5. # Initiating the loop
carry out the code in the else code block. Only when 6. while counter < 10: # giving the condition
the else block has been run does the program break 7. counter = counter + 3
from the loop. 8. print("Python Loops")

1. for n in range(5): Nested Loops


2.
3. print(f"Current iteration: {n+1}")
4. else: If we have a piece of script that we want to run a number of
5. print("This is the else block") times and then another piece of script inside that script that
6. print("Outside the loop") we want to run B number of times, we employ a "nested
loop." When working with an iterable in the lists, these are
Python Loops widely utilized in Python.

The following loops are available in Python to fulfil the Code


looping needs. Python offers 3 choices for running the
loops. The basic functionality of all the techniques is the
1. import random
same, although the syntax and the amount of time required
2. numbers = [ ]
for checking the condition differ.
3. for val in range(0, 11):
4. numbers.append( random.randint( 0, 11 ) )
We can run a single statement or set of statements 5. for num in range( 0, 11 ):
repeatedly using a loop command. 6. for i in numbers:
7. if num == i:
The for Loop 8. print( num, end = " " )

Python's for loop is designed to repeatedly execute a code Difference between break and
block while iterating through a list, tuple, dictionary, or
other iterable objects of Python. The process of traversing a continue.
sequence is known as iteration.
Break;
1 The break statement is used to jump out of a loop.
Syntax of the for Loop 2.Its syntax is -:break; 3. The break is a keyword
present in the language 4. It can be used with loops
ex-: for loop, while loop. 5. The break statement is
1. for value in sequence: also used in switch statements
2. { code block }
Continue:- 1 The continue statement is used to
Ex. numbers = [4, 2, 6, 7, 3, 5, 8, 10, 6, 1, 9, 2] skip an iteration from a loop. 2 Its syntax is
3. -:continue; 3 continue is a keyword present in the
4. # variable to store the square of the number language. 4 It can be used with loops ex-: for loop,
5. square = 0 while loop. 5 We can use continue with a switch
6. statement to skip a case.
7. # Creating an empty list
8. squares = []
9.
10. # Creating a for loop
11. for value in numbers:
Defining a Function Features of Python Language

You can define functions to provide the required In this section, we will learn about the different features
functionality. Here are simple rules to define a function of Python language.
in Python.
Interpreted
**Function blocks begin with the keyword def followed
by the function name and parentheses ( ( ) ). Python is processed at runtime using the interpreter.
**Any input parameters or arguments should be placed There is no need to compile program before execution.
within these parentheses. You can also define It is similar to PERL and PHP.
parameters inside these parentheses.
Object-Oriented
**The first statement of a function can be an optional
statement - the documentation string of the function Python follows object-oriented style and design
or docstring. patterns. It includes class definition with various
**The code block within every function starts with a features like encapsulation, polymorphism and many
colon (:) and is indented. more.
**The statement return [expression] exits a function,
optionally passing back an expression to the caller. A Portable
return statement with no arguments is the same as
return None. Python code written in Windows operating system and
can be used in Mac operating system. The code can be
reused and portable as per the requirements.
Syntax
Easy to code
def functionname( parameters ): Python syntax is easy to understand and code. Any
"function_docstring" developer can understand the syntax of Python within
function_suite few hours. Python can be described as “programmer-
return [expression] friendly”

Extensible
Default arguments
If needed, a user can write some of Python code in C
language as well. It is also possible to put python code
A default argument is an argument that assumes a in source code in different languages like C++. This
default value if a value is not provided in the function makes Python an extensible language.
call for that argument. The following example gives an
idea on default arguments, it prints default age if it is
not passed −

# Function definition is here


def printinfo( name, age = 35 ):
"This prints a passed info into this function"
print "Name: ", name
print "Age ", age
return;

# Now you can call printinfo function


printinfo( age=50, name="miki" )
printinfo( name="miki" )
Output:- Name: miki
Age 50
Name: miki
Age 35

You might also like