DEV Community

Sunny
Sunny

Posted on • Updated on

5 Tricks for beginners if you are coding in Python

Image description> For a novice, try these tricks if you haven't already

1. Function to make a noun (adjective) from a verb or an adverb from a noun (adjective)

def verbing(s):
    returns iflen(s) < 3 elses + ('ing', 'ly')['ing' ins]

>>> verbing('help')
helping
>>> verbing('helping')
helpingly
Enter fullscreen mode Exit fullscreen mode

2. use a bare "*" asterisk in function parameter lists to force the caller to use keyword arguments for certain parameters

>>> def f(a, b, *, c='x', d='y', e='z'):
...     return 'Hello'
Enter fullscreen mode Exit fullscreen mode

To pass the value for c, d, and e you will need to explicitly pass it as "key=value" named arguments:

>>> f(1, 2, 'p', 'q', 'v')
TypeError: f() takes 2 positional arguments but 5 were given

>>> f(1, 2, c='p', d='q',e='v')
'Hello' 
Enter fullscreen mode Exit fullscreen mode

3. getpass module provides a platform-independent way to enter a password in a command-line program without echoing

>>> import getpass
>>> password = getpass.getpass()
Password:
>>> password
'alohomora'
Enter fullscreen mode Exit fullscreen mode

getuser() gets the current username:

>>> getpass.getuser()
'sirius_black'
Enter fullscreen mode Exit fullscreen mode

4. if the fractional component of the number is halfway between two integers, one of which is even and the other odd, then round() returns the even. This kind of rounding is called rounding to even (or banker’s rounding)

>>> round(0.5)
0
>>> round(2.4)
2
>>> round(2.5)
2
>>> round(2.6)
3
>>> round(3.5)
4
>>> round(4.5)
4
Enter fullscreen mode Exit fullscreen mode

5. The built-in function sys.getsizeof() returns the size of an object in bytes. The object can be any type of object

>>> sys.getsizeof(1)
28
>>> sys.getsizeof([1, 2, 3])
88
>>> sys.getsizeof('')
49
>>> sys.getsizeof('P')
50
>>> sys.getsizeof('Py')
51
>>> sys.getsizeof('Python')
55
Enter fullscreen mode Exit fullscreen mode

Top comments (0)