Found 10400 Articles for Python

How to compare numbers in Python?

Samual Sam
Updated on 05-Mar-2020 10:48:16

17K+ Views

You can use relational operators in python to compare numbers(both float and int) in python. These operators compare the values on either side of them and decide the relation among them. Assume variable a holds 10 and variable b holds 20, thenOperatorExample==(a == b) is not true.!=(a != b) is true.>(a > b) is not true.=(a >= b) is not true.= b) print(a

How to Find Hash of File using Python?

Arjun Thakur
Updated on 05-Mar-2020 10:46:21

3K+ Views

You can find the hash of a file using the hashlib library. Note that file sizes can be pretty big. Its best to use a buffer to load chunks and process them to calculate the hash of the file. You can take a buffer of any size.Exampleimport sys import hashlib BUF_SIZE = 32768 # Read file in 32kb chunks md5 = hashlib.md5() sha1 = hashlib.sha1() with open('program.cpp', 'rb') as f: while True:    data = f.read(BUF_SIZE)    if not data:       break    md5.update(data)    sha1.update(data) print("MD5: {0}".format(md5.hexdigest())) print("SHA1: {0}".format(sha1.hexdigest()))OutputThis will give the outputMD5: 7481a578b20afc6979148a6a5f5b408d SHA1: ... Read More

How to Find ASCII Value of Character using Python?

Chandu yadav
Updated on 05-Mar-2020 10:39:47

191 Views

The ord function in python gives the ordinal value of a character(ASCII). You can use this function to find the ascii codes as followsExamples = "Hello" for c in s:    print(ord(c))OutputThis will give the output72 101 108 108 111

How to Convert Decimal to Binary, Octal, and Hexadecimal using Python?

karthikeya Boyini
Updated on 05-Mar-2020 10:38:46

1K+ Views

Python provides straightforward functions to convert Decimal to Binary, Octal, and Hexadecimal. These functions are −Binary: bin() Octal: oct() Hexadecimal: hex()ExampleYou can use these functions as follows to get the corresponding representation −decimal = 27 print(bin(decimal),"in binary.") print(oct(decimal),"in octal.") print(hex(decimal),"in hexadecimal.")OutputThis will give the output −0b11011 in binary. 0o33 in octal. 0x1b in hexadecimal.

How to print current date and time using Python?

Abhinanda Shri
Updated on 05-Mar-2020 10:31:00

6K+ Views

You can get the current date and time using multiple ways. The easiest way is to use the datetime module. It has a function, now, that gives the current date and time. exampleimport datetime now = datetime.datetime.now() print("Current date and time: ") print(str(now))OutputThis will give the output −2017-12-29 11:24:48.042720You can also get the formatted date and time using strftime function. It accepts a format string that you can use to get your desired output. Following are the directives supported by it.DirectiveMeaning%aLocale's abbreviated weekday name.%ALocale's full weekday name.%bLocale's abbreviated month name.%BLocale's full month name.%cLocale's appropriate date and time representation.%dDay of the month ... Read More

How can we do the basic print formatting for Python numbers?

Ankith Reddy
Updated on 17-Jun-2020 12:39:20

184 Views

You can format a floating number to the fixed width in Python using the format function on the string. For example, nums = [0.555555555555, 1, 12.0542184, 5589.6654753] for x in nums:    print("{:10.4f}".format(x))This will give the output0.5556 1.0000 12.0542 5589.6655Using the same function, you can also format integersnums = [5, 20, 500] for x in nums:    print("{:d}".format(x))This will give the output:5 20 500You can use it to provide padding as well, by specifying the number before dnums = [5, 20, 500] for x in nums:    print("{:4d}".format(x))This will give the output5 20 500The https://pyformat.info/ website is a great resource ... Read More

How to generate statistical graphs using Python?

Ankitha Reddy
Updated on 30-Jul-2019 22:30:22

406 Views

Python has an amazing graph plotting library called matplotlib. It is the most popular graphing and data visualization module for Python. You can start plotting graphs using 3 lines! For example, from matplotlib import pyplot as plt # Plot to canvas plt.plot([1, 2, 3], [4, 5, 1]) #Showing what we plotted plt.show() This will create a simple graph with coordinates (1, 4), (2, 5) and (3, 1). You can Assign labels to the axes using the xlabel and ylabel functions. For example, plt.ylabel('Y axis') plt.xlabel('X axis') And also provide a title using the title ... Read More

How to generate a random 128 bit strings using Python?

Abhinaya
Updated on 05-Mar-2020 10:21:59

3K+ Views

You can generate these just random 128-bit strings using the random module's getrandbits function that accepts a number of bits as an argument. exampleimport random hash = random.getrandbits(128) print(hex(hash))OutputThis will give the output −0xa3fa6d97f4807e145b37451fc344e58c

How to find time difference using Python?

Ankith Reddy
Updated on 05-Mar-2020 10:19:02

2K+ Views

It is very easy to do date and time maths in Python using time delta objects. Whenever you want to add or subtract to a date/time, use a DateTime.datetime(), then add or subtract date time.time delta() instances. A time delta object represents a duration, the difference between two dates or times. The time delta constructor has the following function signatureDateTime.timedelta([days[, seconds[, microseconds[, milliseconds[, minutes[, hours[, weeks]]]]]]])¶Note: All arguments are optional and default to 0. Arguments may be ints, longs, or floats, and may be positive or negative. You can read more about it here https://docs.python.org/2/library/datetime.html#timedelta-objectsExampleAn example of using the time ... Read More

How to generate JSON output using Python?

karthikeya Boyini
Updated on 05-Mar-2020 10:16:33

2K+ Views

The json module in python allows you to dump a dict to json format directly. To use it,Exampleimport json my_dict = {    'foo': 42,    'bar': {       'baz': "Hello",       'poo': 124.2    } } my_json = json.dumps(my_dict) print(my_json)OutputThis will give the output −'{"foo": 42, "bar": {"baz": "Hello", "poo": 124.2}}'You can also pass indent argument to prettyprint the json. exampleimport json my_dict = {    'foo': 42,    'bar': {       'baz': "Hello",       'poo': 124.2    } } my_json = json.dumps(my_dict, indent=2) print(my_json)OutputThis will give the output −{    "foo": 42,    "bar":    {       "baz": "Hello",       "poo": 124.2    } }

Advertisements