DEV Community

Cover image for Python in a nutshell [Part-1]
Anurag Pandey
Anurag Pandey

Posted on

Python in a nutshell [Part-1]

Lets start with the Hello World of Python.

>>> print("Hello, World")
Hello, World
>>>
Enter fullscreen mode Exit fullscreen mode

We know one rule, a computer program does only what we have specified it to do. So how did the print function printed a new line character?
Lets investigate the print function with one of our bestfriends called the help function.

>>> help(print)
print(value, ..., sep=' ', end='\n', file=sys.stdout, flush=False)

    Prints the values to a stream, or to sys.stdout by default.
    Optional keyword arguments:
    file:  a file-like object (stream); defaults to the current sys.stdout.
    sep:   string inserted between values, default a space.
    end:   string appended after the last value, default a newline.
    flush: whether to forcibly flush the stream.
Enter fullscreen mode Exit fullscreen mode

(Type q to exit the help)

So from this we can understand that after printing the value, it entered a new line character. Lets see different arguments in action:

>>> print("Hello, World", end='')
Hello, World>>> print(1, 2, 3)
1 2 3
>>> print(1, 2, 3, sep='-')
1-2-3
>>>
Enter fullscreen mode Exit fullscreen mode

Okay next thing now is to take input from the user, which can be done as:

>>> a = input("Enter your name:")
Enter your name: Anurag
>>> print(a)
Anurag
>>>
Enter fullscreen mode Exit fullscreen mode

The input function returns a string. Don't worry about different data types, we will cover them later.
You can find the type of an object using type function:

>>> type(a)
<class 'str'>
Enter fullscreen mode Exit fullscreen mode

So the object returned by the input function is of class str.

Lets try our new bestfriend help function on it:

>>> help(input)
Help on built-in function input in module builtins:

input(prompt=None, /)
    Read a string from standard input.  The trailing newline is stripped.

    The prompt string, if given, is printed to standard output without a
    trailing newline before reading input.

    If the user hits EOF (*nix: Ctrl-D, Windows: Ctrl-Z+Return), raise EOFError.
    On *nix systems, readline is used if available.
Enter fullscreen mode Exit fullscreen mode

It is important to remember what type of object a function returns.

Takeaways:

  1. Make help function your best friend.
  2. Use type function to find the type of an object.
  3. Know what to provide to a function and more importantly what it returns.

In Part-2, we will discuss about the importing different modules and different data structures in Python.

P.S : Python 2 Python 3 is used.

Top comments (1)

Collapse
 
hrishibhattu profile image
Hrishikesh Bhattu

This is great for beginners. Good job 👍🏽👍🏽