Python in a Nutshell! 🙃(Part-1)

Vicky Kumar
13 min readAug 21, 2022
Photo by David Clode on Unsplash

This article teaches you the basics of python in very less time. If you are a college student or a programmer or a hacker who want to revise all the python concept for your exam or just forgot it due to not Practicing from a long while you can refer to it.

Note: If you are a beginner to learn python don’t totally depend on it. Just select a topic from here and learn it on the internet in a deep manner.

Intro to Python Programming language

Python is a general-purpose interpreted, interactive, object-oriented, and high-level programming language. It was created by Guido van Rossum in the late eighties and early nineties at the National Research Institute for Mathematics and Computer Science in the Netherlands.

Python is an easy-to-learn programming language that has some really useful features for a beginner programmers. The code is quite easy to read when compared to other programming language, and it has an interactive shell into which you can enter your programs and see them by run.

It has efficient high-level data structure 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.

If you want to know more on how program works on system and run Please check out this post

Python Identifiers

A Python identifier is a name used to identify a variable, function, class, module, or other object. An identifier starts with a letter A to Z or a to z or an underscore (_) followed by zero or more letters and digits (0 to 9).

Python does not allow punctuation characters such as @, $ and % within the identifiers. Python is case sensitive programming language. Thus variable1 and Variable1 are two different identifiers in Python.

Here are following identifier naming convention for Python.

  • Class names start with an uppercase letter and all other identifiers with a lowercase letter.
  • Starting an identifier with a signal leading underscore indicates by convention that the identifier is meant to be private
  • Starting an identifier with two leading underscores indicates a strongly private identifier.
  • If the identifier also ends with two trailing underscore, the identifier is a language-defined special name.

Reserve Words

The following list shows the reserved words in Python. These reserved words may not be used as constant or variable or any other identifier names.

|…………………………………………………………………………………..| |and | exec | not | assert | finally | or | break | for | pass | class | from | |print | continue | global | raise | def | if | return | del | import | try | elif | | in | while | else | is | with | except | lambda | yield | |………………………………………………………………………………….|

Quotation in Python

Python accepts single (‘), double (“) and triple (‘’’ or “””) quotes to denote string literals, as long as the same type of quote starts and ends the string.

word= ‘word’sentence= “This is a sentence”paragraph=””” This is a paragraph. It is made up of multiple lines and sentences.”””

Comments in Python

Python supports two types of comments first one is single line comment and the second one is multi-line comment

A hash sign (#) that is not inside a string literal begins a comments. All characters after the # and up to the physical line end are part of the comment and the Python interpreter ignores them.

# This is a single line comment

Triple quotes (“””) is used to write multi-line comment in python.

“””
This is a comment
written in
more than just one line
“””

Multiple Statements on a single line

The semicolon (;) allows multiple statements on the single line given that neither statement starts a new code block. Here is a sample snip using the semicolon:

a=10 ; print(‘value of a is :’,a)

Python Variable Types

Variables are nothing but reserved memory locations to store values.This means that when you create a variable you reserve some space in memory. Based on the data type of a variable, the interpreter allocates memory and decides what can be stored in the reserves memory. Therefore, by assigning different data type to variables, you can store integers, decimals, or characters in these variables.

The operand ot the left of the = operator is the name of the variable, and the operand to the right of the = operator is the value stored in the variable.

number=100 # An integer assignment
salary=600.34 # A floating point
name=”elliot” # A string

Standard Data Types in Python

  • Numbers
  • String
  • List
  • Tuple
  • Dictionary

Python Numbers

Number objects are created when you assign a value to them. Fore example:

var1=10

var2=20

Python supports four different numerical types:

  • int (signed integers)
  • long (long integers [can be in octal or hexadecimal])
  • float (floating point real values)
  • complex (complex numbers)

Python Strings

Strings in Python are identified as a contiguous set of characters in between quotation marks.

str=’Hello Python!’
print(str) #it prints complete string

Python Lists

Lists are the most versatile of Python’s compound data types. A list contains items separated by commas and enclosed within square brackets([]).

list=[‘hello’, 1234, 13.32]
smllist=[‘world’, 8055]
print(list) # it prints list
print(list + smllist) # it prints concatenated lists

Python Tuples

A tuple is another sequence data type that is similar to the list. A tuple consists of a number of values separated by commas. Unlike lists, however tuples are enclosed within parentheses.

Tuples can be thought of as read-only lists. It can’t be modified or alter. It is immutable in nature.

tuple=(‘malware’,2345,18.0,)
smltuple=(132,’elliot’)
print(tuple) #Prints complete list
print(tuple + smltuple) #Prints concatenated list

Python Dictionary

Python’s dictionaries are hash table type. They work like associative arrays or hashes found in Perl and consists of key-value pairs.

smldict={‘name’:’alex’, ‘code’:1280, ‘dept’:’HR’}
print(smldict[‘name’]) # Prints value for name key
print(smldict[‘dept’]) # Prints value for dept key
print(smldict) # Prints complete dictionary
print(smldict.keys()) # Prints all keys
print (smldict.values()) #prints all values
Photo by Jeswin Thomas on Unsplash

Python Basic Operators

Operators are special symbols that are used to perform some operation.

The different types of operators supported by Python are as follows:

  1. Arithmetic Operators
  2. Relational Operators
  3. Logical Operators
  4. Bitwise Operators
  5. Assignment Operators
  6. Identity Operators
  7. Membership Operators

Arithmetic Operators

Arithmetic operators are used in performing mathematical operations such as Addition, Subtraction, Multiplication, Division, Modulus, Floor Division, and Exponent.

Example

Below is the simple python snippet that you can use as a reference:

# Assigning values to variables
a = 10
b = 5# Addition
print('a + b =', a + b)# Subtraction
print('a - b =', a - b)# Multiplication
print('a * b =', a * b)# Division
print('a / b =', a / b)# Modulus
print('a % b =', a % b)# Floor Division
print('a // b =', a // b)# Exponent
print('a ** b =', a ** b)

When you run the above python script you will be prompted by the following output

a + b = 15 
a - b = 5
a * b = 50
a / b = 2.0
a % b = 0
a // b = 2
a ** b = 100000

Important Notes

  • If you divide any number by 0 then you will be prompted by an error called ZeroDivisionError. Don’t divide anything by zero (0).
  • The result generated by the division operator will always be floating number (represented in decimal points).
  • Floor division returns the quotient(answer or result of division) in which the digits after the decimal point are removed. But if one of the operands(dividend and divisor) is negative, then the result is floored, i.e., rounded away from zero(means, towards the negative of infinity).

Relational Operators

Relational operators or comparison operators as their name suggest are used in comparing the values. The return type of these operators are either True or False. The different comparison operators are Greater than, Greater than or equal to, less than, lesser than or equal to, equal to, and not equal to.

Example

Below is the simple python snippet that you can use as a reference:

# Assigning values to variables
a = 10
b = 5# Greater than
print('a > b =', a > b)# Lesser than
print('a < b =', a < b)# Equal to
print('a == b =', a == b)# Not equal to
print('a != b =', a != b)# Greater than or equal to
print('a >= b =', a >= b)# Lesser than or equal to
print('a <= b =', a <= b)

When you run the above python script you will be prompted by the following output

a > b = True 
a < b = False
a == b = False
a != b = True
a >= b = True
a <= b = False

Important notes

  • Relational operators are also called comparison operators.
  • The comparison operator can be used to compare more than two values. For example 5 > 3 < 1 will result in False.
  • These are also called as relational operators because it compares the value and then decides the relation among them. For example, 5 > 4 the relation is such that 5 is greater than 4 and the answer is True. The relation here is greater.

Logical Operators

Logical operators are used to evaluate the conditions between the operands. The different type of operators are and, orand not.

To make things more clear you can refer to the truth table of the logical operators given below:

Example

Below is the simple python snippet that you can use as a reference:

# Assigning values to variable
a = True
b = False# Logical and
print('a and b is',a and b)# Logical or
print('a or b is',a or b)# Logical not
print('not a is',not a)

When you run the above python script you will be prompted by the following output

a and b is False 
a or b is True
not a is False

Important notes

  • Logical operators are also called as Boolean Operators.
  • If the operands are not boolean then it would be automatically converted to a boolean for the evaluation.
  • The logical operators can be applied to any type of value. For example, they can be applied to strings as shown below. In this case, the and operator returns the first false value if there are null or false values otherwise, they return the last value. The or returns the first true value if there are any otherwise returns the last value.

Logical “and” operator on Strings

a = ""
b = "Python"
a and b''

Logical “or” operator on Strings

a = ""
b = "Python"
a or b 'Python'
  • In both the cases of and, or the evaluation is done from left to right.

Bitwise Operators

Bitwise operators operate on operands at a binary level. Meaning the bitwise operator looks directly at the binary digits or binary bits of an integer. Hence the name bitwise (bit by bit operation). The different types of bitwise operators are Bitwise AND, OR, NOT, XOR, Right Shift, and Left Shift.

Example

Below is the simple python snippet that you can use as a reference:

# Assigning values to variables
a = 10
b = 11# Bitwise AND
print('a & b is',a & b)# Bitwise OR
print('a | b is',a | b)# Bitwise XOR
print('a ^ b is',a ^ b)# Bitwise NOT
print('~a is',~a)# Bitwise Left Shift
print('a << b is',a << b)# Bitwise Right Shift
print('a >> b is',a >> b)

When you run the above python script you will be prompted by the following output

a & b is 10 
a | b is 11
a ^ b is 1
~a is -11
a << b is 20480
a >> b is 0

Important Notes

  • Bitwise operator works on bits and performs a bit by bit operation on the operands.
  • No matter the type of operands you pass, the bitwise operator will convert it to a series of binary digits respectively. For example, if an operand is 2 then its binary format is 10, similarly, 9 will be rendered as 1001 and so on. Below is the truth table of bitwise operators excluding left and right shift operators.

Assignment Operators

As the name suggests assignments operators are used to assigning the values to the variables. Let me give you a simple example.

a = 5

Many at times people make mistakes while reading the above line of code. People say “a equals to 5”, this might sound correct, but programmatically it’s incorrect. The correct way is:

The value 5 is assigned to the variable ‘a’

Because the way the assignment operator works is that it assigns the value from the right to the variable on to the left. So remember its right to left.

Example

Below is the simple python snippet that you can use as a reference:

# Assigning the values to variables
a = 15
b = 5# Simple assignment operator
b = a
print('b = a: ',b)# ADD AND operator
b += a
print('b += a: ', b)# SUBTRACT AND operatpr
b -= a
print('b -= a: ', b)# MULTIPLICATION AND operator
b *= a
print('b *= a: ', b)# DIVISION AND operator
b /= a
print('b /= a: ', b)# FLOOR AND operator
b //= a
print('b //= a: ', b)# MODULUS AND operator
b %= a
print('b %= a: ', b)# EXPONENT AND operator
b **= a
print('b **= a: ', b)# LESS THAN AND operator
b <= a
print('b <= a: ', b)# GREATOR THAN AND operator
b >= a
print('b >= a: ', b)# BINARY AND operator
a &= 5
print('a &= 5: ', a)# BINARY OR operator
a |= 5
print('a |= 5: ', a)

When you run the above python script you will be prompted by the following output

b = a:   15 
b += a: 30
b -= a: 15
b *= a: 225
b /= a: 15.0
b //= a: 1.0
b %= a: 1.0
b **= a: 1.0
b <= a: 1.0
b >= a: 1.0
a &= 5: 5
a |= 5: 5

Notes

  • We can extend the assignment operators for more operators such as -, /, *, //, %, <<, >>, &, |, **, ^. For example: a **= 5, will be a = a**5, the answer would be 298023223876953125. Make sure that you write the operator followed by the assignment operator.

Special Operators

There are two types of special operators in a python programming language as shown below:

Identity Operators

As the name suggests the identity operators compare the id (identity) of two or more python objects such as variables, values, and many more. In other words, others say that the identity operator can also be used to compare the memory locations of two objects. There are two types of identity operators namely is and is not.

Example

Below is the simple python snippet that you can use as a reference:

# Assigning values to variables
a = 10
b = 11# Identity is operator
print('a is b is',a is b)# Identity is not operator
print('a is not b is',a is not b)

When you run the above python script you will be prompted by the following output

a is b is False 
a is not b is True

Important Notes

  • In general, the identity operator does not compare the value or object itself. Rather it compares the id’s (identity). Below is an example:
# Assigning the values to variables
a = 5
b = 5
c = a# Getting the id of the variables
print(id(a))
print(id(b))
print(id(c))# Comparing the id of a and c
print(a is c)

To compare the id’s you can use the id function in python. It returns the id of the memory location.

id of a is: 10914624 
id of b is: 10914624
id of c is: 10914624
True

Membership Operators

Membership operators are used to verifying whether a particular element is a part of a sequence or not. Now a sequence can be a list, string, sets, dictionary, and tuples. The two membership operators are in and not in.

Example

Below is the simple python snippet that you can use as a reference:

# Assigning a string value to a variable
a = "Python"# Type of the variable
print(type(a))# Checking whether 'y' is present in the variable a or not
print('y' in a)# Checking whether 'P' is present in the variable a or not
print('p' not in a)

When you run the above python script you will be prompted by the following output

<class 'str'> 
True
True

Important Notes

  • While we can use membership operators on dictionaries but there is one thing you should know i.e. we can only test for the presence of the key and not the value as shown below:
# Dictionary with key as 1, 2 and values as 'A' and 'B'
a = {1: "A", 2: 'B'}# Using 'in' operator
print(2 in a)# Using 'not in' operator
print(3 not in a)

Hence the output of the above will be:

True 
True

Python Operator Precedence

The following table list all operators from highest precedence to lowest.

operator_precedence

And this is it. 🥂 Enjoy python scripting today and wait for next part.🤸‍♂️

Feel free to Subscribe for more content 🔔, clap 👏🏻 and share the article With anyone you’d like.

--

--

Vicky Kumar

I am an Ethical Hacker 👩‍💻 | Security Researcher 📖 | Open Source Contributor 🤝| Bug Hunter🐞| Penetration Tester💻| Python Lover ❤️ | DevSecOps Explorer 🕵️