Python Introduction

What is python exactly?

• Python is one of the easiest yet most useful high-level, Interpreter programming language which is widely used in the software industry.

But what is a programming language?

A programming language is a set of instructions and syntax used to create software programs.

Where did it came from?

• Python is developed by Guido van Rossum in 1991.

• Rossum was a fan of a comedy series from late seventies. The name "Python" was adopted from the same series "Monty Python's Flying Circus".

Why Python?

There are multiple Features of python which makes it easy and interesting.

What Can You Do with Python?

Who uses Python?

Okay...But what is the meaning of Interpreter language?

Interpreter Compiler
Translates program one statement at a time. Scans the entire program and translates it as a whole into machine code.
Interpreters usually take less amount of time to analyze the source code. However, the overall execution time is comparatively slower than compilers. Compilers usually take a large amount of time to analyze the source code. However, the overall execution time is comparatively faster than interpreters.
No Object Code is generated, hence are memory efficient. Generates Object Code which further requires linking, hence requires more memory.
Programming languages like JavaScript, Python, Ruby use interpreters. Programming languages like C, C++, Java use compilers.

New topic

Python Reserved Keywords

Keyword Description
fromTo import specific parts of a module
globalTo declare a global variable
ifTo make a conditional statement
importTo import a module
inTo check if a value is present in a list, tuple, etc.
isTo test if two variables are equal
lambdaTo create an anonymous function
NoneRepresents a null value
nonlocalTo declare a non-local variable
notA logical operator
orA logical operator
passA null statement, does nothing
raiseTo raise an exception
returnTo exit a function and return a value
TrueBoolean value
tryTo make a try...except statement
whileTo create a while loop
withUsed to simplify exception handling
yieldTo return from a generator

Keyword Description

andA logical operator
asTo create an alias
assertFor debugging
breakTo break out of a loop
classTo define a class
continueTo continue to next loop iteration
defTo define a function
delTo delete an object
elifUsed like else if
elseUsed in conditional statements
exceptUsed with exceptions
FalseBoolean value
finallyExecutes no matter what
forTo create a for loop

Python Reserved Words

Python has a set of keywords that are reserved words that cannot be used as variable names, function names or any other identifiers:

import keyword
k = keyword.kwlist
print(k)

Output:

[
'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'
]

Use len(k) to get the total number of keywords (e.g., 35).

Identifiers

An Identifier is a user-defined name given to variables, functions, classes, objects, etc.

Rules:
  • Keywords cannot be used as identifier names. If you try, it will throw Syntax Error.
  • Python identifiers can contain letters in a small case (a-z), upper case (A-Z), digits (0-9), and underscore (_).
  • Identifiers cannot begin with a digit.
  • Python identifiers can’t contain only digits.
  • Python identifier names can start with an underscore.
  • There is no limit on the length of the identifier name. But it is better kept short.
  • Python identifier names are case-sensitive.

Case Sensitive

• Python is a case-sensitive language.

This means, Variable and variable are not the same.

• Remember this while naming identifiers:

Always give the identifiers a name that makes sense.

For example –

  • c = 10 is a valid name,
  • but writing count = 10 would make more sense,
    and it would be easier to figure out what it represents when you look at your code after a long gap.
Case Sensitivity Example

Types of Literals

  1. String literals:

    A string is literal and can be created by writing a text (a group of Characters) surrounded by a single(‘), double(“), or triple quotes.

# in single quote
s = 'codewithankit'

# in double quotes
t = "codewithankit"

# multi-line String
m = """code
with
ankit"""

print(s)
print(t)
print(m)
      
Output:
codewithankit
codewithankit
code
with
ankit

Types of Literals

  1. String literals:

    A string is literal and can be created by writing a text (a group of Characters) surrounded by a single(‘), double(“), or triple quotes.

    # in single quote
    s = 'codewithankit'
    
    # in double quotes
    t = "codewithankit"
    
    # multi-line String
    m = """code
    with
    ankit"""
    
    print(s)
    print(t)
    print(m)
              
    Output:
    codewithankit
    codewithankit
    code
    with
    ankit
  2. Numeric literal: (Integer, Float, Complex)

    • Integer: Both positive and negative numbers including 0. There should not be any fractional part. We assigned integer literals (0b10100, 50, 0o320, 0x12b) into different variables. Here, ‘a‘ is a binary literal, ‘b’ is a decimal literal, ‘c‘ is an octal literal, and ‘d‘ is a hexadecimal literal.

    # integer literal
    
    # Binary Literals
    a = 0b10100
    
    # Decimal Literal
    b = 50
    
    # Octal Literal
    c = 0o320
    
    # Hexadecimal Literal
    d = 0x12b
    
    print(a, b, c, d)
              
    Output:
    20 50 208 299

    • Float: These are real numbers having both integer and fractional parts.

    # Float Literal
    e = 24.8
    f = 45.0
    
    print(e, f)
              
    Output:
    24.8 45.0

    • Complex: The numerals will be in the form of a + bj, where ‘a’ is the real part and ‘b’ is the complex part.

    z = 7 + 5j
    
    # real part is 0 here.
    k = 7j
    
    print(z, k)
              
    Output:
    (7+5j) 7j
  3. Boolean literals:

    • There are only two Boolean literals in Python. They are true and false.
    True represents the value as 1, and False represents the value as 0.

    Boolean True False
  4. Special literal:

    Python contains one special literal (None). ‘None’ is used to define a null variable.
    If ‘None’ is compared with anything else other than a ‘None’, it will return false.

    water_remain = None
    print(water_remain)
              
    Output:
    None

Statement and Expression

• Statement:
A statement is an instruction that a Python interpreter can execute. So, in simple words, we can say anything written in Python is a statement.

a = 2
print(a)
      
2

• Expression:
An expression is a combination of operators and operands that is interpreted to produce some other value.

b = 2 + 4
print(b)
      
6

Operators

Operators in Python are special symbols that carry arithmetic or logical operations. The value that the operator operates on is called the operand.

Operand
3
Operator
+
Operand
2
= Result
5
Assignment Operators
Arithmetic Operators
Comparison Operators
Logical Operators
Identity Operators
Membership Operators
Bitwise Operators

1. ARITHMETIC OPERATOR

Python Arithmetic operators are used to perform basic mathematical operations like addition, subtraction, multiplication, and division.


a, b = 9, 4
add = a + b
sub = a - b
mul = a * b
mod = a % b
p = a ** b
print(add)
print(sub)
print(mul)
print(mod)
print(p)
        
Operator Operation Example Description
+Additiona+bAdds a and b
-Subtractiona-bSubtracts b from a
*Multiplicationa*bMultiplies a and b
/Divisiona/bDivides a and b
%Modulusa%bGives remainder after dividing a from b
**Exponential3**2=9Ignores the decimal value if present
//Floor Division15//2=7Gives the result of 3 to the power of 2
Output:
13
5
36
1
6561

2. ASSIGNMENT OPERATOR

These are operators used for assigning values to a variable. The values to be assigned must be on the right side, and the variable must be on the left-hand side of the operator.


a = 10
b = a
print(b)
b += a
print(b)
b -= a
print(b)
b *= a
print(b)
b <<= a
print(b)
        
Operator Description Example
=Assigns right side operands to left variable.>>>'number'=10
+=Added and assign back the result to left operand.>>>'number' += 20 # 'number'='number'+20
-=Subtracted and assign back the result to left operand.>>>'number' -= 5
*=Multiplied and assign back the result to left operand.>>>'number' *= 5
/=Divide and assign back the result to left operand.>>>'number' /= 2
%=Taken modulus (Remainder) using two operands and assign the result to left operand.>>>'number' %= 3
**=Performed exponential (power) calculation on operators and assign value to the left operand.>>>'number' **= 2
//=Performed floor division on operators and assign value to the left operand.>>>'number' //= 3
Output:
10
20
10
100
102400

3. COMPARISON OPERATOR

In Python, the comparison operators have lower precedence than the arithmetic operators.


a = 13
b = 33
print(a > b)
print(a < b)
print(a == b)
print(a != b)
print(a >= b)
print(a <= b)
        
Operator Description Example
==If the values of two operands are equal, then the condition becomes true.(a==b) is not true.
!=If the values of two operands are not equal, then the condition becomes true.(a!=b) is true.
<>If the values of two operands are not equal, then the condition becomes true.(a<>b) is true. This is similar to != operator
>If the values of left operand is greater than the value of right operand, the condition is true.(a>b) is not true.
<If the values of left operand is less than the value of right operand, the condition is true.(a<b) is true.
>=If the values of left operand is greater than or equal to the value of right operand, the condition is true.(a>=b) is not true.
<=If the values of left operand is less than or equal to the value of right operand, the condition is true.(a<=b) is true.
Output:
False
True
False
True
False
True

4. LOGICAL OPERATOR

Python logical operators are used to combine conditional statements, allowing you to perform operations based on multiple conditions.


a = True
b = False
print(a and b)
print(a or b)
print(not a)
        
Operator Description Syntax
and Logical AND: True if both the operands are true x and y
or Logical OR: True if either of the operands is true x or y
not Logical NOT: True if the operand is false not x
Output:
False
True
False

5. BITWISE OPERATOR

Bitwise operators are used to perform bit-level operations on integers.

Operator Description Example
& Bitwise AND: Sets each bit to 1 if both bits are 1 5 & 3 = 1
| Bitwise OR: Sets each bit to 1 if one of two bits is 1 5 | 3 = 7
^ Bitwise XOR: Sets each bit to 1 if only one of two bits is 1 5 ^ 3 = 6
~ Bitwise NOT: Inverts all the bits ~5 = -6
<< Left Shift: Shifts bits to the left, adding zeros from right 5 << 1 = 10
>> Right Shift: Shifts bits to the right, discarding bits 5 >> 1 = 2

Example Code:

a = 5  # 0b0101
b = 3  # 0b0011

print(a & b)  # Output: 1 (0b0001)
print(a | b)  # Output: 7 (0b0111)
print(a ^ b)  # Output: 6 (0b0110)
print(~a)     # Output: -6 (invert bits)
print(a << 1) # Output: 10 (shift left)
print(a >> 1) # Output: 2 (shift right)
        

6. IDENTITY OPERATORS

Identity operators are used to compare the memory locations of two objects.

Operator Description Example
is Returns True if both variables point to the same object a is b
is not Returns True if both variables do not point to the same object a is not b

Example Code:

a = [1, 2, 3]
b = a
c = [1, 2, 3]

print(a is b)      # True
print(a is c)      # False
print(a is not c)  # True
        

7. MEMBERSHIP OPERATORS

Membership operators test whether a value or variable is found in a sequence (string, list, tuple, set, etc.).

Operator Description Example
in Returns True if a value is found in the sequence 5 in list
not in Returns True if a value is not found in the sequence 5 not in list

Example Code:

list = [1, 2, 3, 4, 5]

print(3 in list)       # True
print(6 not in list)   # True