Introduction to Python

Author: neptune | 22nd-May-2021 | views: 158

Introduction

Python is an easy to learn, powerful programming language. It has efficient high-level data structures and a simple but effective approach to object-oriented programming. Python’s elegant syntax and dynamic typing, together with its interpreted nature, make it an ideal language for scripting and rapid application development in many areas on most platforms.

Why python?

Python is easy to use, powerful, and versatile, making it a great choice for beginners and experts. Python's readability makes it a great first programming language that allows you to think like a programmer and not waste time with confusing syntax.

Learning from this course.

This course advances the reader informally to the basic concepts and features of the Python language. It is not going to be just theory and concepts it covers every single feature of Python. It helps the learner to make a strong base for python. It also includes illustrations that help the learner to understand each topic correctly. It gives you a good idea of the Python flavor and style.

First program in Python.

Run your first program in Python. It is easy than cutting an Apple.

# Type the below line in editor or IDE.
print("Hello World!")

output:
Hello World!

If you didn't get the output then make sure you installed Python. To check open terminal or cmd prompt. Type python3 (Linux user) or python (windows user).

[email protected]:~$ python3
Python 3.8.2 (default, Jul 16 2020, 14:00:26)
[GCC 9.3.0] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>>

If not then Install Python from here.

Primitives:-

  • Booleans
  • Strings
  • Numbers

Booleans

Boolean values are True or False and 0 or 1. In python we use it to evaluate the expression is True or False.

>>> 10==10
True

>>> 2==3
False

>>> 1 == True
True

String

String is one of the most important primitive of Python Language.We can also manipulate strings in many ways and it is widely used primitive. We represent string in single quotes ('neptuneworld') or double quotes ("neptuneworld") it will be same.

>>> website = "neptuneworld.in"
>>> website
'neptuneworld.in'
>>> type(website)
<class 'str'>
>>>

There are lot of operations we can perform in strig if you want to go in deep then check it out here.

Numbers

We all know what is integers, python interpreter is capable of handling integers expression syntax. Operators like +, -, *, **(power operator) and / work just like in most other languages.

>>> type(1)
>>> (class 'int')

>>> type(2.3)
<class 'float'>

>>> num = float(1)
>>> print(num)
1.0

>>> num = int(2.3)
>>> print(num)
2

# Multiply
>>> 2*3
6

# Power
>>> 2**3
8
>>>

There are other operations like divide(/), modulo(%) you do these by own.

Collections:-

  • Lists
  • Dictionaries

Lists

If we need to group diffrent datatypes in one collection then List is one of the most versatile collection in python. It store comma-separated values (items) between square brackets ["a","b",1,2.0]. Lists might contain items of different types, but usually the items all have the same type.

>>> squares = [1, 4, 9, 16, 25]
>>> squares
>>> [1,4, 9, 16, 25]
>>> sample = [1,"one",1.0,2,"two",2.0]
>>> type(sample)
>>> (class 'list')

If you want to explore more about list then click here.

Dictionaries

Dictionary is second collection, it optimizes elements lookups. Dictionary uses {} bracket to store data in "key" and "value" pairs dict={"key": value }. Each key must have a value, and you can use a key to look up a value.

Most important dictionary takes O(1) time or constant time for lookup or search a element in a dictionary. You can initialize dictionary using following methods.

>>> key = [1,2,3,4]
>>> value = ["one","two","three"]
>>> sample2 = dict(zip(key,value))
>>> sample2
{1: 'one', 2: 'two', 3: 'three'}

>>> words = {'apple': 'red','lemon': 'yellow'}
>>> words['apple']
red

Control statements:-

  • If statements
  • Loops

If statements

If statement has blocks if a condition is true then python interpreter runs a block of statements called the if-block.

If the statement is false, the interpreter skips the if block and processes to another block of statements called the else-block.

>>> If 2==2:
>>> print("True")
>>> else:
>>> print("False")
True

Loops

There are 2 kinds of loops used in Python:-

  • For loop
  • while loop.

For loops

For loops are used when you want to iterate same section of code again and again or N number of times. Loops are also used to iterate lists.

>>> for i in range(1,3):
>>> print(i)
1
2
>>> key = [1, 2, 3, 4]
>>> for i in key:
... print(i)
1
2
3
4

While loops

While loops in python work the same way it work in other languages. It is used where we want to loop until certain condition are not meet. Once the condition meet loop exit.

>>> i=0
>>> while i<5:
... print(i)
... i+=1
0
1
2
3
4

Continue statement in Python.

Continue statement is use to alter the flow of loop. It is used to continue the flow of loop for particular iteration. If we want to pass the particular section of code for the current iteration then we can use the Continue statement.

>>> for char in "neptuneworld":
... if char=="w":
... continue
... print(char)
n
e
p
t
u
n
e
o
r
l
d


Python Keywords and Identifiers

keywords are reserved words in Python we are not allowed to use the keywords as a variable and function names.So keywords are defined by python for it's syntax and structure. You need to know that keywords are case sensitive.

In Python3.7 there are 33 keywords available.

Except TrueFalse and None remaining keywords are in lowercase.

    Some of keywords are:-
  1. else
  2. break
  3. continue
  4. pass
  5. global
  6. except
  7. class
  8. for
  9. from
  10. return
  11. many more...

Identifiers are the name you assigned to variables, functions, classes etc.

Rules for identifiers are:-

1. Identifiers can not start with digit. eg 1name, 1_var etc are invalid.

>>> 1_var
File "", line 1
1_var
^
SyntaxError: invalid decimal literal

2. Identifiers can be a combinations of letters, underscore and digits. eg neptune_world, nep_tune_1, print_this_here etc.

>>> var_$ = 5
File "", line 1
var_$ = 5
^
SyntaxError: invalid syntax

Keywords can not be used as identifiers. eg global=1

>>> global=1
File "", line 1
global=1
^
SyntaxError: invalid syntax

Keep in mind.

  1. Python is case sensitive.
  2. In identifiers name multiple words separated by "_" eg. neptune_world = neptuneworld.in



Functions in Python

We are going to understand functions, how to declare a function, syntax, components etc.

We all know in programming we need to perform a specific task many times then we use function. Function is a set of related statements that perform a specific task.

it also help in organizing and managing the program and avoid repetition of code.

>>> def function_name():
... statement_1 = 1
... statement_2 = 2
... val = statement_1 + statement_2
... return val
...
>>> function_name()
3

def is keyword that make the start of the function header. function_name is used to identify the function. ":" colon is used to mark the end of header.return is used to return the value from the function.

>>> def neptune_world(url):
... """
... This function neptune_world is used to
... print url of neptuneworld it takes url
... as paprameter
... """
... print("Url of neptuneworld is https://",url)
...
>>> neptune_world("neptuneworld.in") #function call
Url of neptuneworld is https://neptuneworld.in #output
>>>

docstrings

You have seen that we have some lines after the function header which is a docstrings it gives an idea about what function can do.

>>> print(neptune_world.__doc__)

This function neptune_world is used to
print url of neptuneworld it takes url
as paprameter


Python Function Arguments

Arguments in Functions

Before we move on let us understand types of arguments in Python. In all Python has three types of arguments.

  • Default arguments
  • Keyword arguments
  • Arbitrary arguments

Python Default Arguments

Functions in python have default arguments values. We can do this by using a assignment (=) operator.

  
>>>> def marks(name, mark=0):
... print("Marks obtained by ",name + " is "+str(marks))
...
>>> marks("Neptune",92)
Marks obtained by Neptune is 92
>>>marks("Neptune")
Marks obtained by Neptune is 0

So the parameter "name" does not have the default value So it requires a value whenever you call a function but marks have default value 0, It is not required to pass a value each time during the call.


anonymous | Sept. 30, 2021, 1:38 p.m.

👍


anonymous | May 14, 2021, 6:23 p.m.

Awesome!



Related Courses
Related Courses