Python – AppDividend https://appdividend.com Latest Code Tutorials Tue, 17 Sep 2019 11:08:12 +0000 en-US hourly 1 https://wordpress.org/?v=5.2.3 https://appdividend.com/wp-content/uploads/2017/08/cropped-ApDivi-32x32.png Python – AppDividend https://appdividend.com 32 32 Python Recursion Example | Recursion In Python Programming Tutorial https://appdividend.com/2019/09/17/python-recursion-example-recursion-in-python-programming-tutorial/ https://appdividend.com/2019/09/17/python-recursion-example-recursion-in-python-programming-tutorial/#respond Tue, 17 Sep 2019 10:59:53 +0000 http://localhost/wordpress/?p=11316 Python Recursion Example | Recursion In Python Programming Tutorial

Python Recursion Example | Recursion In Python Programming Tutorial is today’s topic. Recursion is the method of programming or coding the problem, in which the function calls itself one or more times in its body. Usually, it is returning a return value of this function call. If the function definition satisfies the condition of recursion, […]

The post Python Recursion Example | Recursion In Python Programming Tutorial appeared first on AppDividend.

]]>
Python Recursion Example | Recursion In Python Programming Tutorial

Python Recursion Example | Recursion In Python Programming Tutorial is today’s topic. Recursion is the method of programming or coding the problem, in which the function calls itself one or more times in its body. Usually, it is returning a return value of this function call. If the function definition satisfies the condition of recursion, we call this function a recursive function.

What is recursion in Python

Recursion is a process of defining something in terms of itself.

A Real-world example would be to place two parallel mirrors facing each other like the movie in inception. Any object in between them would be reflected recursively and you will see infinite reflections of that object.

Python Recursive Function

A recursive function is the function defined in terms of itself via self-referential expressions.

The recursive function has to fulfill an essential condition to be used in a program: it has to terminate.

The recursive function terminates if with every recursive call the solution of the problem is downsized and moves towards the base case.

The base case is a case where a problem can be solved without further recursion.

The recursion can end up in an infinite loop if the base case is not met in the calls.

Factorial of any number is the product of all the integers from 1 to that number. For instance, the factorial of 6 (denoted as 6!) is 1*2*3*4*5* = 120.

Python Recursion Program

See the following program of Recursion in Python.

# app.py

def factorial(x):
    if x == 1:
        return 1
    else:
        return (x * factorial(x-1))


number = 5
print("The factorial of", number, "is", factorial(number))

See the output.

➜  pyt python3 app.py
The factorial of 5 is 120
➜  pyt

In the above example, factorial() is the recursive function as it calls itself.

When we call this function with the positive integer, it will recursively call itself by decreasing a number.

Each function calls multiples the number with the factorial of number 1 until the number is equal to one.

What is the base case in recursion

When working with a recursion, we should define the base case for which we already know an answer. In an above example, we are finding the factorial of the integer number, and we already know that a factorial of 1 is 1 so this is our base case.

Each successive recursive call to a function should bring it closer to the base case, which is precisely what we are doing in the above example.

We use a base case in recursive function so that the function stops calling itself when the base case is reached. Without the base case, the function would keep calling itself indefinitely.

Python Recursion Example

To demonstrate this structure, let’s write the recursive function for calculating n!:

  1. Decompose the original problem into more straightforward instances of a same problem. This is the recursive case:

    n! = n x (n−1) x (n−2) x (n−3) ⋅⋅⋅⋅ x 3 x 2 x 1
    n! = n x (n−1)!
    
  2. As a large problem, we need to broke down into successively less complex ones, those subproblems must eventually become so simple that they could solved without any further subdivision. This is the base case:

    n! = n x (n−1)! 
    n! = n x (n−1) x (n−2)!
    n! = n x (n−1) x (n−2) x (n−3)!
    ⋅
    ⋅
    n! = n x (n−1) x (n−2) x (n−3) ⋅⋅⋅⋅ x 3!
    n! = n x (n−1) x (n−2) x (n−3) ⋅⋅⋅⋅ x 3 x 2!
    n! = n x (n−1) x (n−2) x (n−3) ⋅⋅⋅⋅ x 3 x 2 x 1!
    

Here, 1! is our base case, and it equals 1.

Advantages of Recursion

  1. Recursive functions make a code look clean and elegant.
  2. The complex task can be broken down into simpler sub-problems using recursion.
  3. Sequence generation is more comfortable with a recursion than using the nested iteration.

Disadvantages of Recursion

  1. A logic behind recursion is hard to follow through.
  2. The recursive calls are expensive (inefficient) as they take up the lot of memory and time.
  3. Recursive functions are very hard to debug.

Finally, Python Recursion Example | Recursion In Python Programming Tutorial is over.

Recommended Posts

Python Operators Example

Python Not Equal Operator Example

Python Sum Example

Python Time sleep() Function Example

Python Data Types Example

The post Python Recursion Example | Recursion In Python Programming Tutorial appeared first on AppDividend.

]]>
https://appdividend.com/2019/09/17/python-recursion-example-recursion-in-python-programming-tutorial/feed/ 0
Python Operators Example | Arithmetic, Comparison, Logical, Assignment https://appdividend.com/2019/09/17/python-operators-example-arithmetic-comparison-logical-assignment/ https://appdividend.com/2019/09/17/python-operators-example-arithmetic-comparison-logical-assignment/#respond Tue, 17 Sep 2019 08:39:35 +0000 http://localhost/wordpress/?p=11289 Python Operators Example | Arithmetic, Comparison, Logical, Assignment

Python Operators Example | Arithmetic, Comparison, Logical, Assignment Operator is today’s topic. In this post, you will learn everything about different kinds of operators in Python, their syntax, and how to use them with brief examples. Python Operator is used to performing operations on variables and values. Operators are used to perform the operations on […]

The post Python Operators Example | Arithmetic, Comparison, Logical, Assignment appeared first on AppDividend.

]]>
Python Operators Example | Arithmetic, Comparison, Logical, Assignment

Python Operators Example | Arithmetic, Comparison, Logical, Assignment Operator is today’s topic. In this post, you will learn everything about different kinds of operators in Python, their syntax, and how to use them with brief examples. Python Operator is used to performing operations on variables and values. Operators are used to perform the operations on values and variables.

Operators can manipulate an individual item and returns the result. The data items are referred to as operands or arguments. Keywords or special characters either represent operators.

For example, for identity operators, we use the keyword “is” and “is not”.

What is Operator in Python

Operators are unique symbols in Python that carry out arithmetic or logical calculation. A value that the Python operator runs on is called the operand.

Let’s see the following code example.

print(11 + 21)

See the output.

➜  pyt python3 app.py
32
➜  pyt

Here, + is the operator that performs addition. 11 and 21 are the operands, and 32 is the output of the operation.

Python Operators Example

Python divides the operators into the following groups:

  1. Arithmetic operators
  2. Assignment operators
  3. Comparison operators
  4. Logical operators
  5. Identity operators
  6. Membership operators
  7. Bitwise operators

Python Arithmetic Operator

Arithmetic operators are used with the numeric values to perform everyday mathematical operations. 

Arithmetic Operators perform different arithmetic computations like addition, subtraction, multiplication, division, %modulus, exponent, etc.

There are several methods for arithmetic computation in Python like you can use the eval function, declare variable & calculate, or call functions.

Operator Meaning Example
+ Add two operands or unary plus. a + b
+2
Subtract the right operand from the left or unary minus. a – b
-2
* Multiply two operands. a * b
/ Divide left operand by a right one (always results into float). a / b
% Modulus: the remainder of the division of left operand by the right. a % b (remainder of a/b)
// Floor division: division that results in the whole number adjusted to the left in the number line. a // b
** Exponent: left operand raised to the power of right. a**b (a to the power b)

Arithmetic Operators Example In Python

See the following code.

# app.py

a = 11
b = 21

print('a + b =', a+b)

print('a - b =', a-b)

print('a * b =', a*b)

print('a / b =', a/b)

print('a // b =', a//b)

print('a ** b =', a**b)

See the output.

➜  pyt python3 app.py
a + b = 32
a - b = -10
a * b = 231
a / b = 0.5238095238095238
a // b = 0
a ** b = 7400249944258160101211
➜  pyt

Python Assignment Operator

Python assignment operators are used to assigning the value of the right operand to a left operand. Multiple assignment operators used in Python are (+=, – = , *=, /= , etc.).

Example: Python assignment operators is to assign the value, for example.

a = 11 is a simple assignment operator that assigns the value 5 on the right to the variable a on the left.

There are various compound operators like a += 11 that adds to the variable and later assigns the same. It is equivalent to a = a + 11.

Operator Example Equivatent to
= a = 11 a = 11
+= a += 11 a = a + 11
-= a -= 11 a = a – 11
*= a *= 11 a = a * 11
/= a /= 11 a = a / 11
%= a %= 11 a = a % 11
//= a //= 11 a = a // 11
**= a **= 11 a = a ** 11
&= a &= 11 a = a & 11
|= a |= 11 a = a | 11
^= a ^= 11 a = a ^ 11
>>= a >>= 11 a = a >> 11
<<= a <<= 11 a = a << 11

 

Python Comparison Operator

Comparison operators are used to compare two values.

It either returns True or False based to the condition.

Operator Meaning Example
> Greater than: True if the left operand is greater than the right a > b
< Less than: True if the left operand is less than the right a < b
== Equal to: True if both the operands are equal a == b
!= Not equal to: True if the operands are not equal a != b
>= Greater than or equal to: True if the left operand is greater than or equal to the right a >= b
<= Less than or equal to: True if the left operand is less than or equal to the right a <= b

 

Comparison Operators Example In Python

See the following code.

# app.py

a = 11
b = 21

print('b > a  is', b > a)

print('b < a  is', b < a)

print('b == a is', b == a)

print('b != a is', b != a)

print('b >= a is', b >= a)

print('b <= a is', b <= a)

See the output.

➜  pyt python3 app.py
b > a  is True
b < a  is False
b == a is False
b != a is True
b >= a is True
b <= a is False
➜  pyt

Python Logical Operator

Logical operators are used to combine the conditional statements.

Logical operators are used for conditional statements are True or False.

Logical operators are AND, OR and NOT. For logical operators, the following condition is applied.

  1. For AND operator: It returns TRUE if both the operands (right side and left side) are True.
  2. For OR operator: It returns TRUE if either of the operand (right side or left side) is True.
  3. For NOT operator: returns TRUE if an operand is False.
Operator Meaning Example
and True if both the operands are true. a and b
or True if either of the operands is true. a or b
not True if the operand is false (complements the operand). not a

 

Logical Operators Example In Python

See the following code.

# app.py

a = True
b = False

print('a and b is', a and b)

print('a or b is', a or b)

print('not a is', not a)

See the output.

➜  pyt python3 app.py
a and b is False
a or b is True
not a is False
➜  pyt

Python Identity Operator

The is and is not are the identity operators in Python.

They are used to check if the two values (or variables) are located on the identical part of the memory.

Two equal variables do not imply that they are same.

Identity operators are used to comparing the objects, not if they are equal, but if they are the same object, with the same memory location.

Operator Meaning Example
is True if the operands are same (refer to the same object) a is True
is not True if the operands are not similar (do not refer to the same object) a is not True

 

Identity Operators Example In Python

See the following code.

# app.py

a1 = 11
b1 = 21
a2 = 'Eleven'
b2 = 'Eleven'
a3 = [11, 21, 10]
b3 = [11, 21, 10]

print(a1 is not b1)

print(a2 is b2)

print(a3 is b3)

See the output.

➜  pyt python3 app.py
True
True
False
➜  pyt

Python Membership Operator

Membership operators are used for testing if the sequence is presented in an object.

The in and not in are the membership operators in Python. They are used to test whether the value or variable is found in a sequence (stringlisttupleset, and dictionary).

Operator Meaning Example
in True if value/variable is found in a sequence 5 in a
not in True if the value/variable is not found in a sequence 5 not in a

 

Membership Operators Example In Python

See the following code.

# app.py

a = 'Millie Bobby Brown'
b = {1:'x',2:'y'}

print('B' in a)

print('Millie' not in a)

print(1 in b)

print('a' in b)

See the output.

➜  pyt python3 app.py
True
False
True
False
➜  pyt

Python Bitwise Operator

Bitwise operators act on the operands as if they were a string of binary digits.

It operates a bit by bit, hence the name.

Operator Meaning Example
& Bitwise AND a & b = 0 (0000 0000)
| Bitwise OR a | b = 14 (0000 1110)
~ Bitwise NOT ~a = -11 (1111 0101)
^ Bitwise XOR a ^ b = 14 (0000 1110)
>> Bitwise right shift a >> b = 2 (0000 0010)
<< Bitwise left shift a << b = 40 (0010 1000)

 

For example, 2 is 10 in the binary, and 7 is 111 in binary.

Summary of Python Operators

Operators in the programming language are used to perform various operations on values and variables. In Python, you can use operators like the following.

  1. There are several methods for arithmetic calculation in Python as you can use the eval function, declare variable & calculate, or call functions.
  2. Comparison operators often referred to as relational operators are used to comparing the values on either side of them and determine a relation between them.
  3. Python assignment operators are to assign a value to a variable.
  4. Python also allows you to use the compound assignment operator, in the complicated arithmetic calculation, where you can assign a result of one operand to the other.
  5. For AND operator: It returns TRUE if both the operands (right side and left side) are True.
  6. For OR operato: It returns TRUE if either of the operand (right side or left side) is True.
  7. For NOT operator- returns TRUE if an operand is False.
  8. Two membership operators are used in Python. (in, not in).
  9. It gives a result based on the variable present in the particular sequence or string.
  10. The two identify operators used in the Python are is, is not.
  11. It returns true if the two variables point the same object and false otherwise.

Finally, Python Operators Example | Arithmetic, Comparison, Logical, Assignment is over.

The post Python Operators Example | Arithmetic, Comparison, Logical, Assignment appeared first on AppDividend.

]]>
https://appdividend.com/2019/09/17/python-operators-example-arithmetic-comparison-logical-assignment/feed/ 0
Python Not Equal Operator Example | Not Equal Operator In Python https://appdividend.com/2019/09/16/python-not-equal-operator-example-not-equal-operator-in-python/ https://appdividend.com/2019/09/16/python-not-equal-operator-example-not-equal-operator-in-python/#respond Mon, 16 Sep 2019 11:57:59 +0000 http://localhost/wordpress/?p=11281 Python Not Equal Operator Example | Not Equal Operator In Python

Python Not Equal Operator Example is today’s topic. Python is dynamic and strongly typed language, so if the two variables have the same values, but they are of a different type, then not equal operator will return True. For comparing object identities, you can use the keyword is, and its negation is not. Python Not […]

The post Python Not Equal Operator Example | Not Equal Operator In Python appeared first on AppDividend.

]]>
Python Not Equal Operator Example | Not Equal Operator In Python

Python Not Equal Operator Example is today’s topic. Python is dynamic and strongly typed language, so if the two variables have the same values, but they are of a different type, then not equal operator will return True. For comparing object identities, you can use the keyword is, and its negation is not.

Python Not Equal Operator

The Not equal operator returns True if two variables are of the same type and have different values, if the values are identical, then it returns False.

print(1 == 1)
print(1 != 1)
print([] is [])

See the output.

➜  pyt python3 app.py
True
False
False
➜  pyt

See the following table.

Operator Description
!= Not Equal operator works in both Python 2 and Python 3.
<> Not equal operator in Python 2, deprecated in Python 3.

 

There’s the != (not equal) operator that returns True when two values differ, though be careful with the types because “1 != 1”. This will always return True and “1” == 1 will always return False since the types differ. Python is dynamically, but strongly typed, and other statically typed languages would complain about comparing different types.

We can use Python not equal operator with f-strings too if you are using Python 3.6 or higher version.

# app.py

x = 11
y = 21
z = 19

print(f'x is not equal to y = {x!=y}')

flag = x != z
print(f'x is not equal to z = {flag}')

# python is strongly typed language
s = '11'
print(f'x is not equal to s = {x!=s}')

See the output.

➜  pyt python3 app.py
x is not equal to y = True
x is not equal to z = True
x is not equal to s = True
➜  pyt

Python not equal with custom object

When we use not equal operator, it calls  __ne__(self, other) function. So we can define our custom implementation for an object and alter the natural output.

Let’s say we have Data class with fields – id and record. When we are using the not-equal operator, we want to compare it for record value. We can achieve this by implementing our __ne__() function.

See the following code.

# app.py

class App:
    id = 0
    netflix = ''

    def __init__(self, i, s):
        self.id = i
        self.netflix = s

    def __ne__(self, other):
        # return true if different types
        if type(other) != type(self):
            return True
        if self.netflix != other.netflix:
            return True
        else:
            return False


d1 = App(1, 'Stranger Things')
d2 = App(2, 'Money Heist')
d3 = App(3, 'Sacred Games')

print(d1 != d2)
print(d2 != d3)

See the output.

➜  pyt python3 app.py
True
True
➜  pyt

Finally, Python Not Equal Operator Example is over.

Recommended Posts

Null Object In Python Example

Python property() Example

Python pow() Example

Python open() Example

Python iter() Example

The post Python Not Equal Operator Example | Not Equal Operator In Python appeared first on AppDividend.

]]>
https://appdividend.com/2019/09/16/python-not-equal-operator-example-not-equal-operator-in-python/feed/ 0
Python property() Example | property() Function In Python https://appdividend.com/2019/08/20/python-property-example-property-function-in-python/ https://appdividend.com/2019/08/20/python-property-example-property-function-in-python/#respond Tue, 20 Aug 2019 11:37:52 +0000 http://localhost/wordpress/?p=10797 Python property() Example | property() Function In Python

Python property() Example | property() Function In Python is today’s topic. The property() method returns a property attribute. The property() method delivers the property attribute from a given getter, setter, and deleter. If no arguments are given, the property() method returns the base property attribute that doesn’t include any getter, setter, or deleter. If the […]

The post Python property() Example | property() Function In Python appeared first on AppDividend.

]]>
Python property() Example | property() Function In Python

Python property() Example | property() Function In Python is today’s topic. The property() method returns a property attribute. The property() method delivers the property attribute from a given getter, setter, and deleter. If no arguments are given, the property() method returns the base property attribute that doesn’t include any getter, setter, or deleter. If the doc isn’t provided, the property() method takes the docstring of the getter function.

Python property()

The syntax of the Python property() method is following.

property(fget=None, fset=None, fdel=None, doc=None)

The property() method takes four optional parameters:

  1. fget (Optional) – This function for getting the attribute value.
  2. fset (Optional) – This function for setting the attribute value.
  3. fdel (Optional) – This function for deleting the attribute value.
  4. doc (Optional) – The string that contains the documentation (docstring) for the attribute.

See the following example.

# app.py

class Student:
    def __init__(self, fname):
        self._fname = fname

    def getfname(self):
        print('Getting fname')
        return self._fname

    def setfname(self, value):
        print('Setting fname to ' + value)
        self._fname = value

    def delfname(self):
        print('Deleting fname')
        del self._fname

    fname = property(getfname, setfname, delfname, 'fname property')


s = Student('Jane')
print(s.fname)
s.fname = 'Eleven'
del s.fname

See the output.

➜  pyt python3 app.py
Getting fname
Jane
Setting fname to Eleven
Deleting fname
➜  pyt

Here, _fname is used as the private variable for storing the fname of a Student.

We also set:

  1. a getter method getfname() to get the name of the Student,
  2. a setter method setfname() to set the name of the Student,
  3. a deleter method delname() to delete the name of the Student.

Now, we set the new property attribute name by calling the property() method.

As shown in the program, referencing s.fname internally calls getfname() as getter, setfname() as setter and delfname() as deleter through the printed output present inside the methods.

@property Decorator

The @property decorator allows us to define properties easily without calling a property() function manually. Before studying about the @property decorator, let’s understand what is a decorator.

#What is a decorator

In Python, a function is a first-order object. It means that it can be passed as an argument to another function.

It is also possible to define the function inside another function. Such a function is called the nested function. Moreover, the function can return another function.

A decorator is a function that receives another function as an argument. The behavior of an argument function is extended by a decorator without actually modifying it. So, that is it for a decorator.

@decorator Example

Instead of using a property() method, you can use the Python decorator @property to assign a getter, setter, and deleter. See the following code.

# app.py

class Student:
    def __init__(self, fname):
        self._fname = fname

    @property
    def fname(self):
        print('Getting fname')
        return self._fname

    @fname.setter
    def fname(self, value):
        print('Setting fname to ' + value)
        self._fname = value

    @fname.deleter
    def fname(self):
        print('Deleting fname')
        del self._fname

s = Student('Enola')
print('The fname is:', s.fname)

s.fname = 'Millie'

del s.fname

See the output.

➜  pyt python3 app.py
Getting fname
The fname is: Enola
Setting fname to Millie
Deleting fname
➜  pyt

Here, instead of using a property() method, we’ve used the @property decorator.

First, we specify that fname() method is also an attribute of Student. It is done by using the @property before the getter method, as shown in the program.

Next, we use an attribute name to specify the setter and the deleter.

This is done by using @<name-of-attribute>.setter (@fname.setter) for setter method and @<name-of-attribute>.deleter (@fname.deleter) for deleter method.

Notice, we’ve used the same method fname() with different definitions for defining the getter, setter, and deleter.

Now, whenever we use s.fname, it internally calls the appropriate getter, setter, and deleter as shown by the printed output present inside the method.

Finally, Python property() Example | property() Function In Python is over.

The post Python property() Example | property() Function In Python appeared first on AppDividend.

]]>
https://appdividend.com/2019/08/20/python-property-example-property-function-in-python/feed/ 0
Python open() Example | File open() Function In Python https://appdividend.com/2019/08/20/python-open-example-file-open-function-in-python/ https://appdividend.com/2019/08/20/python-open-example-file-open-function-in-python/#respond Tue, 20 Aug 2019 10:29:05 +0000 http://localhost/wordpress/?p=10784 Python open() Example | File open() Function In Python

Python open() Example | File open() Function In Python is today’s topic. The open() function opens the file and returns it as a file object. It is used in the file handling process. Python open() function returns the file object which can be used to read, write, and modify the file. If a file is not found, […]

The post Python open() Example | File open() Function In Python appeared first on AppDividend.

]]>
Python open() Example | File open() Function In Python

Python open() Example | File open() Function In Python is today’s topic. The open() function opens the file and returns it as a file object. It is used in the file handling process. Python open() function returns the file object which can be used to read, write, and modify the file. If a file is not found, then it raises FileNotFoundError exception.

Python open() Example

File handling in Python requires no importing of modules. Python open() is built-in function.

The syntax of the open() function is following.

open(file, mode)
Parameter Description
file The path and name of a file.
mode The string, define which mode you want to open the file in:

“r” – Read – Default value. Opens the file for reading, error if the file does not exist.

“a” – Append – Opens the file for appending, creates the file if it does not exist.

“w” – Write – Opens the file for writing, creates a file if it does not exist.

“x” – Create – Creates a specified file, returns an error if the file exists.

Also, you can specify if a file should be handled as binary or text mode.

“t” – Text – Default value. Text mode.

“b” – Binary – Binary mode (e.g. images).

 

#How to open a file in Python

Let’s create app.txt file in the same directory as our app.py file.

Now, inside the app.py file, write the following code.

f = open("app.txt")
print(f)

See the output.

➜  pyt python3 app.py
<_io.TextIOWrapper name='app.txt' mode='r' encoding='UTF-8'>
➜  pyt

Since the mode is omitted, the file is opened in ‘r’ mode; it opens for reading.

#Providing mode to open()

Let’s pass the ‘r’ mode as a parameter and see the output.

# app.py

f = open("app.txt", 'r')
print(f)

It will give us the same output as above.

Python has an encoding system which is platform dependent. Hence, it’s recommended to specify an encoding type if you are working in the text mode.

f = open("path_to_file", mode = 'r', encoding='utf-8')

Let’s pass the ‘w’ mode. The ‘w‘ stands for writing mode.

f = open("app.txt", 'w')
print(f)

See the output.

➜  pyt python3 app.py
<_io.TextIOWrapper name='app.txt' mode='w' encoding='UTF-8'>
➜  pyt

Let’s pass the ‘a’ mode. The ‘a’ stands for append mode.

f = open("app.txt", 'a')
print(f)

See the output.

➜  pyt python3 app.py
<_io.TextIOWrapper name='app.txt' mode='a' encoding='UTF-8'>
➜  pyt

#Close file

We can close the opened file using the close() function.

# app.py

f = open("app.txt", 'r')
print('File is opened')
f.close()
print('File is closed')

See the output.

➜  pyt python3 app.py
File is opened
File is closed
➜  pyt

Finally, Python open() Example | File open() Function In Python is over.

The post Python open() Example | File open() Function In Python appeared first on AppDividend.

]]>
https://appdividend.com/2019/08/20/python-open-example-file-open-function-in-python/feed/ 0
Python pow() Example | pow() Function In Python Tutorial https://appdividend.com/2019/08/20/python-pow-example-pow-function-in-python-tutorial/ https://appdividend.com/2019/08/20/python-pow-example-pow-function-in-python-tutorial/#respond Tue, 20 Aug 2019 09:35:11 +0000 http://localhost/wordpress/?p=10772 Python pow() Example | pow() Function In Python Tutorial

Python pow() Example | pow() Function In Python Tutorial is today’s topic. The pow() method returns x to the power of y. If the third argument (z) is given, it returns x to the power of y modulus z, i.e., pow(x, y) % z. The pow() function returns a value of x to power of […]

The post Python pow() Example | pow() Function In Python Tutorial appeared first on AppDividend.

]]>
Python pow() Example | pow() Function In Python Tutorial

Python pow() Example | pow() Function In Python Tutorial is today’s topic. The pow() method returns x to the power of y. If the third argument (z) is given, it returns x to the power of y modulus z, i.e., pow(x, y) % z. The pow() function returns a value of x to power of y (xy). If the third parameter is present, it returns x to the power of y, modulus z.

Python pow() Example

The pow() function computes a**b. This function first converts its arguments into float and then computes the power.

The syntax of the pow() method is following.

pow(a, b, c)
Parameter Description
a A number, the base
b A number, the exponent
c Optional. A number, the modulus

 

  1. If only two arguments are provided, then a to the power of b is returned. In this case, the arguments can be integers, floats, and complex numbers. The two-argument form of pow(a, b) is equivalent to using the power operator: a**b.
  2. If three arguments are provided, then a to the power b, modulo c is returned. It’s computed more efficiently than using pow(a, b) % c.
  3. If c is present, a and b must be of integer types, and b must be non-negative.

See the following example.

# app.py

data = pow(4, 3)
print(data)

See the output.

➜  pyt python3 app.py
64
➜  pyt

Let’s pass the third parameter and see the output.

# app.py

data = pow(4, 3, 10)
print(data)

So, what is does is first 4*4*4, which is 64 and then 64%10, which is 4. That is why it will give us output 4.

➜  pyt python3 app.py
4
➜  pyt

#Python pow() with floats

See the following code example of floats.

# app.py

print(pow(11, 2.0))

print(pow(21.0, 2))

See the output.

➜  pyt python3 app.py
121.0
441.0
➜  pyt

#Python pow() with different format integers

See the following code example.

# app.py

print(pow(0b11, 2)) 
print(pow(0b11, 2, 2))

print(pow(0o11, 2))
print(pow(0o11, 3, 2))

print(pow(0xF, 2))
print(pow(0xF, 3, 2))

See the following output.

➜  pyt python3 app.py
9
1
81
1
225
1
➜  pyt

#pow() with complex numbers

See the following code.

# app.py

print(pow(11 + 21j, 2))

See the output.

➜  pyt python3 app.py
(-320+462j)
➜  pyt

#pow() vs math.pow()

Python math module also has the pow() function, but the built-in function is more powerful because we can perform the modulo operation too after power.

Also, we don’t need to import the math module for a single functionality.

So, it is preferable to use Python built-in pow() function and not the math.pow() function.

The math.pow() always returns float values. So if you, for some reason, want to make sure you get float as a result back, then math.pow() will provide that benefit to the user.

Finally, Python pow() Example | pow() Function In Python Tutorial is over.

The post Python pow() Example | pow() Function In Python Tutorial appeared first on AppDividend.

]]>
https://appdividend.com/2019/08/20/python-pow-example-pow-function-in-python-tutorial/feed/ 0
Python iter() Example | iter() Function In Python Tutorial https://appdividend.com/2019/08/17/python-iter-example-iter-function-in-python-tutorial/ https://appdividend.com/2019/08/17/python-iter-example-iter-function-in-python-tutorial/#respond Sat, 17 Aug 2019 11:28:20 +0000 http://localhost/wordpress/?p=10709 Python iter() Example | iter() Function In Python Tutorial

Python iter() Example | iter() Function In Python Tutorial is today’s topic. In python, the iter() method is used to convert an iterable to an iterator. It offers another way to iterate the container i.e access its elements. iter() uses next() for obtaining values. The iter() method returns the iterator for the provided object. The […]

The post Python iter() Example | iter() Function In Python Tutorial appeared first on AppDividend.

]]>
Python iter() Example | iter() Function In Python Tutorial

Python iter() Example | iter() Function In Python Tutorial is today’s topic. In python, the iter() method is used to convert an iterable to an iterator. It offers another way to iterate the container i.e access its elements. iter() uses next() for obtaining values. The iter() method returns the iterator for the provided object. The iter() method creates tje object which can be iterated one item at a time.

Python iter() Example

These objects are useful when we coupled with the loops like for loopwhile loop.

Iteration object remembers an iteration count via internal count variable.

Once the iteration is finished, it raises the StopIteration exception and iteration count cannot be
reassigned to 0.

Therefore, it can be used to traverse a container just once.

The syntax of the iter() method is following.

iter(object, sentinel)

object – It is an object whose iterator has to be created (can be setstuples, lists, dictionaries, etc.)

sentinel (Optional) – It is the special value that is used to represent the end of a sequence.

See the following example.

# app.py

data = iter(['millie', 'finn', 'gaten', 'caleb'])

print(next(data))
print(next(data))
print(next(data))
print(next(data))

In the above code, we have passed a list to the iter() function and then print the item one by one using the Python next() function.

#How iter() works for custom objects

Okay, now let’s define the custom object and then iterate that object using next() function.

# app.py

class Display:
    def __init__(self, count):
        self.count = count

    def __iter__(self):
        self.data = 0
        return self

    def __next__(self):
        if(self.data >= self.count):
            raise StopIteration
        self.data += 1
        return self.data

num = Display(2)

printData = iter(num)

# prints '1'
print(next(printData))

# prints '2'
print(next(printData))

# raises StopIteration
print(next(printData))

See the output.

➜  pyt python3 app.py
1
2
Traceback (most recent call last):
  File "app.py", line 26, in <module>
    print(next(printData))
  File "app.py", line 11, in __next__
    raise StopIteration
StopIteration
➜  pyt

Iteration is a generic term for taking each element of something, one after another. Any time you use the loop, explicit or implicit, to go over the group of items, that is an iteration.

In Python, iterable and iterator have precise meanings.

The iterable is an object that has an __iter__ method which returns an iterator, or which describes the __getitem__ method that can take the sequential indexes starting from zero (and raises an IndexError when the indexes are no longer valid).

So the iterable is an object that you can get an iterator from.

Iterator is an object with a next (Python 2) or __next__ (Python 3) method.

Whenever you practice a for loop, or map, or a list comprehension, etc. in Python, the next() method is called automatically to get all item from an iterator, therefore going through the process of iteration.

Finally, Python iter() Example | iter() Function In Python Tutorial is over.

The post Python iter() Example | iter() Function In Python Tutorial appeared first on AppDividend.

]]>
https://appdividend.com/2019/08/17/python-iter-example-iter-function-in-python-tutorial/feed/ 0
Python next() Example | next() Function In Python https://appdividend.com/2019/08/17/python-next-example-next-function-in-python/ https://appdividend.com/2019/08/17/python-next-example-next-function-in-python/#respond Sat, 17 Aug 2019 10:51:29 +0000 http://localhost/wordpress/?p=10699 Python next() Example | next() Function In Python

Python next() Example | next() Function In Python is today’s topic. The next() function returns the next item from an iterator. The next() function is used to fetch the next item from the collection. It takes two arguments an iterator and a default value and returns an element. This method calls on iterator and throws […]

The post Python next() Example | next() Function In Python appeared first on AppDividend.

]]>
Python next() Example | next() Function In Python

Python next() Example | next() Function In Python is today’s topic. The next() function returns the next item from an iterator. The next() function is used to fetch the next item from the collection. It takes two arguments an iterator and a default value and returns an element. This method calls on iterator and throws an error if no item is present. To avoid the error, we can set a default value.

Python next()

You can add a default return value, to return if the iterable has reached to its end.

The syntax of next() is following.

next(iterator, default)
  1. iterator: The next() retrieves next item from the iterator.
  2. default (optional): The default value is returned if the iterator is exhausted (no items left).

It returns an item from the collection.

Let’s see some examples of next() function to understand it’s functionality.

# app.py

data = ['eleven', 'mike', 'dustin', 'caleb', 'noah']

dataIterator = iter(data)

print(next(dataIterator))
print(next(dataIterator))
print(next(dataIterator))
print(next(dataIterator))
print(next(dataIterator))

See the following output.

➜  pyt python3 app.py
eleven
mike
dustin
caleb
noah
➜  pyt

We got an error from the last statement in the above program if we tried to get the next element when no next element was available (iterator is exhausted).

In such cases, you can give the default value as the second parameter.

#Iterator With Default Value

See the following example in which, we define a Python list with only two elements, and then we use the next() function to add three more items and print in the output.

# app.py

data = ['eleven', 'mike']

dataIterator = iter(data)

print(next(dataIterator))
print(next(dataIterator))
print(next(dataIterator, 'caleb'))
print(next(dataIterator, 'dustin'))
print(next(dataIterator, 'noah'))

See the following output.

➜  pyt python3 app.py
eleven
mike
caleb
dustin
noah
➜  pyt

#Python Tuple with next() method

Let’s define Python Tuple and apply the next() function on that tuple iterator and see the output.

# app.py

data = ('eleven', 'mike')

dataIterator = iter(data)

print(next(dataIterator))
print(next(dataIterator))

See the output.

➜  pyt python3 app.py
eleven
mike
➜  pyt

#Python next() Function with Python iter() Function

We have used the Python iter() function used to convert an iterable to an iterator. 

See the following code example.

# app.py

data = iter(['millie', 'finn'])

dataIterator = iter(data)

print(next(dataIterator))
print(next(dataIterator))

See the output.

➜  pyt python3 app.py
millie
finn
➜  pyt

To note here that For loop is the better choice when printing the contents of the list than next().

The next() is the utility function for printing the components of the container of iter type.

Its usage is when the size of the container is not known, or we need to give a prompt when the list/iterator has exhausted.

The method next() is used when the file is used as the iterator, typically in the loop, the next() method is called repeatedly. This method returns a next input line or raises StopIteration when the EOF is hit.

Combining the next() method with other file methods like readline() does not work right. However, using the seek() to reposition the file to an absolute position will flush the read-ahead buffer.

Finally, Python next() Example | next() Function In Python is over.

The post Python next() Example | next() Function In Python appeared first on AppDividend.

]]>
https://appdividend.com/2019/08/17/python-next-example-next-function-in-python/feed/ 0
Null Object In Python Example | Python Null Value Tutorial https://appdividend.com/2019/08/16/null-object-in-python-example-python-null-value-tutorial/ https://appdividend.com/2019/08/16/null-object-in-python-example-python-null-value-tutorial/#respond Fri, 16 Aug 2019 07:15:11 +0000 http://localhost/wordpress/?p=10628 Null Object In Python Example | Python Null Value Tutorial

Null Object In Python Example | Python Null Value Tutorial is today’s topic. In Python, a ‘null‘ object is the singleton None. There’s no null value in Python; instead, there’s None. As stated already, the most accurate way to test that something has been given None as the value is to use the is identity operator, […]

The post Null Object In Python Example | Python Null Value Tutorial appeared first on AppDividend.

]]>
Null Object In Python Example | Python Null Value Tutorial

Null Object In Python Example | Python Null Value Tutorial is today’s topic. In Python, a ‘null‘ object is the singleton None. There’s no null value in Python; instead, there’s None.

As stated already, the most accurate way to test that something has been given None as the value is to use the is identity operator, which tests that two variables refer to the same object.

In other programming languages, for example, this is how you may create a null variable in PHP and Java.

#In Java

myVariable = null;

#In PHP

$myVariable = NULL;

If you need to evaluate a variable in the if condition, you may check this as follows in Java:

if(myVariable == null) {
  System.out.println(”Some output”);
}

How to use the ‘None’ in Python. I will use it in the if statement and a few compound data types.

How to test a variable is null in Python

As stated already, the most accurate way to test the something has been given None as the value is to use the is identity operator, which tests that two variables refer to the same object.

In Python, to represent an absence of the value, you can use a None value (types.NoneType.None) for objects and “” (or len() == 0) for strings.

Regarding the difference between “==” and “is” testing for object identity using “==” should be sufficient.

However, since the operation “is” is defined as an object identity operation, it is probably more correct to use it, rather than “==”. Not sure if there is even the speed difference.

#Python is Operator

See the following code.

# app.py

eleven = None
print(eleven is None)

See the following output.

➜  pyt python3 app.py
True
➜  pyt

#Check Using if…else condition

We can write the following code if we want to check if the value is None.

# app.py

value = None

if value is None:
    print('The value is null')
else:
    print('The value is not null')

In the above example, we have defined the variable called value and assign the None value.

Then, we have used the if…else condition to check the None value and if it does then return print statement with “The value is null.”

We can use the following code if we want to check if the name exists.

try:
    val
except NameError:
    pass  # val does not exist at all

#There is only be one None

The None is the built-in constant, as soon as you start Python, whether in module, class, or function. The NonType, by contrast, is not, you’d need to get a reference to it first by querying None for its class.

>>> NoneType
NameError: name 'NoneType' is not defined
>>> type(None)
NoneType

None cannot be overwritten.

Before Python 2.4, it was possible to reassign None, but not anymore. Not even as the class attribute or in the confines of a function.

#Testing if a value is None

Why do this

value is None

rather than

value==None

The first is equivalent to:

id(value)==id(None)

Whereas the expression value==None is applied like this

value.__eq(None)__

if the value is None, then you’ll get what you expected.

>>> nothing = function_that_does_nothing()
>>> nothing.__eq__(None)
True

The None has a distinctive status in Python language. It’s a preferred baseline value because many algorithms treat it as an exceptional value.

In such scenarios, it can be used as the flag to signal that the condition requires some special handling such as the setting of the default value.

The post Null Object In Python Example | Python Null Value Tutorial appeared first on AppDividend.

]]>
https://appdividend.com/2019/08/16/null-object-in-python-example-python-null-value-tutorial/feed/ 0
Python id() Example | id() Function In Python Tutorial https://appdividend.com/2019/08/15/python-id-example-id-function-in-python-tutorial/ https://appdividend.com/2019/08/15/python-id-example-id-function-in-python-tutorial/#respond Thu, 15 Aug 2019 04:49:49 +0000 http://localhost/wordpress/?p=10618 Python id() Example | id() Function In Python Tutorial

Python id() Example | id() Function In Python Tutorial is today’s topic. The identity of the object is an integer, which is guaranteed to be the unique and constant for this object during its lifetime. The id() is an inbuilt function in Python. Two objects with the non-overlapping lifetimes may have the same id() value. […]

The post Python id() Example | id() Function In Python Tutorial appeared first on AppDividend.

]]>
Python id() Example | id() Function In Python Tutorial

Python id() Example | id() Function In Python Tutorial is today’s topic. The identity of the object is an integer, which is guaranteed to be the unique and constant for this object during its lifetime. The id() is an inbuilt function in Python. Two objects with the non-overlapping lifetimes may have the same id() value. In CPython implementation, it is an address of the object in memory.

Python id() Example

Python cache is the id() value of commonly used the data types, such as the stringintegertuples, etc.

So you might find that multiple variables refer to a same object and have the same id() value if their values are same. The syntax of Python id() function is following.

id(object)

The id() function takes the single parameter object.

# app.py

# integers
a = 11
b = 21
c = 19
d = 18

print(id(a))
print(id(b))
print(id(c))
print(id(d))

See the following output.

➜  pyt python3 app.py
4304849600
4304849920
4304849856
4304849824
➜  pyt

The id() function returns the identity of the object. This is an integer which is unique for the given object and remains constant during its lifetime.

Let’s see if we get similar behavior with string and tuples too.

# app.py

# tuples
t = ('Eleven', 'Mike')
print(id(t))

t1 = ('Dustin', 'Suzie')
print(id(t1))

# strings
s1 = 'Jane'
s2 = 'Jane'
print(id(s1))
print(id(s2))

See the following output.

➜  pyt python3 app.py
4358154504
4358154440
4356016256
4356016256
➜  pyt

As we can see, a function accepts the single parameter and is used to return the identity of the object. The identity has to be the unique and constant for this object during the lifetime. 

Two objects with an non-overlapping lifetimes may have the same id() value.

Python cache the strings and tuple objects and use them to save the memory space.

We know that dictionary is not immutable, So, if the id() function is different for different dictionaries even if the elements are same.

# app.py

a1 = {"age": 26, "year": 1993}
a2 = {"age": 26, "year": 1993}
print(id(a1))
print(id(a2))

See the following output.

➜  pyt python3 app.py
4345653144
4345653216
➜  pyt

The dict objects are returning different id() value, and there seems no caching here.

#Python id() for custom object

See the following example.

# app.py

class Student:
    data = 0


e1 = Student()
e2 = Student()

print(id(e1))
print(id(e2))

See the following output.

➜  pyt python3 app.py
4349781216
4349781328
➜  pyt

Python id() value is the guaranteed to be unique and constant for the object. We can use this to make sure that two objects are referring to the same object in memory or not.

The post Python id() Example | id() Function In Python Tutorial appeared first on AppDividend.

]]>
https://appdividend.com/2019/08/15/python-id-example-id-function-in-python-tutorial/feed/ 0