Python Unit 1
Python Unit 1
programming in python
UNIT 1
1) INTRODUCTION TO PYTHON BASICS
What is Python?
Python is a very popular general-purpose interpreted, interactive, object-oriented, and
high-level programming language.
Python is dynamically-typed and garbage-collected programming language. It was
created by Guido van Rossum during 1985- 1990.
Python supports multiple programming paradigms, including Procedural, Object Oriented
and Functional programming language.
o Data Science
o Date Mining
o Desktop Applications
o Console-based Applications
o Mobile Applications
o Software Development
o Artificial Intelligence
o Web Applications
o Enterprise Applications
o 3D CAD Applications
o Machine Learning
o Computer Vision or Image Processing Applications.
o Speech Recognitions
Python uses new lines to complete a command, as opposed to other programming languages
which often use semicolons or parentheses.
Python relies on indentation, using whitespace, to define scope; such as the scope of loops,
functions and classes. Other programming languages often use curly-brackets for this
purpose.
Example
print("Hello, World!")
python features
Interpreted
There are no separate compilation and execution steps like C and C++.
Directly run the program from the source code.
Internally, Python converts the source code into an intermediate form
called bytecodes which is then translated into native language of specific
computer to run it.
No need to worry about linking and loading with libraries, etc.
Platform Independent
Python programs can be developed and executed on multiple operating
system platforms.
Python can be used on Linux, Windows, Macintosh, Solaris and many
more.
Free and Open Source; Redistributable
High-level Language
In Python, no need to take care about low-level details such as managing
the memory used by the program.
Simple
Closer to English language;Easy to Learn
More emphasis on the solution to the problem rather than the syntax
Embeddable
Python can be used within C/C++ program to give scripting capabilities
for the program’s users.
Robust:
Exceptional handling features
Memory management techniques in built
Rich Library Support
The Python Standard Library is very vast.
Known as the “batteries included” philosophy of Python ;It can help do
various things involving regular expressions, documentation generation,
To check if you have python installed on a Windows PC, search in the start bar for Python or run the
following on the Command Line (cmd.exe):
To check if you have python installed on a Linux or Mac, then on linux open the command line or on
Mac open the Terminal and type:
python --version
If you find that you do not have Python installed on your computer, then you can download it for free
from the following website: https://www.python.org/
Python Quickstart
Python is an interpreted programming language, this means that as a developer you write Python
(.py) files in a text editor and then put those files into the python interpreter to be executed.
The way to run a python file is like this on the command line:
Let's write our first Python file, called helloworld.py, which can be done in any text editor.
helloworld.py
print("Hello, World!")
Try it Yourself »
Simple as that. Save your file. Open your command line, navigate to the directory where you saved
your file, and run:
Hello, World!
Congratulations, you have written and executed your first Python program.
C:\Users\Your Name>python
Or, if the "python" command did not work, you can try "py":
C:\Users\Your Name>py
From there you can write any python, including our hello world example from earlier in the
tutorial:
C:\Users\Your Name>python
Python 3.6.4 (v3.6.4:d48eceb, Dec 19 2017, 06:04:45) [MSC v.1900 32 bit (Intel)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>> print("Hello, World!")
C:\Users\Your Name>python
Python 3.6.4 (v3.6.4:d48eceb, Dec 19 2017, 06:04:45) [MSC v.1900 32 bit (Intel)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>> print("Hello, World!")
Hello, World!
Whenever you are done in the python command line, you can simply type the following to
quit the python command line interface:
exit()
Interpreted Python
And if any error is encounterd it stops the translation until the error is
fixed.
Interactive mode
In the Python programming language, there are two ways in which we can run our code:
1. Interactive mode
2. Script mode
In the interactive mode as we enter a command and press enter, the very next step we
get the output. The output of the code in the interactive mode is influenced by the last
command we give. Interactive mode is very convenient for writing very short lines of
code.
print("Hello GFG")
Output:
Script Mode:
In the script mode, a python program can be written in a file. This file can then
be saved and executed using the command prompt.
We can view the code at any time by opening the file and editing becomes quite
easy as we can open and view the entire code as many times as we want.
Script mode is very suitable for writing long pieces of code. It is much preferred
over interactive mode by experts in the program.
The file made in the script made is by default saved in the Python installation
folder and the extension to save a python file is “.py”.
How to run python code in script mode?
Step 1: Make a file using a text editor. You can use any text editor of your choice(Here
I use notepad).
Step 2: After writing the code save the file using “.py” extension.
Step 3: Now open the command prompt and command directory to the one where your
file is stored.
Step 4: Type python “filename.py” and press enter.
Step 5: You will see the output on your command prompt.
In Python, we don't need to specify the type of variable because Python is a infer
language and smart enough to get variable type.
Variable names can be a group of both the letters and digits, but they have to begin with a
letter or an underscore.
Identifier Naming
Variables are the example of identifiers. An Identifier is used to identify the literals used in the
program. The rules to name an identifier are given below.
We don't need to declare explicitly variable in Python. When we assign any value to the variable,
that variable is declared automatically.
Object References
It is necessary to understand how the Python interpreter works when we declare a variable. The
process of treating variables is somewhat different from many other programming languages.
Python is the highly object-oriented programming language; that's why every data item belongs
to a specific type of class. Consider the following example.
1. print("John")
Output:
John
The Python object creates an integer object and displays it to the console. In the above print
statement, we have created a string object. Let's check the type of it using the Python built-
in type() function.
1. type("John")
Output:
<class 'str'>
In Python, variables are a symbolic name that is a reference or pointer to an object. The variables
are used to denote objects by that name.
1. a = 50
a = 50
b=a
The variable b refers to the same object that a points to because Python does not create another
object.
Let's assign the new value to b. Now both variables will refer to the different objects.
a = 50
b =100
Variable Names
We have already discussed how to declare the valid variable. Variable names can be any length
can have uppercase, lowercase (A to Z, a to z), the digit (0-9), and underscore character(_).
Consider the following example of valid variables names.
1. name = "Devansh"
2. age = 20
3. marks = 80.50
4.
5. print(name)
6. print(age)
7. print(marks)
Output:
Devansh
20
80.5
Multiple Assignment
Python allows us to assign a value to multiple variables in a single statement, which is also
known as multiple assignments.
We can apply multiple assignments in two ways, either by assigning a single value to multiple
variables or assigning multiple values to multiple variables. Consider the following example.
Eg:
1. x=y=z=50
2. print(x)
3. print(y)
4. print(z)
Output:
50
50
50
Eg:
1. a,b,c=5,10,15
2. print a
3. print b
4. print c
Output:
5
10
15
Local Variable
Local variables are the variables that declared inside the function and have scope within the
function. Let's understand the following example.
Example -
1. # Declaring a function
2. def add():
3. # Defining local variables. They has scope only within a function
4. a = 20
5. b = 30
6. c=a+b
7. print("The sum is:", c)
8.
9. # Calling a function
10. add()
Output:
Explanation:
In the above code, we declared a function named add() and assigned a few variables within the
function. These variables will be referred to as the local variables which have scope only inside
the function. If we try to use them outside the function, we get a following error.
1. add()
2. # Accessing local variable outside the function
3. print(a)
Output:
Global Variables
Global variables can be used throughout the program, and its scope is in the entire program. We
can use global variables inside or outside the function.
A variable declared outside the function is the global variable by default. Python provides
the global keyword to use global variable inside the function. If we don't use
the global keyword, the function treats it as a local variable. Let's understand the following
example.
Example -
13. mainFunction()
14. print(x)
Output:
101
Welcome To Javatpoint
Welcome To Javatpoint
Explanation:
In the above code, we declare a global variable x and assign a value to it. Next, we defined a
function and accessed the declared variable using the global keyword inside the function. Now
we can modify its value. Then, we assigned a new string value to the variable x.
Now, we called the function and proceeded to print x. It printed the as newly assigned value of x.
Delete a variable
We can delete the variable using the del keyword. The syntax is given below.
Syntax -
1. del <variable_name>
In the following example, we create a variable x and assign value to it. We deleted variable x,
and print it, we get the error "variable x is not defined". The variable x will no longer use in
future.
Example -
1. # Assigning a value to x
2. x=6
3. print(x)
4. # deleting a variable.
5. del x
6. print(x)
- Subtraction Subtracts right hand operand from left hand operand. a–b=
-10
% Modulus Divides left hand operand by right hand operand and returns remainder b%a=
0
// Floor Division - The division of operands where the result is the quotient in 9//2 = 4
which the digits after the decimal point are removed. But if one of the and
operands is negative, the result is floored, i.e., rounded away from zero 9.0//2.0
Example
Assume variable a holds 21 and variable b holds 10, then −
a = 21
b = 10
c=0
c=a+b
print "Line 1 - Value of c is ", c
c=a-b
print "Line 2 - Value of c is ", c
c=a*b
print "Line 3 - Value of c is ", c
c=a/b
print "Line 4 - Value of c is ", c
c=a%b
print "Line 5 - Value of c is ", c
a=2
b=3
c = a**b
print "Line 6 - Value of c is ", c
a = 10
b=5
c = a//b
print "Line 7 - Value of c is ", c
When you execute the above program, it produces the following result −
Line 1 - Value of c is 31
Line 2 - Value of c is 11
Line 3 - Value of c is 210
Line 4 - Value of c is 2
Line 5 - Value of c is 1
Line 6 - Value of c is 8
Line 7 - Value of c is 2
A value is one of the most basic things in any program works with.
A value may be characters i.e. ‘Hello, World!’ or a number like 1,2.2 ,3.5 etc.Values
belong to different types: 1 is an integer, 2 is a float and ‘Hello, World!’ is a string etc.
First, we type the python command to start the interpreter.
Numbers:
Python supports 3 types of numbers: integers, float and complex number. If you want to know
what type a value has you can use type() function.
print(type(1))
print(type(2.2))
print(type(complex(2,3)))
<class 'int'>
<class 'float'>
<class 'complex'>
Strings:
Strings are defined either with a single quote or a double quotes. The difference between the two
is that using double quotes makes it easy to include apostrophes.
print(type('Hello World'))
print(type("Today's News Paper"))
Python Statement
Instructions that a Python interpreter can execute are called statements. For example, a
Multi-line statement
In Python, the end of a statement is marked by a newline character. But we can make
a statement extend over multiple lines with the line continuation character (\). For
example:
a=1+2+3+\
4+5+6+\
7+8+9
a = (1 + 2 + 3 +
4+5+6+
7 + 8 + 9)
Here, the surrounding parentheses () do the line continuation implicitly. Same is the
case with [] and { }. For example:
colors = ['red',
'blue',
'green']
We can also put multiple statements in a single line using semicolons, as follows:
a = 1; b = 2; c = 3
Python Indentation
A code block (body of a function, loop, etc.) starts with indentation and ends
with the first unindented line.
The amount of indentation is up to you, but it must be consistent throughout
that block.
Generally, four whitespaces are used for indentation and are preferred over tabs. Here
is an example.
for i in range(1,11):
print(i)
if i == 5:
break
Run Code
The enforcement of indentation in Python makes the code look neat and clean. This
results in Python programs that look similar and consistent.
Indentation can be ignored in line continuation, but it's always a good idea to indent. It
makes the code more readable. For example:
if True:
print('Hello')
a=5
and
if True: print('Hello'); a = 5
both are valid and do the same thing, but the former style is clearer.
7)PYTHON OPERATORS
Operators are used to perform operations or mathematical calculation on variables and values.
In the example below, we use the + operator to add together two values:
Example
print(10 + 5)
Arithmetic operators
Assignment operators
Comparison operators
Logical operators
Identity operators
Membership operators
Bitwise operators
Arithmetic Operators
Arithmetic operators are used with numeric values to perform common mathematical operations:
+ Addition x+y
- Subtraction x-y
* Multiplication x*y
/ Division x/y
% Modulus x%y
** Exponentiation x ** y
// Floor division x // y
Example:
X = 10
Y = 20
# output: x + y = 30
print ( ‘x + y =’, x + y )
Assignment Operators
Assignment operators are used to assign values to variables:
+= x += 3 x=x+3 Try i
-= x -= 3 x=x-3 Try i
*= x *= 3 x=x*3 Try i
/= x /= 3 x=x/3 Try i
%= x %= 3 x=x%3 Try i
|= x |= 3 x=x|3 Try i
^= x ^= 3 x=x^3 Try i
== Equal x == y
!= Not equal x != y
ex :
x = 20
y = 25
# Output: x > y is False
print('x > y is',x>y)
Run:
x > y is False
Logical Operators:
and Returns True if both statements are true x < 5 and x < 10
Not Reverse the result, returns False if the not(x < 5 and x < 10)
x = 10
y = 20
# Output: x and y is True
print('x and y is',x and y)
Output:
Identity Operators:
Identity operators are used to compare the objects, not if they are equal, but if they are actually the
same object, with the same memory location:
is not Returns True if both variables are not the same x is not y
object
Example –
number1 = 5
number2 = 5
number3 = 10
print(number1 is number2) # check if number1 is equal to number2
print(number1 is not number3) # check if number1 is not equal to number3
Output:
True
True
The first print statement checks if number1 and number2 are equal or not; if they are, it gives
output as True, otherwise False—the next print statement checks for number1 and number3. To
return True, number1 and number3 shouldn’t be equal.
not in Returns True if a sequence with the specified value is not x not in y
present in the object
<< Zero fill left Shift left by pushing zeros in from the right and let the leftmost bits fall off
shift
>> Signed right Shift right by pushing copies of the leftmost bit in from the left, and let the rightm
shift off
Output:
Output-
& operation- 0
| operation- 7
^ operation- 7
~ operation- -4
<< operation- 8
>> operation- 2
For the and operation, the results become 0 because at least 1 bit is 0 in 4 or 3. In the case of
the or operator, if at least one bit is 1, then it returns 1.
8)Boolean Values
In programming you often need to know if an expression is True or False.
You can evaluate any expression in Python, and get one of two answers, True or False.
When you compare two values, the expression is evaluated and Python returns the Boolean
answer:
Example
print(10 > 9)
print(10 == 9)
print(10 < 9)
Example
Print a message based on whether the condition is True or False:
a = 200
b = 33
if b > a:
print("b is greater than a")
else:
print("b is not greater than a")
Example
Evaluate a string and a number:
print(bool("Hello"))
print(bool(15))
Example
Evaluate two variables:
x = "Hello"
y = 15
print(bool(x))
print(bool(y))
Any list, tuple, set, and dictionary are True, except empty ones.
Example
The following will return True:
bool("abc")
bool(123)
bool(["apple", "cherry", "banana"])
Example
The following will return False:
bool(False)
bool(None)
bool(0)
bool("")
bool(())
bool([])
bool({})
One more value, or object in this case, evaluates to False, and that is if you have an object that is
made from a class with a __len__ function that returns 0 or False:
Example
class myclass():
def __len__(self):
return 0
myobj = myclass()
print(bool(myobj))
Example
Print the answer of a function:
def myFunction() :
return True
print(myFunction())
Example
Print "YES!" if the function returns True, otherwise print "NO!":
def myFunction() :
return True
if myFunction():
print("YES!")
else:
print("NO!")
Python also has many built-in functions that return a boolean value, like
the isinstance() function, which can be used to determine if an object is of a certain data type:
Example
Check if an object is an integer or not:
x = 200
print(isinstance(x, int))
9)OPERATOR PRECEDENCE
The Python interpreter executes operations of higher precedence operators first in any
given logical or arithmetic expression. Except for the exponent operator (**), all other
operators are executed from left to right.
An expression is a collection of numbers, variables, operations, and built-in or user-
defined function calls. The Python interpreter can evaluate a valid expression.
Code 2 - 7
Output:
-5
The following table lists all operators from highest precedence to lowest.
Operator Description
~+- Complement, unary plus and minus (method names for the last two are +@ and -@)
e = (a + b) * c / d #( 30 * 15 ) / 5
print "Value of (a + b) * c / d is ", e
e = ((a + b) * c) / d # (30 * 15 ) / 5
print "Value of ((a + b) * c) / d is ", e
e = a + (b * c) / d; # 20 + (150/5)
print "Value of a + (b * c) / d is ", e
When you execute the above program, it produces the following result −
Value of (a + b) * c / d is 90
Value of ((a + b) * c) / d is 90
Value of (a + b) * (c / d) is 90
Value of a + (b * c) / d is 50
Example :
x = 25 # a statement
x = x + 10 # an expression
print(x)
Output :
35
The expression in Python can be considered as a logical line of code that is evaluated to obtain
some result. If there are various operators in an expression then the operators are resolved based
on their precedence. We have various types of expression in Python
1. Constant Expressions
A constant expression in Python that contains only constant values is known as a constant
expression. In a constant expression in Python, the operator(s) is a constant. A constant is a
value that cannot be changed after its initialization.
Example :
x = 10 + 15
Output :
Example :
x = 10
y=5
addition = x + y
subtraction = x - y
product = x * y
division = x / y
power = x**y
Output :
Example :
x = 10 # an integer number
y = 5.0 # a floating point number
# we need to convert the floating-point number into an integer or vice versa for summation.
result = x + int(y)
Output :
A floating expression in Python is used for computations and type conversion (integer to float,
a string to integer, etc.). A floating expression always produces a floating-point number as a
resultant.
Example :
x = 10 # an integer number
y = 5.0 # a floating point number
# we need to convert the integer number into a floating-point number or vice versa for
summation.
result = float(x) + y
Output :
For example :
10 + 15 > 2010+15>20
In this example, first, the arithmetic expressions (i.e. 10 + 1510+15 and 2020) are evaluated,
and then the results are used for further comparison.
Example :
a = 25
b = 14
c = 48
d = 45
# The expression checks if the sum of (a and b) is the same as the difference of (c and d).
result = (a + b) == (c - d)
print("Type:", type(result))
print("The result of the expression is: ", result)
Output :
As the name suggests, a logical expression performs the logical computation, and the overall
expression results in either True or False (boolean result). We have three types of logical
expressions in Python, let us discuss them briefly.
And xx and yy The expression return True if both xx and yy are true, else it returns False.
Note :
In the table specified above, xx and yy can be values or another expression as well.
Example :
x = (10 == 9)
y = (7 > 5)
and_result = x and y
or_result = x or y
not_x = not x
Output :
The expression in which the operation or computation is performed at the bit level is known as
a bitwise expression in Python. The bitwise expression contains the bitwise operators.
Example :
x = 25
left_shift = x << 1
right_shift = x >> 1
Output :
As the name suggests, a combination expression can contain a single or multiple expressions
which result in an integer or boolean value depending upon the expressions involved.
Example :
x = 25
y = 35
result = x + (y << 1)
Output :
Result obtained: 95
Whenever there are multiple expressions involved then the expressions are resolved based on
their precedence or priority. Let us learn about the precedence of various operators in the
following section.
1. ()[]{} Parenthesis
2. ** Exponentiation
8. ^ Bitwise XOR
x = 12
y = 14
z = 16
result_1 = x + y * z
print("Result of 'x + y + z' is: ", result_1)
result_2 = (x + y) * z
print("Result of '(x + y) * z' is: ", result_2)
result_3 = x + (y * z)
print("Result of 'x + (y * z)' is: ", result_3)
Output :
A statement in Python is used for creating variables The expression in Python produces some value or result after being
or for displaying values. interpreted by the Python interpreter.
Example: x = 3 + 6x=3+6.
Example : x= 3x=3. Output : 99
Output : 33
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, the condition after evaluation will be either true or false. if the 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.
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
i = 10
if (i > 15):
Output:
I am Not in if
As the condition present in the if statement is false. So, the block below the if statement
is executed.
if-else
if a condition is true it will execute a block of statements 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
Flow chart
i = 20
if (i < 15):
print("i'm in if Block")
else:
Output:
i is greater than 15
i'm in else Block
i'm not in if and not in else Block
The block of code following the else statement is executed as the condition present in
the if statement is false after calling the statement which is not in block(without spaces).
def digitSum(n):
dsum = 0
dsum += int(ele)
return dsum
print(newList)
Output
[16, 3, 18, 18]
nested-if
A nested if is an if statement that is the target of another if statement. Nested if
statements mean 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
i = 10
if (i == 10):
if (i < 15):
if (i < 12):
else:
Output:
i is smaller than 15
i is smaller than 12 too
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
i = 20
if (i == 10):
print("i is 10")
elif (i == 15):
print("i is 15")
elif (i == 20):
print("i is 20")
else:
Output:
i is 20
i = 10
if i < 15:
Output:
i is less than 15
i = 10
Output:
True
The following sorts of loops are available in the Python programming language.
1 While loop Repeats a statement or group of statements while a given condition is TRUE. It tests th
condition before executing the loop body.
2 For loop This type of loop executes a code block multiple times and abbreviates the code tha
manages the loop variable.
1 Break statement This command terminates the loop's execution and transfers the program's contro
to the statement next to the loop.
2 Continue statement This command skips the current iteration of the loop. The statements following th
continue statement are not executed once the Python interpreter reaches th
continue statement.
3 Pass statement The pass statement is used when a statement is syntactically necessary, but no cod
is to be executed.
Python's for loop is designed to repeatedly execute a code block while iterating through a list,
tuple, dictionary, or other iterable objects of Python. The process of traversing a sequence is
known as iteration.
In this case, the variable value is used to hold the value of every item present in the sequence
before the iteration begins until this particular iteration is completed.
Loop iterates until the final item of the sequence are reached.
Code
Output:
The list of squares is [16, 4, 36, 49, 9, 25, 64, 100, 36, 1, 81, 4]
Only if the execution is complete does the else statement comes into play. It won't be executed if
we exit the loop or if an error is thrown.
Code
1.
2. string = "Python Loop"
3.
4. # Initiating a loop
5. for s in a string:
6. # giving a condition in if block
7. if s == "o":
8. print("If block")
9. # if condition is not satisfied then else block will be executed
10. else:
11. print(s)
Output:
P
y
t
h
If block
n
L
If block
If block
p
Syntax:
else:
Code
1. # Python program to show how to use else statement with for loop
2.
3. # Creating a sequence
4. tuple_ = (3, 4, 6, 8, 9, 2, 3, 8, 9, 7)
5.
6. # Initiating the loop
7. for value in tuple_:
8. if value % 2 != 0:
9. print(value)
10. # giving an else statement
11. else:
12. print("These are the odd numbers present in the tuple")
Output:
3
9
3
9
7
These are the odd numbers present in the tuple
We can give specific start, stop, and step size values in the manner range(start, stop, step size). If
the step size is not specified, it defaults to 1.
Since it doesn't create every value it "contains" after we construct it, the range object can be
characterized as being "slow." It does provide in, len, and __getitem__ actions, but it is not an
iterator.
Code
1.
2. print(range(15))
3.
4. print(list(range(15)))
5.
6. print(list(range(4, 9)))
7.
8. print(list(range(5, 25, 4)))
Output:
range(0, 15)
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14]
[4, 5, 6, 7, 8]
[5, 9, 13, 17, 21]
To iterate through a sequence of items, we can apply the range() method in for loops. We can use
indexing to iterate through the given sequence by combining it with an iterable's len() function.
Here's an illustration.
Code
Output:
PYTHON
LOOPS
SEQUENCE
CONDITION
RANGE
While Loop
While loops are used in Python to iterate until a specified condition is met. However, the
statement in the program that follows the while loop is executed once the condition changes to
false.
1. while <condition>:
2. { code block }
All the coding statements that follow a structural command define a code block. These
statements are intended with the same number of spaces. Python groups statements together with
indentation.
1. counter = 0
2. # Initiating the loop
3. while counter < 10: # giving the condition
4. counter = counter + 3
5. print("Python Loops")
Output:
Python Loops
Python Loops
Python Loops
Python Loops
Code
1. #Python program to show how to use else statement with the while loop
2. counter = 0
3.
4. # Iterating through the while loop
5. while (counter < 10):
6. counter = counter + 3
7. print("Python Loops") # Executed untile condition is met
8. # Once the condition of while loop gives False this statement will be executed
9. else:
10. print("Code block inside the else statement")
Output:
Python Loops
Python Loops
Python Loops
Python Loops
Code block inside the else statement
Code
1. counter = 0
2. while (count < 3): print("Python Loops")
Continue Statement
It returns the control to the beginning of the loop.
Code
Output:
Current Letter: P
Current Letter: y
Current Letter: h
Current Letter: n
Current Letter:
Current Letter: L
Current Letter: s
Break Statement
It stops the execution of the loop when the break statement is reached.
1.
2. # Initiating the loop
3. for string in "Python Loops":
4. if string == 'L':
5. break
6. print('Current Letter: ', string)
Output:
Current Letter: P
Current Letter: y
Current Letter: t
Current Letter: h
Current Letter: o
Current Letter: n
Current Letter:
Pass Statement
Pass statements are used to create empty loops. Pass statement is also employed for classes,
functions, and empty control statements.
Output:
Last Letter: s
SYNTAX
Myfun.py
Output:
Welcome to JavaTpoint
Syntax:
1. def function_name():
2. Statement1
3. function_name() # directly call the function
4.
5. # calling function using built-in function
6. def function_name():
7. str = function_name('john') # assign the function to call the function
Consider the following example to print the Welcome Message using a function in Python.
CallFun.py
1. def MyFun():
2. print("Hello World")
3. print(" Welcome to the JavaTpoint")
4.
5. MyFun() # Call Function to print the message.
Output:
Hello World
Welcome to the JavaTpoint
In the above example, we call the MyFun() function that prints the statements.
Nest.py
Output:
Program to print the multiplication of two numbers using the nested function in Python.
Nest_arg.py
Output:6
Obj.py
Output:
WELCOME TO JAVATPOINT
HELLO, WELCOME TO JAVATPOINT
Student.py
1. class Student:
2. Roll_no = 101
3. name = "Johnson"
4. def show(self):
5. print(" Roll no. is %d\nName of student is %s" % (self.Roll_no, self.name))
6.
7. stud = Student() # Create the stud object of Student class
8. stud.show() # call the function using stud object.
Output:
A return statement is used to end the execution of the function call and
“returns” the result (value of the expression following the return keyword) to the
caller. The statements after the return statements are not executed. If the return
statement is without any expression, then the special value None is
returned. A return statement is overall used to invoke a function so that the
passed statements can be executed.
def is_true(a):
# returning boolean of a
return bool(a)
# calling function
res = add(2, 3)
print("Result of add function is {}".format(res))
res = is_true(2<5)
Output:
Result of add function is 5
class Test:
def __init__(self):
self.str = "geeksforgeeks"
self.x = 20
def fun():
return Test()
t = fun()
print(t.str)
print(t.x)
Output
geeksforgeeks
20
Using Tuple: A Tuple is a comma separated sequence of items. It is created with
or without (). Tuples are immutable. See this for details of tuple.
Python3
def fun():
str = "geeksforgeeks"
x = 20
# write (str, x)
print(str)
print(x)
Output:
geeksforgeeks
20
Using a list: A list is like an array of items created using square brackets. They
are different from arrays as they can contain items of different types. Lists are
different from tuples as they are mutable. See this for details of list.
Python3
def fun():
str = "geeksforgeeks"
x = 20
list = fun()
print(list)
Output:
['geeksforgeeks', 20]
Using a Dictionary: A Dictionary is similar to hash or map in other languages.
See this for details of dictionary.
Python3
def fun():
d = dict();
d['str'] = "GeeksforGeeks"
d['x'] = 20
return d
d = fun()
print(d)
Output:
{'x': 20, 'str': 'GeeksforGeeks'}
Python3
def create_adder(x):
def adder(y):
return x + y
return adder
add_15 = create_adder(15)
def outer(x):
return x * 10
def my_func():
return outer
res = my_func()
Output:
The result is 25
15)PARAMETER PASSING
Pass-by-value vs Pass-by-reference
Before answering this question, let’s first understand the basic principles of
Python variables and assignments.
Here, 1 is first assigned to a, that is, a points to the object 1, as shown in the
following flowchart:
Then b = a means, let the variable b also, point to the object 1 at the same
time. Note here that objects in Python can be pointed to or referenced by
multiple variables. Now the flowchart looks like this:
Finally the a = a + 1 statement. It should be noted that Python data types, such
as integers (int), strings (string), etc., are immutable. So, a = a + 1, does not
increase the value of a by 1, but means that a new object with a value of 2 is
created and a points to it. But b remains unchanged and still points to
the 1 object:
At this point, you can see that a simple assignment b = a does not mean that a
new object is recreated, but that the same object is pointed or referenced by
multiple variables.
At the same time, pointing to the same object does not mean that the two
variables are bound together. If you reassign one of the variables, it will not
affect the value of the other variables.
At first, we let the lists l1 and l2 point to the object [1, 2, 3] at the same time:
Since the list is mutable, l1.append(4) does not create a new list, it just inserts
element 4 at the end of the original list, which becomes [1, 2, 3, 4].
Since l1 and l2 point to this list at the same time, the change of the list will be
reflected in the two variables of l1 and l2 at the same time, then the values
of l1 and l2 will become [1, 2, 3, 4] at the same time.
Also, note that variables in Python can be deleted, but objects cannot be
deleted. For example the following code:
l = [1, 2, 3]
del l
del l deletes the variable l, and you cannot access l from now on, but the object
[1, 2, 3] still exists. When a Python program runs, its own garbage collection
system keeps track of every object reference. If [1, 2, 3] is referenced in other
places besides l, it will not be collected, otherwise, it will be collected.
So, in Python:
For immutable objects (strings, ints, tuples, etc.), the value of all
variables that point to the object is always the same and does not change.
But when the value of an immutable object is updated by some operation
(+= etc.), a new object is returned.
For example:
def my_func1(b):
b = 2a = 1
my_func1(a)
a
1
The parameter passing here makes the variables a and b point to the object 1 at
the same time. But when we get to b = 2, the system will create a new object
with a value of 2 and let b point to it; a still points to the 1 object. So, the value
of a doesn’t change, it’s still 1.
Here l1 and l2 first both point to lists with values [1, 2, 3]. However, since the
list is variable when the append() the function is executed and a new
element 4 is added to the end of the list, the values of the variables l1 and l2 are
also changed.
However, the following example, which seems to add a new element to the
list, yields significantly different results.
def my_func4(l2):
l2 = l2 + [4]l1 = [1, 2, 3]
my_func4(l1)
l1
[1, 2, 3]
This is because statement l2 = l2 + [4], which means that a new list with
“element 4 added at the end” is created, and l2 points to this new object.
Local Scope
A variable created inside a function belongs to the local scope of that function,
and can only be used inside that function.
Example
A variable created inside a function is available inside that function:
def myfunc():
x = 300
print(x)
myfunc()
Example
The local variable can be accessed from a function within the function:
def myfunc():
x = 300
def myinnerfunc():
print(x)
myinnerfunc()
myfunc()
Global Scope
A variable created in the main body of the Python code is a global variable and
belongs to the global scope.
Global variables are available from within any scope, global and local.
Example
A variable created outside of a function is global and can be used by anyone:
x = 300
def myfunc():
print(x)
myfunc()
print(x)
Naming Variables
If you operate with the same variable name inside and outside of a function,
Python will treat them as two separate variables, one available in the global
scope (outside the function) and one available in the local scope (inside the
function):
Example
The function will print the local x, and then the code will print the global x:
x = 300
def myfunc():
x = 200
print(x)
myfunc()
print(x)
Global Keyword
If you need to create a global variable, but are stuck in the local scope, you can
use the global keyword.
Example
If you use the global keyword, the variable belongs to the global scope:
def myfunc():
global x
x = 300
myfunc()
print(x)
Also, use the global keyword if you want to make a change to a global variable
inside a function.
Example
To change the value of a global variable inside a function, refer to the variable
by using the global keyword:
x = 300
def myfunc():
global x
x = 200
myfunc()
print(x)
Recursion
Python also accepts function recursion, which means a defined function can call
itself.
The developer should be very careful with recursion as it can be quite easy to
slip into writing a function which never terminates, or one that uses excess
amounts of memory or processor power. However, when written correctly
recursion can be a very efficient and mathematically-elegant approach to
programming.
To a new developer it can take some time to work out how exactly this works,
best way to find out is by testing and modifying it.
Example
Recursion Example
def tri_recursion(k):
if(k>0):
result = k+tri_recursion(k-1)
print(result)
else:
result = 0
return result