Python – AppDividend https://appdividend.com Latest Code Tutorials Tue, 21 Jan 2020 11:42:14 +0000 en-US hourly 1 https://appdividend.com/wp-content/uploads/2017/08/cropped-ApDivi-32x32.png Python – AppDividend https://appdividend.com 32 32 Python List Contains | How To Check If Item Exists In List https://appdividend.com/2020/01/21/python-list-contains-how-to-check-if-item-exists-in-list/ https://appdividend.com/2020/01/21/python-list-contains-how-to-check-if-item-exists-in-list/#respond Tue, 21 Jan 2020 11:40:15 +0000 http://localhost/wordpress/?p=13854 Python List Contains | How To Check If Item Exists In List

The in operator is an inbuilt operator that checks Python list contains a specific item or not. Also, we can check if item exists on the list or not using the list.count() function. Python not in inverse operator is also used to check if the item exists in the list or not. Python list contains Python […]

The post Python List Contains | How To Check If Item Exists In List appeared first on AppDividend.

]]>
Python List Contains | How To Check If Item Exists In List

The in operator is an inbuilt operator that checks Python list contains a specific item or not. Also, we can check if item exists on the list or not using the list.count() function. Python not in inverse operator is also used to check if the item exists in the list or not.

Python list contains

Python list is an essential container as if stores elements of all the datatypes as a collection. Python in is the most convenient way to check if an item exists on the list or not.

This approach returns True if an item exists in the list and False if an item does not exist in the list. The list need not be sorted to practice this approach of checking.

Check if item exists in list using Python in Operator

See the following syntax of Python in.

item in List

It will return True if an item exists in the list else returns False.

# app.py

listA = ['Stranger Things', 'S Education', 'Game of Thrones']

if 'S Eductation' in listA:
    print("Yes, 'S Eductation' found in List : ", listA)

Output

python3 app.py
Yes, 'S Eductation' found in List :  ['Stranger Things', 'S Education', 'Game of Thrones']

Let’s take an example in which we do not find an item on the list.

# app.py

listA = ['Stranger Things', 'S Education', 'Game of Thrones']

if 'Dark' in listA:
    print("Yes, 'S Eductation' found in List : ", listA)
else:
    print("Nope, 'Dark' not found in the list")

Output

python3 app.py
Nope, 'Dark' Not found in the list

The list does not contain the dark element, so it returns False and else block executes.

Check if item exists in list using List comprehension

See the following code.

# app.py

data_string = "The last season of Game of Thrones was not good"

listA = ['Stranger Things', 'S Education', 'Game of Thrones']

print("The original string : " + data_string)

print("The original list : " + str(listA))

res = [ele for ele in listA if(ele in data_string)]

print("Does string contain any list element : " + str(bool(res)))

Output

python3 app.py
The original string : The last season of Game of Thrones was not good
The original list : ['Stranger Things', 'S Education', 'Game of Thrones']
Does string contain any list element : True

List comprehensions provide a concise way to create the lists.

It consists of brackets containing the expression followed by a for clause, then zero or more for or if clauses. The expressions can be anything, meaning you can put in all types of objects in lists.

The result will be the new list resulting from evaluating an expression in the context of the for and if clauses that follow it.

In our example, we check for the list and also with string items if we can find a match, and return true.

Let’s see if the string contains the word which does not exist in an item of the list.

# app.py

data_string = "The last season of BoJack Horseman was good"

# initializing test list
listA = ['Stranger Things', 'S Education', 'Game of Thrones']

# printing original string
print("The original string : " + data_string)

# printing original list
print("The original list : " + str(listA))

# using list comprehension
# checking if string contains list element
res = [ele for ele in listA if(ele in data_string)]

# print result
print("Does string contain any list element : " + str(bool(res)))

Output

python3 app.py
The original string: The last season of BoJack Horseman was good
The original list : ['Stranger Things', 'S Education', 'Game of Thrones']
Does string contain any list element: False

Check if element exists in list using list.count()

The syntax of the list.count() function is following.

list.count(elem)

Python List count(item) method returns the occurrence count of the given element in the list. If it’s greater than 0, it means a given item exists in the list.

# app.py

listA = ['Stranger Things', 'S Education', 'Game of Thrones']

if listA.count('Stranger Things') > 0:
    print("Yupp, 'Stranger Things' found in List : ", listA)

Output

python3 app.py
Yupp, 'Stranger Things' found in List :  ['Stranger Things', 'S Education', 'Game of Thrones']

Check if an element exists in the list using any()

Using Python any() function is the most classical way in which you can perform this task and also efficiently. The any() function checks for a match in a string with a match of each element of the list.

# app.py

data_string = "The last season of Game of Thrones was not good"

listA = ['Stranger Things', 'S Education', 'Game of Thrones']

print("The original string : " + data_string)

print("The original list : " + str(listA))

res = any(item in data_string for item in listA)

print("Does string contain 'Game of Thrones' list element: " + str(res))

Output

python3 app.py
The original string : The last season of Game of Thrones was not good
The original list : ['Stranger Things', 'S Education', 'Game of Thrones']
Does string contain 'Game of Thrones' list element: True

From the output, Game of Thrones exists in the list.

Conclusion

There are many approaches you can use to determine whether an item exists in the list or not. We have seen the following ways.

  1. Using Python “in” operator
  2. Using Python list comprehension
  3. Using list.count() method
  4. Using Python any() function

Finally, Python list contains example is over.

The post Python List Contains | How To Check If Item Exists In List appeared first on AppDividend.

]]>
https://appdividend.com/2020/01/21/python-list-contains-how-to-check-if-item-exists-in-list/feed/ 0
How To Convert Datetime To String In Python https://appdividend.com/2020/01/21/how-to-convert-datetime-to-string-in-python/ https://appdividend.com/2020/01/21/how-to-convert-datetime-to-string-in-python/#respond Tue, 21 Jan 2020 09:22:43 +0000 http://localhost/wordpress/?p=13836 How To Convert Datetime To String In Python

Python strftime() is an inbuilt datetime module function that converts datetime to string. The strftime() method returns the string representing date and time using date, time, or datetime object. To convert datetime to time, first, you need to import a datetime module in the python program, and then we can use the strftime() method. Python: How to convert datetime […]

The post How To Convert Datetime To String In Python appeared first on AppDividend.

]]>
How To Convert Datetime To String In Python

Python strftime() is an inbuilt datetime module function that converts datetime to string. The strftime() method returns the string representing date and time using date, time, or datetime object. To convert datetime to time, first, you need to import a datetime module in the python program, and then we can use the strftime() method.

Python: How to convert datetime to string

Python’s datetime class provides a member function called strftime() to create a string representation of data in the object. The datetime module supplies the classes for manipulating dates and times.

While the date and time arithmetic is supported, the focus of the implementation is on efficient attribute extraction for output formatting and manipulation.

datetime.strftime()

The following program converts a datetime object containing the current date and time to different string formats.

See the following syntax.

datetime.strftime(Format_String)

See the following code.

# app.py

from datetime import datetime

# current date and time
curDT = datetime.now()

# current day
day = curDT.strftime("%d")
print("day:", day)

# current month
month = curDT.strftime("%m")
print("month:", month)

# current year
year = curDT.strftime("%Y")
print("year:", year)

# current time
time = curDT.strftime("%H:%M:%S")
print("time:", time)

# current date and time
date_time = curDT.strftime("%m/%d/%Y, %H:%M:%S")
print("date and time:", date_time)

Output

pyt python3 app.py
day: 21
month: 01
year: 2020
time: 13:31:14
date and time: 01/21/2020, 13:31:14

Here, day, month, year, time, and date_time are strings, whereas now is a datetime object.

In the above program, %d, %m, %Y, etc. are format codes. The strftime() function takes one or more format codes as the argument and returns the formatted string based on it.

We imported the datetime class from the datetime module. It’s because the object of the datetime class can access the strftime() method.

#Python Date to String

Let’s convert the only date to string in Python.

# app.py

from datetime import datetime

# current date and time
curDTObj = datetime.now()

# current date
dateStr = curDTObj.strftime("%d %b, %Y")
print("dateStr:", date)

Output

python3 app.py
date: 21 Jan, 2020

In the above example, we have converted the date part of datetime object to string.

#Python Time to String

Let’s convert the only time to string in Python.

# app.py

from datetime import datetime

# current date and time
curDTObj = datetime.now()

# current time
timeStr = curDTObj.strftime("%H:%M:%S.%f")
print("Time:", timeStr)

Output

python3 app.py
Time: 14:30:27.650890

In the above example, we have converted the time part of datetime object to string.

#Python: How to Convert Timestamp to String

Let’s say we have the following timestamp.

1579596626.421213

Now, we need to convert the above timestamp to string.

For that, we can use the datetime.fromtimestamp() function.

datetime.fromtimestamp()

The fromtimestamp() function takes timestamp as a parameter and returns the datetime object, and then we can use the strftime() function to extract a day, month, year from the datetime object.

See the following code.

# app.py

from datetime import datetime

timestamp = 1579596626.421213

date_time = datetime.fromtimestamp(timestamp)
print("Date time object:", date_time)

fm_dt = date_time.strftime("%d/%m/%Y, %H:%M:%S")
print("Formatted Date Time:", fm_dt)

Output

python3 app.py
Date time object: 2020-01-21 14:20:26.421213
Formatted Date Time: 21/01/2020, 14:20:26

#Python: How to convert datetime to text

In this example, we will see how we can convert datetime to more readable text in Python.

See the following code.

# app.py

from datetime import datetime

# current date and time
curDTObj = datetime.now()

# current datetime
datetimeStr = curDTObj.strftime("Today is %d %B of %Y and the week day is %A at %I:%M %p")
print("Readable Text of Current Date Time:", datetimeStr)

Output

python3 app.py
Readable Text of Current Date Time: Today is 21 January of 2020 and the week day is Tuesday at 02:35 PM

#List of the date-time format in Python

Format Codes Description Example
%d Day of the month as a zero-padded decimal number 01, 02, 03, 04 …, 31
%a Weekday as an abbreviated name Sun, Mon, …, Sat
%A Weekday as the full name Sunday, Monday, …, Saturday
%m Month as the zero-padded decimal number 01, 02, 03, 04, 05,…, 12
%b Month as an abbreviated name Jan, Feb, Mar,…, Dec
%B Month as full name January, February, …, December
%y Year without century as the zero-padded decimal number 00, 01, 02, 03, …, 99
%Y Year with century as the decimal number 0001, …, 2018, …, 9999
%H Hour (24-hour clock) as the zero-padded decimal number 01, 02, 03, 04, 05 …, 23
%M Minute as a zero-padded decimal number 01, 02, 03, 04, 05 …, 59
%S Second as a zero-padded decimal number 01, 02, 03, 04, 05 …, 59
%f Microsecond as the decimal number, zero-padded on the left 000000, 000001, …, 999999
%I Hour (12-hour clock) as a zero-padded decimal number 01, 02, 03, 04, 05 …, 12
%p Locale’s equivalent of either AM or PM AM, PM
%j Day of the year as a zero-padded decimal number 01, 02, 03, 04, 05 …, 366

 

Conclusion

If you want to convert Python date or time to string or text format, the first thing you need to do is create a datetime object, and then you have access to different methods as per your requirement.

I hope this article has solved your issue regarding how to convert datetime to string in Python.

See also

Python Date Format

Python Datetime example

The post How To Convert Datetime To String In Python appeared first on AppDividend.

]]>
https://appdividend.com/2020/01/21/how-to-convert-datetime-to-string-in-python/feed/ 0
Python: Remove Item From Dictionary Example https://appdividend.com/2020/01/20/python-remove-item-from-dictionary-example/ https://appdividend.com/2020/01/20/python-remove-item-from-dictionary-example/#respond Mon, 20 Jan 2020 12:33:32 +0000 http://localhost/wordpress/?p=13820 Python Remove Item From Dictionary Example

To remove item from dictionary in Python, you can use Python dict.pop() method or del operator to remove the key. In this article, we will discuss different ways to delete a key from a dictionary in python. Python remove item from dictionary Python Dictionary is used in various practical applications such as day-day programming, web […]

The post Python: Remove Item From Dictionary Example appeared first on AppDividend.

]]>
Python Remove Item From Dictionary Example

To remove item from dictionary in Python, you can use Python dict.pop() method or del operator to remove the key. In this article, we will discuss different ways to delete a key from a dictionary in python.

Python remove item from dictionary

Python Dictionary is used in various practical applications such as day-day programming, web development, and AI/ML programming, data science application as well, making it a useful container overall.

Remove a key from dictionary using del

Python del keyword can be used to inplace delete the key that is present in the dictionary. One drawback that can be thought of using this is that it raises an exception if the key is not found, and hence non-existence of key has to be handled.

The syntax for Python del() is the following.

del d[key]

The del statement removes the given item from the dictionary. If the given key is not present in the dictionary, then it will throw KeyError.

See the following code.

# app.py

netflix_dict = {"Stranger Things" : 11, "You" : 3, "BoJack Horseman" : 21} 
  
# Printing dictionary before removal 
print ("The dictionary before performing remove is : " + str(netflix_dict)) 
  
# Using del to remove a dict 
# removes You 
del netflix_dict['You'] 
  
# Printing dictionary after removal 
print ("The dictionary after remove is : " + str(netflix_dict))

Output

python3 app.py
The dictionary before performing remove is : {'Staranger Things': 11, 'You': 3, 'BoJack Horseman': 21}
The dictionary after remove is : {'Staranger Things': 11, 'BoJack Horseman': 21}

In the above program, we have removed the element whose key is “You” using the del operator.

Let’s see another scenario where the key does not exist in the dictionary and then try to remove the element.

# app.py

netflix_dict = {"Stranger Things" : 11, "You" : 3, "BoJack Horseman" : 21} 
  
# Printing dictionary before removal 
print ("The dictionary before performing remove is : " + str(netflix_dict)) 
  
# Using del to remove a dict 
# try to removes Black Mirror 
del netflix_dict['Black Mirror'] 
  
# Printing dictionary after removal 
print ("The dictionary after remove is : " + str(netflix_dict))

Output

python3 app.py
The dictionary before performing remove is : {'Staranger Things': 11, 'You': 3, 'BoJack Horseman': 21}
Traceback (most recent call last):
  File "app.py", line 8, in <module>
    del netflix_dict['Black Mirror']
KeyError: 'Black Mirror'

So, we got the KeyError because of the key “Black Mirror” which does not exist in the dictionary.

Deleting a key from a dictionary using del and try/except

We can use try/except mechanism handling if the key is not found, then we catch the exception and show the proper error to the user.

See the following code.

# app.py

netflix_dict = {"Stranger Things" : 11, "You" : 3, "BoJack Horseman" : 21} 
  
# Printing dictionary before removal 
print ("The dictionary before performing remove is : " + str(netflix_dict)) 
  
try:
    del netflix_dict['Black Mirror'] 
except KeyError:
    print("Key 'Black Mirror' not found")
  
# Printing dictionary after removal 
print ("The dictionary after remove is : " + str(netflix_dict))

Output

python3 app.py
The dictionary before performing remove is : {'Staranger Things': 11, 'You': 3, 'BoJack Horseman': 21}
Key 'Black Mirror' not found
The dictionary after remove is : {'Staranger Things': 11, 'You': 3, 'BoJack Horseman': 21}

In the above code, we have written the del code inside try block, and if the key does not found, then it throws an exception, and we except that exception and display the proper error to the user.

One thing to note that the execution of the program did not stop; it continues.

Remove a key from dictionary using dict.pop()

If the key exists in the dictionary, then the dict.pop() removes the item with a given key from the dictionary and returns its value.

If the given key doesn’t exist in the dictionary, then it returns the given Default value.

If the given key doesn’t exist in the dictionary and No Default value is passed to pop() then it will throw the KeyError.

See the following code.

# app.py

netflix_dict = {"Stranger Things" : 11, "You" : 3, "BoJack Horseman" : 21} 
  
# Printing dictionary before removal 
print ("The dictionary before performing remove is : " + str(netflix_dict)) 
  
# Using dict.pop() method to remove a dict 
# removes You 
netflix_dict.pop('You')
  
# Printing dictionary after removal 
print ("The dictionary after remove is : " + str(netflix_dict))

Output

python3 app.py
The dictionary before performing remove is : {'Stranger Things': 11, 'You': 3, 'BoJack Horseman': 21}
The dictionary after remove is : {'Stranger Things': 11, 'BoJack Horseman': 21}

In the above code, we have passed the You as a key parameter to remove that element from the dictionary.

Let’s delete an element that is not present in the dictionary using pop().

# app.py

netflix_dict = {"Stranger Things" : 11, "You" : 3, "BoJack Horseman" : 21} 
  
# Printing dictionary before removal 
print ("The dictionary before performing remove is : " + str(netflix_dict)) 
  
# Using dict.pop() method to remove a dict 
# removes You 
netflix_dict.pop('Black Mirror')
  
# Printing dictionary after removal 
print ("The dictionary after remove is : " + str(netflix_dict))

Output

python3 app.py
The dictionary before performing remove is : {'Stranger Things': 11, 'You': 3, 'BoJack Horseman': 21}
Traceback (most recent call last):
  File "app.py", line 8, in <module>
    netflix_dict.pop('Black Mirror')
KeyError: 'Black Mirror'

So, as expected, it gives the KeyError.

Now, let’s pass the default value in the dict.pop() function’s argument and see the output.

# app.py

netflix_dict = {"Stranger Things": 11, "You": 3, "BoJack Horseman": 21}

# Printing dictionary before removal
print("The dictionary before performing remove is : " + str(netflix_dict))

# Using dict.pop() method to remove a dict
# removes You
removed_item = netflix_dict.pop('Black Mirror', 'Not found')

# Printing dictionary after removal
print(removed_item)

Output

python3 app.py
The dictionary before performing remove is : {'Stranger Things': 11, 'You': 3, 'BoJack Horseman': 21}
Not found

In the above code, we have passed the default value, which is “Not found“. So, the return value from the function dict.pop() would be ‘Not found’.

Deleting key from dictionary using pop() and try/except

Let’s use try/except mechanism to handle the exception.

# app.py

netflix_dict = {"Stranger Things": 11, "You": 3, "BoJack Horseman": 21}

# Printing dictionary before removal
print("The dictionary before performing remove is : " + str(netflix_dict))

# Using dict.pop() method to remove a dict
# removes You
try:
    removed_item = netflix_dict.pop('Black Mirror', 'Not found')
except KeyError:
    print("Key 'Black Mirror' not found")

# Printing dictionary after removal
print(removed_item)

Output

python3 app.py
The dictionary before performing remove is: {'Stranger Things': 11, 'You': 3, 'BoJack Horseman': 21}
Not found

Conclusion

We can remove dictionary items or keys in Python using different approaches like using del statement or using dict.pop() method.

Finally, Python remove item from dictionary example is over.

The post Python: Remove Item From Dictionary Example appeared first on AppDividend.

]]>
https://appdividend.com/2020/01/20/python-remove-item-from-dictionary-example/feed/ 0
Python: List of Files in Directory and Subdirectories https://appdividend.com/2020/01/20/python-list-of-files-in-directory-and-subdirectories/ https://appdividend.com/2020/01/20/python-list-of-files-in-directory-and-subdirectories/#respond Mon, 20 Jan 2020 07:22:07 +0000 http://localhost/wordpress/?p=13794 Python List of Files in Directory and Subdirectories

Python has an OS module that provides the functions to deal with file management. We can list files in directory and subdirectory programmatically in Python using the OS module. In this article, we will discuss the different methods to generate a list of all files in the directory tree. Python: List of Files in Directory […]

The post Python: List of Files in Directory and Subdirectories appeared first on AppDividend.

]]>
Python List of Files in Directory and Subdirectories

Python has an OS module that provides the functions to deal with file management. We can list files in directory and subdirectory programmatically in Python using the OS module. In this article, we will discuss the different methods to generate a list of all files in the directory tree.

Python: List of Files in Directory and Subdirectories

Let’s print the whole files listed in our current working directory.

First, you need to import the os module in your file and then use the os.listdir() function.

Write the following code inside the app.py file.

# app.py

import os

print(os.listdir(path='.'))

Output

python3 app.py
['index.html', 'demo.txt', '.DS_Store', 'person.txt', 'app.json', 'DataScience.ipynb', 
'ads.txt', 'example.http', 'student.csv', 'app.txt', '__pycache__', 'data.csv', 
'app.component.ts', 'data.json', 'help_examples.py', 'MergeSort.java', 'app.sql', 
'NumPy.ipynb', 'TensorFlow.ipynb', 'data.csv.numbers', 'app.py', 
'info.log', '.ipynb_checkpoints', 'SciKit Learn.ipynb', '.vscode', 'app.rs', 'mod.py', 
'output.txt', 'data.txt', 'sample.txt', 'app.cpp']

Get a list of files in directory and subdirectories using os.listdir()

We need to call the os.listdir() function recursively for subdirectories to create a complete list of files in a given directory tree.

See the following code.

# app.py

import os


def getFiles(dirName):
    listOfFile = os.listdir(dirName)
    completeFileList = list()
    for file in listOfFile:
        completePath = os.path.join(dirName, file)
        if os.path.isdir(completePath):
            completeFileList = completeFileList + getFiles(completePath)
        else:
            completeFileList.append(completePath)

    return completeFileList


dirName = '/Users/krunal/desktop/code/pyt'
listOfFiles = getFiles(dirName)
print(listOfFiles)

Output

python3 app.py
['/Users/krunal/desktop/code/pyt/index.html', 
'/Users/krunal/desktop/code/pyt/demo.txt', 
'/Users/krunal/desktop/code/pyt/.DS_Store', 
'/Users/krunal/desktop/code/pyt/person.txt', 
'/Users/krunal/desktop/code/pyt/app.json', 
'/Users/krunal/desktop/code/pyt/DataScience.ipynb', 
'/Users/krunal/desktop/code/pyt/ads.txt', 
'/Users/krunal/desktop/code/pyt/example.http', 
'/Users/krunal/desktop/code/pyt/student.csv', 
'/Users/krunal/desktop/code/pyt/app.txt', 
'/Users/krunal/desktop/code/pyt/__pycache__/help_examples.cpython-36.pyc', 
'/Users/krunal/desktop/code/pyt/__pycache__/mod.cpython-36.pyc', 
'/Users/krunal/desktop/code/pyt/data.csv', 
'/Users/krunal/desktop/code/pyt/app.component.ts', 
'/Users/krunal/desktop/code/pyt/data.json', 
'/Users/krunal/desktop/code/pyt/help_examples.py', 
'/Users/krunal/desktop/code/pyt/MergeSort.java', 
'/Users/krunal/desktop/code/pyt/app.sql', 
'/Users/krunal/desktop/code/pyt/NumPy.ipynb', 
'/Users/krunal/desktop/code/pyt/TensorFlow.ipynb',
 '/Users/krunal/desktop/code/pyt/data.csv.numbers', 
'/Users/krunal/desktop/code/pyt/app.py', 
'/Users/krunal/desktop/code/pyt/info.log', 
'/Users/krunal/desktop/code/pyt/.ipynb_checkpoints/NumPy-checkpoint.ipynb', 
'/Users/krunal/desktop/code/pyt/.ipynb_checkpoints/SciKit Learn-checkpoint.ipynb', 
'/Users/krunal/desktop/code/pyt/.ipynb_checkpoints/DataScience-checkpoint.ipynb', 
'/Users/krunal/desktop/code/pyt/.ipynb_checkpoints/TensorFlow-checkpoint.ipynb', 
'/Users/krunal/desktop/code/pyt/SciKit Learn.ipynb', 
'/Users/krunal/desktop/code/pyt/.vscode/settings.json', 
'/Users/krunal/desktop/code/pyt/app.rs', 
'/Users/krunal/desktop/code/pyt/mod.py', 
'/Users/krunal/desktop/code/pyt/output.txt', 
'/Users/krunal/desktop/code/pyt/data.txt', 
'/Users/krunal/desktop/code/pyt/sample.txt', 
'/Users/krunal/desktop/code/pyt/app.cpp']

In the above code, we have defined a function called getFiles(), which accepts one argument called dirname.

Then we are creating a list and add the complete path of files.

So, it will start iterate over one by one file and add its full path to the list, and in the end, we get our full list of files.

How to get a list of files in directory and subdirectories using os.walk()

The python os module provides a walk() function to iterate over a directory tree.

os.walk(path)

The os.walk() function iterates of the directory tree at giving the path, and for each directory or subdirectory, it returns a tuple containing (<Dir Name>, <List of Sub Dir>,  <List of Files>).

See the following code.

# app.py

import os


dirName = '/Users/krunal/desktop/code/pyt'
listOfFiles = list()
for (dirpath, dirnames, filenames) in os.walk(dirName):
    listOfFiles += [os.path.join(dirpath, file) for file in filenames]
for elem in listOfFiles:
    print(elem)

Output

python3 app.py
/Users/krunal/desktop/code/pyt/index.html
/Users/krunal/desktop/code/pyt/demo.txt
/Users/krunal/desktop/code/pyt/.DS_Store
/Users/krunal/desktop/code/pyt/person.txt
/Users/krunal/desktop/code/pyt/app.json
/Users/krunal/desktop/code/pyt/DataScience.ipynb
/Users/krunal/desktop/code/pyt/ads.txt
/Users/krunal/desktop/code/pyt/example.http
/Users/krunal/desktop/code/pyt/student.csv
/Users/krunal/desktop/code/pyt/app.txt
/Users/krunal/desktop/code/pyt/data.csv
/Users/krunal/desktop/code/pyt/app.component.ts
/Users/krunal/desktop/code/pyt/data.json
/Users/krunal/desktop/code/pyt/help_examples.py
/Users/krunal/desktop/code/pyt/MergeSort.java
/Users/krunal/desktop/code/pyt/app.sql
/Users/krunal/desktop/code/pyt/NumPy.ipynb
/Users/krunal/desktop/code/pyt/TensorFlow.ipynb
/Users/krunal/desktop/code/pyt/data.csv.numbers
/Users/krunal/desktop/code/pyt/app.py
/Users/krunal/desktop/code/pyt/info.log
/Users/krunal/desktop/code/pyt/SciKit Learn.ipynb
/Users/krunal/desktop/code/pyt/app.rs
/Users/krunal/desktop/code/pyt/mod.py
/Users/krunal/desktop/code/pyt/output.txt
/Users/krunal/desktop/code/pyt/data.txt
/Users/krunal/desktop/code/pyt/sample.txt
/Users/krunal/desktop/code/pyt/app.cpp
/Users/krunal/desktop/code/pyt/__pycache__/help_examples.cpython-36.pyc
/Users/krunal/desktop/code/pyt/__pycache__/mod.cpython-36.pyc
/Users/krunal/desktop/code/pyt/.ipynb_checkpoints/NumPy-checkpoint.ipynb
/Users/krunal/desktop/code/pyt/.ipynb_checkpoints/SciKit Learn-checkpoint.ipynb
/Users/krunal/desktop/code/pyt/.ipynb_checkpoints/DataScience-checkpoint.ipynb
/Users/krunal/desktop/code/pyt/.ipynb_checkpoints/TensorFlow-checkpoint.ipynb
/Users/krunal/desktop/code/pyt/.vscode/settings.json

List all the txt files in a specified directory using Glob in Python

See the following code.

# app.py

import glob

dirName = '/Users/krunal/desktop/code/pyt'

files = [f for f in glob.glob(dirName + "**/*.txt", recursive=True)]

for f in files:
    print(f)

Output

python3 app.py
/Users/krunal/desktop/code/pyt/demo.txt
/Users/krunal/desktop/code/pyt/person.txt
/Users/krunal/desktop/code/pyt/ads.txt
/Users/krunal/desktop/code/pyt/app.txt
/Users/krunal/desktop/code/pyt/output.txt
/Users/krunal/desktop/code/pyt/data.txt
/Users/krunal/desktop/code/pyt/sample.txt

In the above example, we have used the list comprehension to get the list of all the files which have .txt extension.

So, in this example, we are getting only text files and not all the files.

List all directories in the specified directory + subdirectories (**)

See the following code.

# app.py

import glob

dirName = '/Users/krunal/desktop/code/pyt'

folders = [f for f in glob.glob(dirName + "**/", recursive=True)]

for f in folders:
    print(f)

Output

python3 app.py
/Users/krunal/desktop/code/pythonenv/
/Users/krunal/desktop/code/pyt/

Conclusion

To list directories, subdirectories, and files, Python has excellent inbuilt support that does the job for you. File management and handling is a day to day operations for any programmers.

In this article, we have seen how to list all the directories, subdirectories, and files using Python os.walk(), blob.blob(), and Python os.listdir() method.

Finally, Python list all files in directory and subdirectories example is over.

See also

How to read file in Python

How to write file in Python

File handling in Python

The post Python: List of Files in Directory and Subdirectories appeared first on AppDividend.

]]>
https://appdividend.com/2020/01/20/python-list-of-files-in-directory-and-subdirectories/feed/ 0
Top 5 Python Online Courses For Beginners In 2020 https://appdividend.com/2020/01/19/top-5-python-online-courses-for-beginners/ https://appdividend.com/2020/01/19/top-5-python-online-courses-for-beginners/#respond Sun, 19 Jan 2020 15:25:31 +0000 http://localhost/wordpress/?p=13773 Top 5 Python Online Courses For Beginners In 2020

In 2020, one Programming language will be everywhere and guess which it is, yes, you guessed right it is a Python. Python is everywhere because of the rise of the fields like Data Science, Artificial Intelligence, and Machine Learning. Python language has every support to make mathematical computations(Numpy, Scikit learn), graphical representations(Matlab) of libraries. Day […]

The post Top 5 Python Online Courses For Beginners In 2020 appeared first on AppDividend.

]]>
Top 5 Python Online Courses For Beginners In 2020

In 2020, one Programming language will be everywhere and guess which it is, yes, you guessed right it is a Python. Python is everywhere because of the rise of the fields like Data Science, Artificial Intelligence, and Machine Learning. Python language has every support to make mathematical computations(Numpy, Scikit learn), graphical representations(Matlab) of libraries.

Day by day python is becoming most used programming language in 2019-20 in the world, mainly because of its simplicity and better exposure to different technical fields like you can create GUI Applications, websites, data science projects, and machine learning models(I am looking at you, Tensorflow).

So, it is like you learn only one programming language and then you can develop any type of application. Also, because of its simplicity, learning & development speed is very fast as compared to another programming languages.

To make a successful career in Computer Science, you must have knowledge of Python, and today I will list the top 5 Python online courses for beginners in 2020.

Top 5 Python Online Courses For Beginners

Here are our top 5 python online courses for 2020.

  1. Complete Python Bootcamp
  2. Python programming Masterclass
  3. Python mega course
  4. Python bible
  5. Python for everybody

Let’s see our first course.

#1: Complete Python Bootcamp: Go from zero to hero in Python 3

It is a comprehensive guide for beginners to master in Python 3.

Jose Portilla creates the courseA well-known tutor in the Python community.

The course has already enrolled over 800,000+ students, and the reviews are great.

The course has 185 lectures(24 hrs).

What you will learn in this course

  • You can Learn Python 3 professionally.
  • You can create games with Python, like Tic Tac Toe and Blackjack!
  • Learn advanced Python features, like the Pythoncollections module, generators, iterators and how to work with timestamps.
  • You can learn Object Oriented Programming with classes!
  • Understand the complex topics, like decorators, tinkter.
  • Understand how to use the Jupyter Notebook and create the .py files.
  • Also get an understanding of how to create GUIs in the Jupyter Notebook system.

Checkout THIS COURSE

#2: Learn Python Programming Masterclass

Tim Buchalka, Jean-Paul Roberts, create the course.

The course has already enrolled over 150,000+ students, and the reviews are great.

It was updated in 2020. So all the latest stuff is there on the course.

The course has 277 lectures(46.6 hrs).

What you will learn in this course

  • Acquire the pre-requisite Python skills to move into specific branches like Machine Learning, Data Science, etc.
  • Add the Python Object-Oriented Programming (OOP) skills to your resume.
  • Understand how to create your Python programs and apply for Python jobs.
  • Learn Python from experienced professional software developers.

CHECK OUT THIS COURSE

#3: Python Mega Course: Build 10 Real World Applications

Ardit Sulce creates the course.

The course has already enrolled over 150,000+ students, and the reviews are great.

It was updated in 2020. So all the latest stuff is there on the course.

The course has 264 lectures(24 hrs).

What you will learn in this course

  • Acquire the pre-requisite Python skills to move into specific branches like Machine Learning, Data Science, etc.
  • Add the Python Object-Oriented Programming (OOP) skills to your resume.
  • Understand how to create your Python programs and apply for Python jobs.
  • Learn Python from experienced professional software developers.

Checkout This Course

#4: Python Bible | Everything You Need to Program in Python

Ziyad Yehia creates the course.

The course has already enrolled over 75,000+ students, and the reviews are good.

The course has 73 lectures(9 hrs).

This course consists of everything you need as a Python beginner. In this course, you will learn about Python variables, loops, functions, data structures, strings & OOP.

What you will learn in this course

  • You can build 11 Easy-to-Follow Python 3 Projects.
  • You can automate Coding Tasks By Building Custom Python Functions.
  • You can add Python 3 to your Resume by Understanding Object-Oriented Programming (OOP).
  • You can use Variables to Track Data in Python Programs.
  • Create Programs that can think using logic and data structures.

Checkout This Course

#5: Python for Everybody Specialization

The Specialization Python course builds on the success for Everybody and will introduce fundamental programming concepts, including the data structures(like list, dictionary, tuple), networked application program interfaces, and databases, using the Python.

In the Capstone Project, you will use the technologies learned throughout the Specialization to design and create your applications for data retrieval, processing, and visualization.

The course has already enrolled over 275,000+ students.

You can track your progress on your personalized dashboard.

What you will learn in this course

  • Create your applications for data retrieval and processing.
  • Describe the basics of the Structured Query Language (SQL) and database design.
  • Explain the basics of programming computers using Python.
  • Understand fundamental programming concepts such as data structures.
  • Every Specialization includes a hands-on project. You’ll need to successfully finish the project(s) to complete the Specialization and earn your certificate.

Checkout This Course

Conclusion

The average Python developer salary in 2020 is around $100,000+, which is cool.

If you want to pursue your career in Computer science, then you need to learn Python at any some point then why you should not learn now. It is a golden age for the next IT revolution, and Python is a big part of it. Thanks for taking this tutorial with me. Have a great learning experience.

The post Top 5 Python Online Courses For Beginners In 2020 appeared first on AppDividend.

]]>
https://appdividend.com/2020/01/19/top-5-python-online-courses-for-beginners/feed/ 0
How To Combine Two or More Dictionaries In Python https://appdividend.com/2020/01/19/python-combine-two-dictionaries/ https://appdividend.com/2020/01/19/python-combine-two-dictionaries/#respond Sun, 19 Jan 2020 06:46:38 +0000 http://localhost/wordpress/?p=13759 How To Combine Two Or More Dictionaries In Python

Python Dictionary update() is a built-in function that accepts another dictionary or an Iterable object (collection of key-value pairs) as an argument. It merges the contents of this passed dictionary or Iterable in the current dictionary. The update() method did not create a new dictionary; it changes the content of the existing dictionary. Python Combine Two Dictionaries There are […]

The post How To Combine Two or More Dictionaries In Python appeared first on AppDividend.

]]>
How To Combine Two Or More Dictionaries In Python

Python Dictionary update() is a built-in function that accepts another dictionary or an Iterable object (collection of key-value pairs) as an argument. It merges the contents of this passed dictionary or Iterable in the current dictionary. The update() method did not create a new dictionary; it changes the content of the existing dictionary.

Python Combine Two Dictionaries

There are mainly two ways that we can use the merge two dictionaries in Python.

  1. Merge two or more dictionaries using dict.update()
  2. Merge two or more Dictionaries using **kwargs

Let’s see python combine two dictionaries example.

Merge two or more dictionaries using dict.update()

Python dictionary update() is an inbuilt method that updates one dictionary with the elements of another dictionary object or from an iterable value of key pair. If a key is not present in the dictionary, it first adds the key to the dictionary.

After that, it combines the value; otherwise, if the key is already present in the dictionary, it just updates the value.

In short, it accepts another dictionary or an Iterable object (collection of key-value pairs) as an argument. Then merges the contents of this passed dictionary or Iterable in the current dictionary.

See the following code.

# app.py

dictA = {'asa': 11, 'emma': 19, 'eric' : 21}

dictB = {'millie': 46, 'finn': 23, 'noah' : 18}

dictA.update(dictB)
 
print('Updated dictionary A :')
print(dictA)

Output

Updated dictionary 1 :
{'asa': 11, 'emma': 19, 'eric': 21, 'millie': 46, 'finn': 23, 'noah': 18}

From the output, you can see that All the items from dictB are added to dictA.

In this example, all the keys are from both the dictionaries are unique.

Let’s take an example in which some of the keys are the same for both the dictionaries and see the output.

# app.py

dictA = {'asa': 11, 'emma': 19, 'eric' : 21}

dictB = {'asa': 46, 'finn': 23, 'eric' : 18}

dictA.update(dictB)
 
print('Updated dictionary A :')
print(dictA)

Output

Updated dictionary A :
{'asa': 46, 'emma': 19, 'eric': 18, 'finn': 23}

So, from the output, you can see that keys that are common in both the dictionaries will contain the values as in dictB. The dictionary we are passing in the update() method as an argument will override the standard key’s values. Therefore ‘asa’ has value 46, and ‘eric‘ has value 18 now.

So, the second dictionary’s value will override the first dictionary value, if the keys are the same in both the dictionaries while doing an update().

The update() method did not create a new dictionary(dictA), it updates the content of the first dictionary(dictA). 

Let’s see the second way of how to merge two dictionaries.

Merge two or more Dictionaries using **kwargs

The special syntax **kwargs in python is used to pass the keyworded, variable-length argument list. We use the name kwargs with a double star.

The main reason is that the double star allows us to pass through any number of keyword arguments.

  1. A keyword argument is where you provide the name to the variable as you pass it into the function.
  2. You can think of the kwargs as being the dictionary that maps each keyword to a value that we pass alongside it. That is why when we iterate over the kwargs, there doesn’t seem to be any order in which they were printed out.

For example, if we have a dictionary like the following.

dictA = {'asa': 11, 'emma': 19, 'eric' : 21}

When we apply **(double star) to the dictA, it deserializes the contents of the dictionary to a collection of key-value pairs like the following.

**dictA

Is equivalent to this.

'asa': 11, 'emma': 19, 'eric' : 21

Now, see the following code.

# app.py

dictA = {'asa': 11, 'emma': 19, 'eric' : 21}

dictB = {'millie': 46, 'finn': 23, 'noah' : 18}

dictC = {**dictA, **dictB}
 
print('Combined Dictionary C :')
print(dictC)

In the above code, we are creating the third dictionary and assign the deserialized values of two dictionaries to that dictionaries.

So, we are getting combined dictC, which is the third dictionary, and it does not modify the content of the existing two dictionaries.

Output

Combined Dictionary C :
{'asa': 11, 'emma': 19, 'eric': 21, 'millie': 46, 'finn': 23, 'noah': 18}

The **dictA and **dictB expanded the contents of both the dictionaries to a collection of key-value pairs.

Let’s take three dictionaries and combine all of them and create the fourth dictionary.

# app.py

dictA = {'asa': 11, 'emma': 19, 'eric' : 21}

dictB = {'millie': 46, 'finn': 23, 'noah': 18}

dictC = {'penny': 29, 'sheldon': 36, 'leonard': 2}

dictD = {**dictA, **dictB, **dictC}
 
print('Combined Dictionary D :')
print(dictD)

Output

Combined Dictionary D :
{'asa': 11, 'emma': 19, 'eric': 21, 'millie': 46, 'finn': 23, 'noah': 18, 'penny': 29, 'sheldon': 36, 'leonard': 2}

Conclusion

Merging two or more dictionaries is an easy task in Python. But to find a better approach is a tough choice for every developer. If you do not have any consequences of modifying the existing dictionary, then you can use the dict.update() method otherwise go for **kwargs approach.

Finally, Python combine two dictionaries example article is over.

The post How To Combine Two or More Dictionaries In Python appeared first on AppDividend.

]]>
https://appdividend.com/2020/01/19/python-combine-two-dictionaries/feed/ 0
Python fsum() Function Example https://appdividend.com/2020/01/17/python-fsum-function-example/ https://appdividend.com/2020/01/17/python-fsum-function-example/#respond Fri, 17 Jan 2020 13:55:24 +0000 http://localhost/wordpress/?p=13752 Python fsum() Function Example

Python fsum() is an inbuilt math function that is used to find the sum between some range or iterable. The sum() function is under the math library, so to use this function, we first will have to import math. Python fsum() Python fsum() method is a library method of the math module, and it is used […]

The post Python fsum() Function Example appeared first on AppDividend.

]]>
Python fsum() Function Example

Python fsum() is an inbuilt math function that is used to find the sum between some range or iterable. The sum() function is under the math library, so to use this function, we first will have to import math.

Python fsum()

Python fsum() method is a library method of the math module, and it is used to find the sum (in float) of the values of an iterable, it accepts an iterable object like an array, list, tuple, etc. (that should contain numbers either integers or floats). It returns the sum in float of all values.

Syntax

math.fsum( value )

Here, the value can be a range or an iterable like an array, tuple.

Return Value

The fsum() function returns the sum of the iterable or range in floating-point number. ‘f’ in fsum() stands for float.

Programming Example

See the following code.

# app.py

#importing math library
import math

#Finding sum of a range first

#taking input from the user
x=int(input("Please enter a range up to which you want to sum: "))

#finding sum of the range using fsum()
print("Sum of the range is: ",math.fsum(range(x)))

#Finding sum of an iterable

#taking input of a list 
print("Please enter array element with space separated integer: ")
arr=list(map(int,input().split(" ")))

#printing all array elements
print("All array elements are: ",arr)

#Finding sum of all the values using fsum()
print("Sum of all elements of the array is: ",math.fsum(arr))

Output

Please enter a range up to which you want to sum: 15
Sum of the range is:  105.0
Please enter the array element with space-separated integer:
1 3 5 7
All array elements are:  [1, 3, 5, 7]
Sum of all elements of the array is:  16.0

In this program, we first have an imported math library, and then we have taken an input integer from the user. After that, we have calculated the sum of all elements up to that number, and then we have printed that.

On the other hand, we have taken input for a list, where the user will have to given all list elements by a space. Then we have called fsum() to calculate the sum of all the list elements.

Example 2

See the following code.

# app.py

import math

# range(11)
print(math.fsum(range(11)))

# Integer list
arr = [11, 46, 21]
print(math.fsum(arr))

# Floating point list
arr = [2.1, 1.1, 1.9]
print(math.fsum(arr))

Output

python3 app.py
55.0
78.0
5.1

Conclusion

Python fsum() is one of the Python Math function that is used to calculate and return the sum of iterators like Tuples and Lists.

See also

Python frexp()

Python fmod()

Python factorial

Python math.fabs()

Python math copysign()

Python math functions

Python math.sqrt()

Python math.floor()

The post Python fsum() Function Example appeared first on AppDividend.

]]>
https://appdividend.com/2020/01/17/python-fsum-function-example/feed/ 0
Python frexp() Function Example https://appdividend.com/2020/01/17/python-frexp-function-example/ https://appdividend.com/2020/01/17/python-frexp-function-example/#respond Fri, 17 Jan 2020 13:31:52 +0000 http://localhost/wordpress/?p=13743 Python frexp() Function Example

Python frexp() is an inbuilt function under the math library that helps us to find mantissa and exponent of x as the pair (m, e), where m is the float, and e is the integer such that x == m * 2**e. If the value of x is 0 then this function returns (0.0,0), otherwise […]

The post Python frexp() Function Example appeared first on AppDividend.

]]>
Python frexp() Function Example

Python frexp() is an inbuilt function under the math library that helps us to find mantissa and exponent of x as the pair (m, e), where m is the float, and e is the integer such that x == m * 2**e. If the value of x is 0 then this function returns (0.0,0), otherwise it returns 5 <= abs(m) <1.

Python frexp()

The frexp() function is one of the Standard math Library functions in Python. It returns mantissa and exponent as a pair (m, e) of a given value x, where mantissa is a floating-point number, and exponent is an integer value. m is the float, and e is an integer such that x == m * 2**e exactly.

If the x is zero, returns (0.0, 0), otherwise 0.5 <= abs(m) < 1. This is used to “pick apart” the internal representation of the float in a portable way.

Syntax

math.frexp(x)

Here x is a number for which we will find mantissa and exponent.

Return Value

The frexp() function returns mantissa and exponent of x as the pair (m, e), where m is the float, and e is an integer. However, if the given value x is not a number, then this function returns a TypeError.

Programming Example

See the following code.

# app.py

# Importing math library
import math

# Demonstrating working of frexp()
# Using different types of value of x

# When x is positive number
x = 5
print("Pair of mantissa and exponent of ", x, " is: ", math.frexp(x))

# When x is float type number
x = 6.4
print("Pair of mantissa and exponent of ", x, " is: ", math.frexp(x))

# When x is a negative number
x = -32
print("Pair of mantissa and exponent of ", x, " is: ", math.frexp(x))

# Declaring a list
x = [4, 3, 7]

# Using frexp() with the 3rd value of the list
print("Pair of mantissa and exponent of ", x[2], " is: ", math.frexp(x[2]))

# When x is not a number
x = '41'
print("Pair of mantissa and exponent of ", x, " is: ", math.frexp(x))

Output

Pair of mantissa and exponent of  5  is:  (0.625, 3)
Pair of mantissa and exponent of  6.4  is:  (0.8, 3)
Pair of mantissa and exponent of  -32  is:  (-0.5, 6)
Pair of mantissa and exponent of  7  is:  (0.875, 3)
Traceback (most recent call last):
  File "frexp.py", line 27, in <module>
	print("Pair of mantissa and exponent of ",x," is: ",math.frexp(x))
TypeError: must be real number, not str

In the above code, we have taken different types of values of x and checked the output using the frexp() method. We can see that in each case, an output is in (m,e) pair. 

At last, when we have declared value of x as a character, a TypeError is returned.

Use frexp() with Python tuple and list

See the following code in which we have defined Python list and tuple.

# app.py

import math

# creating a list
lst = [11, 21.11, 21.19, 30]

# creating a tuple
tpl = (-15.31, -41.31, -11.21, 46.19)

# calculating mantissa and exponent
# of 1st, 3rd elements in list
print(math.frexp(lst[0]))
print(math.frexp(lst[2]))

# calculating mantissa and exponent
# of 2nd, 3rd and 4th elements in tuple
print(math.frexp(tpl[1]))
print(math.frexp(tpl[2]))
print(math.frexp(tpl[3]))

Output

python3 app.py
(0.6875, 4)
(0.6621875, 5)
(-0.64546875, 6)
(-0.700625, 4)
(0.72171875, 6)

Conclusion

Python frexp() method is one of the Python Mathematical Functions that is used to return the mantissa and exponent of x, as a pair (m, e) where m is the float value and e is an integer value.

See also

Python fmod()

Python factorial

Python math.fabs()

Python math copysign()

Python math functions

Python math.sqrt()

Python math.floor()

The post Python frexp() Function Example appeared first on AppDividend.

]]>
https://appdividend.com/2020/01/17/python-frexp-function-example/feed/ 0
Python Math fmod() Function Example https://appdividend.com/2020/01/17/python-math-fmod-function-example/ https://appdividend.com/2020/01/17/python-math-fmod-function-example/#respond Fri, 17 Jan 2020 09:34:36 +0000 http://localhost/wordpress/?p=13732 Python Math fmod() Function Example

Python fmod() is an inbuilt function under the math library that is used to find a module of two given numbers. Means, this function finds x%y for a given any two numbers x and y. Please remember that this function is advised to use when you want to find a module of any float number. […]

The post Python Math fmod() Function Example appeared first on AppDividend.

]]>
Python Math fmod() Function Example

Python fmod() is an inbuilt function under the math library that is used to find a module of two given numbers. Means, this function finds x%y for a given any two numbers x and y. Please remember that this function is advised to use when you want to find a module of any float number. Because, in Python, if you use x%y for any float type number with different signed values, the result may differ from using fmod(x,y).

Python fmod()

The math.fmod() is a method from the Standard math Library of Python Programming Language. Python math fmod() function is used to calculate the module value of given parameters x and y. The math.fmod() method is a library method of the math module, and it is used to find a modulus for given numbers, where the first parameter is a dividend, and the second parameter is the divisor.

It accepts two arguments and will return modulus in the float type.

Note: The math.fmod() can be used to get the modules/remainder of positive and negative integers and positive and negative floats.

Syntax

math.fmod(x,y)

The function takes two arguments, which are x and y (both can be positive or negative), which finds x%y.

Return Value

The fmod() function returns a floating-point number value after calculating the module of the given two numbers.

Please note that, 

  1. If x and y are both zero, then this function returns a ValueError.
  2. If the second argument means y is zero, then also it returns a ValueError.
  3. If any of x or y is not a number, then this function returns a TypeError.

Python fmod() Function Compatibility

Python 2.x – Yes
Python 3.x – Yes

Programming Example

See the following code.

# app.py

# Importing math library
import math
# Demonstrating working of fmod()
# Using different values of x and y

# When both are positive
x = 12
y = 9
print("Module of ", x, " and ", y, "is: ", math.fmod(x, y))

# When any one of them are negative
x = -16
y = 3
print("Module of ", x, " and ", y, "is: ", math.fmod(x, y))

# When both are negative
x = -65
y = -31
print("Module of ", x, " and ", y, "is: ", math.fmod(x, y))

# When second argument (y) is 0
x = 10
y = 0
print("Module of ", x, " and ", y, "is: ", math.fmod(x, y))

Output

Module of  12  and  9 is:  3.0
Module of  -16  and  3 is:  -1.0
Module of  -65  and  -31 is:  -3.0
Traceback (most recent call last):
  File "fmod.py", line 24, in <module>
	print("Module of ",x," and ",y, "is: ",math.fmod(x,y))
ValueError: math domain error

In the above code, we have declared two variables x and y and given their different values in different cases.

After that, we have a printed module of each case, we can see that the answer is positive only when both x and y are positive, and except that in all cases, the answer is negative.

Also, we can see that in each case, the answer is in floating-point.

However, in the last case, when we gave the value of y is 0, we got a ValueError.

Conclusion

The return fmod(x, y), as defined by the platform C library. Note that the Python expression x % y may not return the same result.

The C standard intends that fmod(x, y) be exactly (mathematically; to infinite precision) equal to x – n*y for some integer n such that the result has a same sign as x and magnitude less than abs(y).

Python’s x % y returns the result with the sign of y instead, and may not be precisely computable for float arguments.

See Also

Python factorial

Python math.fabs()

Python math copysign()

Python math functions

Python math.sqrt()

Python math.floor()

The post Python Math fmod() Function Example appeared first on AppDividend.

]]>
https://appdividend.com/2020/01/17/python-math-fmod-function-example/feed/ 0
Python factorial() Example | How To Find Factorial In Python https://appdividend.com/2020/01/15/python-factorial-example-how-to-find-factorial-in-python/ https://appdividend.com/2020/01/15/python-factorial-example-how-to-find-factorial-in-python/#respond Wed, 15 Jan 2020 10:24:15 +0000 http://localhost/wordpress/?p=13646 Python factorial() Example | How To Find Factorial In Python

Python factorial() is an inbuilt math library method that is used to find factorial of any integer type number. We can find factorial of any number using the naive method, but it is easier to find factorial using the factorial() method. The factorial() method is under python math library, so if we want to use […]

The post Python factorial() Example | How To Find Factorial In Python appeared first on AppDividend.

]]>
Python factorial() Example | How To Find Factorial In Python

Python factorial() is an inbuilt math library method that is used to find factorial of any integer type number. We can find factorial of any number using the naive method, but it is easier to find factorial using the factorial() method. The factorial() method is under python math library, so if we want to use this method, we first will have to import the math library.

Python factorial()

Python offers a direct function that can compute the factorial of a number without writing the whole code for computing factorial.

Syntax

math.factorial(num)

The factorial() method takes one integer as an argument. If we provide float or any negative number, it will throw an error.

Return Value

The factorial() method returns the factorial of the desired number.

Program to find factorial using the naive method

See the following code.

# Taking input from user
num = int(input("Enter the number to find factorial: "))
# Declaring one temporary variable to store the answer
fact = 1

# Finding factorial of the given number
for i in range(1, num+1):
    fact = fact*i

print("Factorial of the given number ", num, " is: ", fact)

Output

Enter the number to find factorial: 5
Factorial of the given number  5  is:  120

In this example, we have first taken input from the user then we have declared one temporary variable fact to store the factorial of the given number.

As we know, the factorial of a given number N is N*N-1*N-2*…*1, so we have written this in a reverse manner in a for loop.

At last, we got the answer.

Program to find factorial using factorial() method

See the following code.

# app.py

# importing math library
import math
# Taking input from user
num = int(input("Enter the number to find factorial: "))

# Finding factorial of the given number
fact = math.factorial(num)

print("Factorial of the given number ", num, " is: ", fact)

Output

Enter the number to find factorial: 5
Factorial of the given number  5  is:  120

In this example, we have first taken input from the user after importing the math library. Then we have called factorial() method to find the factorial of the given number, and at last, we got the answer.

Program to find factorial for Non Integral Value

See the following code.

# app.py

import math

print("The factorial of 11.21 is : ", end="")

# raises exception
print(math.factorial(11.21))

Output

python3 app.py
The factorial of 11.21 is : Traceback (most recent call last):
  File "app.py", line 6, in <module>
    print(math.factorial(11.21))
ValueError: factorial() only accepts integral values

We will face the ValueError because factorial() function accepts an only integral value.

Conclusion

If you want to find factorial in Python, then you can either use math.factorial() function or use naive method.

See also

Python math.fabs()

Python math copysign()

Python math functions

Python math.sqrt()

Python math.floor()

The post Python factorial() Example | How To Find Factorial In Python appeared first on AppDividend.

]]>
https://appdividend.com/2020/01/15/python-factorial-example-how-to-find-factorial-in-python/feed/ 0