3.note by kk
3.note by kk
• Equals: a == b
• Not Equals: a!= b
• Less than: a < b
• Less than or equal to: a <= b
• Greater than: a > b
• Greater than or equal to: a >= b
These conditions can be used in several ways, most commonly in "if statements" and loops.
The if statement
The if statement is used to test a particular condition and if the condition is true, it executes a
block of code known as if-block. The condition of if statement can be any valid logical
expression which can be either evaluated to true or false.
if expression:
statement
Example
If statement:
a = 33
b = 200
if b > a:
print("b is greater than a")
Example
num = int(input("enter the number:"))
if num%2 == 0:
Print ("The Given number is an even number")
if-else statement
The if-else statement provides an else block combined with the if statement which is executed
in the false case of the condition.
If the condition is true, then the if-block is executed. Otherwise, the else-block is executed.
The syntax of the if-else statement is given below.
if condition:
#block of statements
else:
#another block of statements (else-block)
if num%2 == 0:
print("Number is even...")
else:
print("Number is odd...")
or
WAP to print the largest of the three numbers
a = int(input("Enter a? "))
b = int(input("Enter b? "))
c = int(input("Enter c? "))
if a>b and a>c:
print("a is largest")
elif b>a and b>c:
print("b is largest")
else:
print("c is largest")
Python frequently uses the Loop to iterate over iterable objects like lists, tuples, and strings.
Crossing is the most common way of emphasizing across a series, for loops are used when a
section of code needs to be repeated a certain number of times. The for-circle is typically
utilized on an iterable item, for example, a rundown or the in-fabricated range capability. In
Python, the for Statement runs the code block each time it traverses a series of elements. On
the other hand, the "while" Loop is used when a condition needs to be verified after each
repetition or when a piece of code needs to be repeated indefinitely. The for Statement is
opposed to this Loop.
for i in list:
c = n*i
print(c)
def reverse_string(str):
str1 = "" # Declaring empty string to store the reversed string
for i in str:
str1 = i + str1
return str1 # It will return the reverse string to the caller function
The Python while loop iteration of a code block is executed as long as the given Condition,
i.e., conditional expression, is true.
The syntax of the Python while loop. The syntax is given below -
Statement
while Condition:
Statement
The given condition, i.e., conditional_expression, is evaluated initially in the Python while
loop. Then, if the conditional expression gives a boolean value True, the while loop statements
are executed. The conditional expression is verified again when the complete code block is
executed. This procedure repeatedly occurs until the conditional expression returns the boolean
value False.
i=1
while i<=10:
print(i, end=' ')
i+=1
Output:
n1 = 0
n2 = 1
Sum = 0
i=0
Example:
for i in range(1,11):
if(i%2) != 0:
continue
print(i)
Break Statement
Break statement is used to terminate the execution of a loop. Break statement can be used
inside “for” as well as “while” loops. Take a look at the following statement to see break
statement in action.
Syntax for break:
Break
for i in range(1,11):
if(i > 5):
break
print(i)
Pass Statement :
The pass statement in Python is used when a statement is required syntactically but you do not want
any command or code to execute.
• The pass statement is a statement is a null operation; nothing operation; nothing happens when it
executes. The pass is also useful in places where your code will eventually go, but has not been
written yet.
Example:
for letter in 'Python':
if letter == 'h':
pass
print ('This is pass block')
print ('Current Letter :', letter)
Functions in Python
If a program contains a large piece of code that must be run repeatedly, it is preferable to
implement that code as a function and then call it using a loop. Functions promote code reuse,
modularity, and integrity.
A function is a block of code which only runs when it is called. You can pass data,
known as parameters, into a function. A function can return data as a result.
A function is a block of organized, reusable code that is used to perform a single, related
action.
Defining a Function
You can define functions to provide the required functionality. Here are simple rules to
define a function in Python.
• Function blocks begin with the keyword def followed by the function name and
parentheses (( )).
• Any input parameters or arguments should be placed within these parentheses. You can
also define parameters inside these parentheses.
• The first statement of a function can be an optional statement - the documentation string
of the function or docstring.
• The code block within every function starts with a colon (:) and is indented.
• The statement return [expression] exits a function, optionally passing back an expression
to the caller. A return statement with no arguments is the same as return none.
Syntax
def functionname( parameters ):
"function_docstring"
function_suite
return [expression]
Creating a Function
In Python a function is defined using the def keyword:
def my_function():
print("Hello GHRCE")
Calling a Function
To call a function, use the function name followed by parenthesis:
def my_function():
print("Hello GHRCE")
my_function()
Example:
# Function definition is here
def abc( str ):
"This prints a passed string into this function"
print (str)
return;
Arguments:
• Information can be passed into functions as arguments.
• Arguments are specified after the function name, inside the parentheses. You can add
as many arguments as you want, just separate them with a comma.
• The following example has a function with one argument (fname). When the function
is called, we pass along a first name, which is used inside the function to print the full
name:
Example:
def my_function(fname):
print(fname + " Kapoor")
my_function("Raj")
my_function("Shashi")
my_function("Shammi")
Parameters or Arguments
• The terms parameter and argument can be used for the same thing: information that
are passed into a function.
• From a function's perspective:
• A parameter is the variable listed inside the parentheses in the function definition.
• An argument is the value that is sent to the function when it is called.
Number of Arguments
By default, a function must be called with the correct number of arguments. Meaning
that if your function expects 2 arguments, you have to call the function with 2
arguments, not more, and not less.
Example:
This function expects 2 arguments, and gets 2 arguments:
def my_function (fname, lname):
print(fname + " " + lname)
my_function("Sachin", "Tendulkar")
Recursion
• Recursion is the process of defining something in terms of itself.
• Advantages of Recursion:
– Recursive functions make the code look clean and elegant.
– A complex task can be broken down into simpler sub-problems using recursion.
– Sequence generation is easier with recursion than using some nested iteration.
• Disadvantages of Recursion:
– Sometimes the logic behind recursion is hard to follow through.
– Recursive calls are expensive (inefficient) as they take up a lot of memory and time.
– Recursive functions are hard to debug.
Example: Factorial of number using recursion
def recur_factorial(n):
"""Function to return the factorial
of a number using recursion"""
if n == 1:
return n
else:
return n*recur_factorial(n-1)
# Change this value for a different result
num = 7
Python String
In Python, strings can be created by enclosing the character or the sequence of characters in
the quotes. Python allows us to use single quotes, double quotes, or triple quotes to create the
string.
Syntax:
str = "Hi Python !"
We can create a string by enclosing the characters in single-quotes or double- quotes. Python
also provides triple-quotes to represent the string, but it is generally used for multiline string
or docstrings.
Output:
Hello Python
Hello Python
Triple quotes are generally used for
represent the multiline or
docstring
Strings indexing and splitting
The indexing of the Python strings starts from 0. For example, The string "HELLO" is
indexed as given
Example:
str = "HELLO"
print(str[0])
print(str[1])
print(str[2])
print(str[3])
print(str[4])
# It returns the IndexError because 6th index doesn't exist
print(str[6])
Output:
H
E
L
L
O
IndexError: string index out of range
The slice operator [] is used to access the individual characters of the string. However,
we can use the : (colon) operator in Python to access the substring from the given string.
example.
Example:
# Given String
str = "JAVATPOINT"
# Start Oth index to end
print(str[0:])
# Starts 1th index to 4th index
print(str[1:5])
# Starts 2nd index to 3rd index
print(str[2:4])
# Starts 0th to 2nd index
print(str[:3])
#Starts 4th to 6th index
print(str[4:7])
Output:
JAVATPOINT
AVAT
VA
JAV
TPO
The negative slicing in the string; it starts from the rightmost character, which is indicated as -
1. The second rightmost index indicates -2, and so on
example
str = 'JAVATPOINT'
print(str[-1])
print(str[-3])
print(str[-2:])
print(str[-4:-1])
print(str[-7:-2])
# Reversing the given string
print(str[::-1])
print(str[-12])
Output:
T
I
NT
OIN
ATPOI
TNIOPTAVAJ
IndexError: string index out of range