Python First Program


Python First Program

Writing a python program is as easy as typing plain English. For our first “Hello World!” program, we just have to type print("Hello World!") in the Jupyter Notebook.

It’s amazing that how simple it is to print ‘Hello World!’ in Python.  We don’t need to do any heavy lifting, such as importing files, as we do in other programming languages. A single statement is all it takes. It’s as easy as it sounds.

In [1]:
print("Hello World!")
Hello World!

Here is the simple breakdown of the First Python Program, which contains the print keyword and the content that we want to print. This content can be the text, number or the variable.

Python First Program
Print Function

Python as Calculator

A Python interpreter can be used to perform calculations like a regular calculator. We can accomplish that by simply typing the actions we wish to take instead of creating a program. We can perform calculations like 5+5, 789*456, (14+2)*(5+3), and many others, for instance. All of this is possible without even writing a single line of code.

In [1]:
5+5
Out[1]:
10
In [2]:
789*456
Out[2]:
359784
In [3]:
(14+2)*(5+3)
Out[3]:
128

Python Version

It is easy to check the version of the python interpreter we are working on. Three ways by which we can check the version of the Python interpreter:

1. In the Jupyter notebook or any other IDE, we just have to import sys and then type print(sys.version).

In [1]:
import sys
print(sys.version)
3.7.4 (default, Aug  9 2019, 18:34:13) [MSC v.1915 64 bit (AMD64)]

2. There is yet another method by which we can check the version of python directly from the command prompt. We just need to go to the command prompt and type python --version.

Checking version of python
How to Check python version from command prompt

3. We can also import platform and then use print(platform.python_version()) to check the version.

In [1]:
import platform

print(platform.python_version())
3.7.4

These are just three techniques to check the version of python. But we can also check the same using some other methods like help(), when we will use the help() function to check the version, the first like it will display is “Welcome to Python 3.7’s help utility!”. Some people use this also as a technique to check the version of Python because for this they don’t need to remember any of the above mwthods.

Keywords in Python

Keywords are reserved words in Python that have special meanings and cannot be used as identifiers (variable names, function names, etc.). We should avoid using these words as variable names to avoid conflicts and ensure proper functionality of your programs.

To check the list of keywords, we just have to import keyword and the type print(keyword.kwlist). It will print the list of keywords.

In [1]:
import keyword
print(keyword.kwlist)
['False', 'None', 'True', 'and', 'as', 'assert', 'async', 'await', 'break', 'class', 'continue', 'def', 'del', 'elif', 'else', 'except', 'finally', 'for', 'from', 'global', 'if', 'import', 'in', 'is', 'lambda', 'nonlocal', 'not', 'or', 'pass', 'raise', 'return', 'try', 'while', 'with', 'yield']

Here is the Table showing all the keywords available in Python:

Keywords are essential building blocks that define the language’s syntax and structure. They are predefined and serve specific purposes within the code. Common keywords include if, else, for, while, def, and class, each playing a crucial role in control flow, function and class definition, and more.

For example, the if keyword is used to create conditional statements, allowing your program to make decisions based on certain conditions. The def keyword is used to define functions, and class is used to create classes, a fundamental concept in object-oriented programming.

Help in Python

At times when we are writing out code, we may need help at any stage with some conditional statement, keyword, topic etc. So python has an inbuilt help() function that can be used anytime.

This help() function can be used in two ways:

1. First, simply type help() function and then type the topic/keyword in the text box. This type of help is also known as the Interactive help because after calling help() function, the interpreter enters the interactive mode.

2. Second, in the help function itself, we can pass the topic/keyword using double quotes. For example, help("for").

In [1]:
help("for")
The "for" statement
*******************

The "for" statement is used to iterate over the elements of a sequence
(such as a string, tuple or list) or other iterable object:

   for_stmt ::= "for" target_list "in" expression_list ":" suite
                ["else" ":" suite]

The expression list is evaluated once; it should yield an iterable
object.  An iterator is created for the result of the
"expression_list".  The suite is then executed once for each item
provided by the iterator, in the order returned by the iterator.  Each
item in turn is assigned to the target list using the standard rules
for assignments (see Assignment statements), and then the suite is
executed.  When the items are exhausted (which is immediately when the
sequence is empty or an iterator raises a "StopIteration" exception),
the suite in the "else" clause, if present, is executed, and the loop
terminates.

A "break" statement executed in the first suite terminates the loop
without executing the "else" clause’s suite.  A "continue" statement
executed in the first suite skips the rest of the suite and continues
with the next item, or with the "else" clause if there is no next
item.

The for-loop makes assignments to the variables(s) in the target list.
This overwrites all previous assignments to those variables including
those made in the suite of the for-loop:

   for i in range(10):
       print(i)
       i = 5             # this will not affect the for-loop
                         # because i will be overwritten with the next
                         # index in the range

Names in the target list are not deleted when the loop is finished,
but if the sequence is empty, they will not have been assigned to at
all by the loop.  Hint: the built-in function "range()" returns an
iterator of integers suitable to emulate the effect of Pascal’s "for i
:= a to b do"; e.g., "list(range(3))" returns the list "[0, 1, 2]".

Note: There is a subtlety when the sequence is being modified by the
  loop (this can only occur for mutable sequences, e.g. lists).  An
  internal counter is used to keep track of which item is used next,
  and this is incremented on each iteration.  When this counter has
  reached the length of the sequence the loop terminates.  This means
  that if the suite deletes the current (or a previous) item from the
  sequence, the next item will be skipped (since it gets the index of
  the current item which has already been treated).  Likewise, if the
  suite inserts an item in the sequence before the current item, the
  current item will be treated again the next time through the loop.
  This can lead to nasty bugs that can be avoided by making a
  temporary copy using a slice of the whole sequence, e.g.,

     for x in a[:]:
         if x < 0: a.remove(x)

Related help topics: break, continue, while

In [2]:
help()
Welcome to Python 3.7's help utility!

If this is your first time using Python, you should definitely check out
the tutorial on the Internet at https://docs.python.org/3.7/tutorial/.

Enter the name of any module, keyword, or topic to get help on writing
Python programs and using Python modules.  To quit this help utility and
return to the interpreter, just type "quit".

To get a list of available modules, keywords, symbols, or topics, type
"modules", "keywords", "symbols", or "topics".  Each module also comes
with a one-line summary of what it does; to list the modules whose name
or summary contain a given string such as "spam", type "modules spam".

help> if
The "if" statement
******************

The "if" statement is used for conditional execution:

   if_stmt ::= "if" expression ":" suite
               ("elif" expression ":" suite)*
               ["else" ":" suite]

It selects exactly one of the suites by evaluating the expressions one
by one until one is found to be true (see section Boolean operations
for the definition of true and false); then that suite is executed
(and no other part of the "if" statement is executed or evaluated).
If all expressions are false, the suite of the "else" clause, if
present, is executed.

Related help topics: TRUTHVALUE

help> quit

You are now leaving help and returning to the Python interpreter.
If you want to ask for help on a particular object directly from the
interpreter, you can type "help(object)".  Executing "help('string')"
has the same effect as typing a particular string at the help> prompt.

Quick Review

First Python Programprint(“Hello World!”)
Python Versionimport sys
print(sys.version)
Keywords in pythonimport keyword
print(keyword.kwlist)
Help in Pythonhelp()
help(“for”)

Resources

Test YourselfHandwritten Notes

Questions:

  1. To use Python as a calculator, we have to write a Program?
  2. We can use Python —version in the Jupyter Notebook to check the version of Python
  3. Keywords can be used as the variable names in Python.
  4. In Python, there is no way to check a list of keywords.
  5. To cannot check the syntax of any statement in Python without the internet.

Answers:

  1. False.
  2. False – It will not work in Jupyter notebook.
  3. False.
  4. False, we can check the list of keywords.
  5. False – we can use the help function.

References:

  1. Getting Started with Python
  2. Hello World Program
  3. Write Your First Program