Python

 

 

image.png

What is Python?

Python is a high-level, object-oriented programming language developed by Guido van Rossum. This means that Python is based around data and is easily understood by humans.

What is Python used for?

Python is commonly used for developing websites and software, task automation, data analysis, and data visualization. Since it’s relatively easy to learn, Python has been adopted by many non-programmers, such as accountants and scientists, for a variety of everyday tasks, like organizing finances.

What can you do with python? Some things include:

Data analysis and machine learning

Web development

Automation or scripting

Software testing and prototyping

Data analysis and machine learning

Python has become a staple in data science, allowing data analysts and other professionals to use the language to conduct complex statistical calculations, create data visualizations, build machine learning algorithms, manipulate and analyze data, and complete other data-related tasks.

Python can build a wide range of different data visualizations, like line and bar graphs, pie charts, histograms, and 3D plots. Python also has a number of libraries that enable coders to write programs for data analysis and machine learning more quickly and efficiently, like TensorFlow and Keras.

Nutshell Tips:

Case – Sensitive Language

Counting or Indexing starts from 0

Read the Error from below

Did you know? The name Python comes from Monty Python. When Guido van Rossum was creating Python, he was also reading the scripts from BBC’s Monty Python’s Flying Circus. He thought the name Python was appropriately short and slightly mysterious.

image-2.png

In last, Python is super easy to learn but hard to master !!

In [22]:
print("Hello")
Hello
In [23]:
print("Hello, World")
Hello, World

image.png

In [ ]:
print("Basic Syntax of Python")
In [ ]:
# This is a comment
In [ ]:
a=7
print(a)
In [ ]:
b=5
print(b)
In [ ]:
# Simple Maths

print(a+b)
In [ ]:
c=a+b
print(c)
In [ ]:
# Multiply

a=1.5

a*2 
In [ ]:
a+1
In [ ]:
# Lets check the type of variable

type(a)
In [ ]:
type(b)
In [ ]:
d=2.5
type(d)
In [ ]:
# Adding an Integer & Float gives float

a=7
b=5.5
a+b
In [ ]:
type(a+b)
In [ ]:
# a=b is b=a ? 
In [ ]:
# Multiplying an String with Integer is allowed in python

Name ='DataMantra'
Name*2
In [ ]:
# Addition an String with Integer is allowed in python ?
# Let's check

Name ='DataMantra'
Name + 2
In [ ]:
Name ='DataMantra'
type(Name)
In [ ]:
# Superuseful function - Help with all In-built functions

help()
In [ ]:
# Seek help

help(str)
In [ ]:
help(int)
In [ ]:
# Declaring the Int var
Number = 100
 
# Display
print( Number)

# Declaring the String var ( Strings always needs to be in " ")
Name = 'DataMantra'

# Display
print(Name)

# 1st Trick
print(Name,Number)
In [ ]:
'single quotes'
In [ ]:
"double quotes"
In [ ]:
" wrap lot's of other quotes"
In [ ]:
Age = 12
name = 'Tarun'
In [ ]:
print('My Age is: {one}, and my name is: {two}'.format(one=Age,two=name))

print(‘My Age is: {}, and my name is: {}’.format(Age,name))

In [ ]:
price = 10
print(price)
In [ ]:
# Python Interprets the code line by line

price = 10
price = 20
print(price)
In [ ]:
# Working with Float & Boolean Data Types 
Rating = 4.9
is_published = True

print(Rating)
print(is_published)

Boolean Datatypes

The boolean is a data type that has only two values (Yes/No) or (True/False) or (0/1)

image.png

In [ ]:
True
In [ ]:
False

Example of checking bool() on strings:

Only an empty string is False, the rest of the strings are considered to be True. Even the string with space is True, as space is also a character in Python.

In [ ]:
bool(" ")
In [ ]:
bool("")
In [ ]:
bool('PythonGeeks')

# Boolean with Lists, tuples, and dictionaries:

These will be boolean False if they do not have **any element or they are empty else, these are True.**

In [ ]:
bool(())
In [ ]:
bool((1,2))
In [ ]:
bool([])
In [ ]:
bool(['t'])
In [ ]:
bool({})
In [ ]:
bool({4:'c'})

# Boolean with Membership operators

The operators **’in’and ‘not in’** are the two membership operators.

The ‘in’ gives **True** if the element is in the sequence, else returns **False.** The operator ‘not in’ does the opposite.

In [ ]:
'e' in 'PythonGeeks'
In [ ]:
5 not in [1,3,4,5.0,8]
In [ ]:
6.7 in (1,5,'t')

Boolean with Comparison Operators

In Python, we have six comparison operators and these are ==,!=,<,<=,>,>=. These give True if the values satisfy the condition of the first operand is

a. equal to the second one for ==

b. not equal the second one for !=

c. less than the second one for <

d. less than or equal to the second one for <=

e. greater than the second one for >

g. f. greater than or equal to the second operand for >=.

image.png

In [1]:
1 > 2
Out[1]:
False
In [2]:
4.5 == 7
Out[2]:
False
In [3]:
1 < 2
Out[3]:
True
In [4]:
1 >= 1
Out[4]:
True
In [5]:
1 <= 4
Out[5]:
True
In [7]:
1 == 1
Out[7]:
True
In [6]:
'hi' == 'bye'
Out[6]:
False

Logical Operators

The operators and, or, are the logical operators in Python.

AND – The ‘and’ gives True if both the operands are True else returns False.

OR – The ‘or’ gives True if at least one of the operands is True else returns False.

not – It is a unary operator that is used to negate the expression after succeeding the operator. According to this, every True expression becomes False, and vice versa.

Consider the statement:

Sunita will not go to school.
If the above statement is true, the statement ‘Sunita will go to school’ would be false.
Thus, not interchanges True and False values.

In [8]:
(1 > 2) and (2 < 3)
Out[8]:
False
In [9]:
(1 > 2) or (2 < 3)
Out[9]:
True
In [10]:
(1 == 2) or (2 == 3) or (4 == 4)
Out[10]:
True
In [11]:
x = True
y = False
print(not x)
print(not y)
False
True

image.png

image.png

Variable

Python Variable is containers that store values.

A variable is created the moment we first assign a value to it.

A Python variable is a name given to a memory location or we can say a reference or pointer to an object. Once an object is assigned to a variable, we can refer to the object by that name.

It is the basic unit of storage in a program.

https://realpython.com/python-variables/#:~:text=A%20Python%20variable%20is%20a,still%20contained%20within%20the%20object.

In [ ]:
# Assigning a variable n whose value is 300

n = 300
print(n)

This assignment creates an integer object with the value 300 and assigns the variable n** to point to that object.

image.png

Now consider the following statement:

m = n

What happens when it is executed? Python does not create another object. It simply creates a new symbolic name or reference, m, which points to the same object that n points to.

image.png

In [ ]:
m = n

Next, suppose we do this:

m = 400

Now Python creates a new integer object with the value 400, and m becomes a reference to it.

image.png

Lastly, suppose this statement is executed next:

n = “foo”

Now Python creates a string object with the value “foo” and makes n reference that.

image-2.png

There is no longer any reference to the integer object 300. It is orphaned, and there is no way to access it.An object’s life begins when it is created, at which time at least one reference to it is created.

An object stays alive, as it were, so long as there is at least one reference to it.

When the number of references to an object drops to zero, it is no longer accessible. At that point, its lifetime is over. Python will eventually notice that it is inaccessible and reclaim the allocated memory so it can be used for something else. In computer lingo, this process is referred to as garbage collection.

Rules for Python variables

  • A Python variable name must start with a letter or the underscore character.
                                        **OR**

Officially, variable names in Python can be any length and can consist of uppercase and lowercase letters (A-Z, a-z), digits (0-9), and the underscore character (_). An additional restriction is that, although a variable name can contain digits, the first character of a variable name cannot be a digit.

  • A Python variable name cannot start with a number.
  • Variable in Python names are case-sensitive (name, Name, and NAME are three different variables).

Object Identity

In Python, every object that is created is given a number that uniquely identifies it. It is guaranteed that no two objects will have the same identifier during any period in which their lifetimes overlap.

Once an object’s reference count drops to zero and it is garbage collected, as happened to the 300 object above, then its identifying number becomes available and may be used again.

The built-in Python function id() returns an object’s integer identifier.

Using the id() function, we can verify that two variables indeed point to the same object:

In [ ]:
n = 300
print(id(n))

m = n
print(id(m))

m = 400
print(id(m))
In [ ]:
hex(id(n))
In [ ]:
bin(id(n))

Advanced

Deep Dive: Caching Small Integer Values

From what you now know about variable assignment and object references in Python, the following probably won’t surprise you:

m = 300
n = 300

id(m)
60062304

id(n)
60062896

With the statement m = 300, Python creates an integer object with the value 300 and sets m as a reference to it. n is then similarly assigned to an integer object with value 300—but not the same object. Thus, they have different identities, which you can verify from the values returned by id().

m = 30
n = 30

id(m)
1405569120

id(n)
1405569120

Here, m and n are separately assigned to integer objects having value 30. But in this case, id(m) and id(n) are identical!n

For purposes of optimization, the interpreter creates objects for the integers in the range [-5, 256] at startup, and then reuses them during program execution. Thus, when you assign separate variables to an integer value in this range, they will actually reference the same object.

Great Job !!

User Inputs

The input() function takes input from the user and returns it.

image.png

In [ ]:
First_Name = input("What is your First Name ")
print(First_Name)
In [ ]:
Family_Name = input("What is your Family Name ")
print(Family_Name)
In [ ]:
print (First_Name + " " + Family_Name )
In [ ]:
Name = input("What is your Name ")
print("Hi" + " " + First_Name )
In [ ]:
## STRING FUNCTIONS

## Upper - Converts the String to Capital Letters.

Name = 'DataMantra'
print(Name.upper())

image.png

In [ ]:
## Lower - Converts the String to small Letters.

Name = 'DataMantra'
print(Name.lower())

OR

In [ ]:
Name = 'DataMantra'
print(Name.casefold())

image.png

image.png

In [ ]:
Name = 'DataMantra'
print(Name.title())

OR

In [ ]:
Name = 'DataMantra'
print(Name.capitalize())

image.png

In [ ]:
# Lets find the age & Solve the Error

birth_year = input("What is your Birth year")
Age = 2023- (birth_year)
print((Age))
In [ ]:
type(birth_year)
In [ ]:
#type(Age)
In [ ]:
# Using int function will do this

birth_year = input("What is your Birth year")
Age = 2023- int(birth_year)
print((Age))
In [ ]:
# Check the Length of String - Similiar Use case in SQL,Tableau & Power BI

Name ='Python'
len(Name)

image.png

image.png

In [ ]:
# Single Inverted Comma's or Double ?

course = 'Python's Course for Beginners'
In [ ]:
# Recommended to use double Inverted Commas

course = "Python's Course for Beginners"
print(course)
In [ ]:
# Tip 

Email = '''

Hi Tarun

Here is our first email to you

Thanks
Contact Team - DataMantra

'''

print(Email)

if else & elif Conditions

If the if condition around the block of the statements is TRUE, then it will be executed; otherwise, the else block of the statements will be executed.

Below is the if-else syntax in python.

if expression

Statement

else

Statement


Quick Note: Indentation, the whitespace at the beginning of a line, plays an important role while working with if else in python programming. It is often used to define the scope of the program, while in other programming languages, we often make use of curly brackets to serve the purpose. It is important to take proper care of the indentation while coding with if – elif – else; otherwise, you will encounter IndentationError while executing the code.

Python relies on indentation (whitespace at the beginning of a line) to define scope in the code.

image.png

In [13]:
if 1 < 2:
    print('Yep!')
Yep!

Else

The else keyword catches anything which isn’t caught by the preceding conditions.

In [14]:
if 1 < 2:
    print('first')
else:
    print('last')
first
In [15]:
if 1 > 2:
    print('first')
else:
    print('last')
last
In [ ]:
a = 33
b = 200
if b > a:
  print("b is greater than a")
In [ ]:
# Python relies on indentation (whitespace at the beginning of a line) to define scope in the code. 

a = 33
b = 200
if b > a:
print("b is greater than a") # you will get an error

image.png

image.png

Elif

The elif keyword is Python’s way of saying “if the previous conditions were not true, then try this condition”.

image.png

In [16]:
if 1 == 2:
    print('first')
elif 3 == 3:
    print('middle')
else:
    print('Last')
middle
In [ ]:
a = 33
b = 33
if b > a:
  print("b is greater than a")
elif a == b:
  print("a and b are equal")
In [ ]:
a = 200
b = 33
if b > a:
  print("b is greater than a")
elif a == b:
  print("a and b are equal")
else:
  print("a is greater than b")
In [17]:
## The and keyword is a logical operator, and is used to combine conditional statements:

a = 200
b = 33
c = 500
if a > b and c > a:
  print("Both conditions are True")
b is greater than a
In [ ]:
# The or keyword is a logical operator, and is used to combine conditional statements.

a = 200
b = 33
c = 500
if a > b or a > c:
  print("At least one of the conditions is True")
In [19]:
# The not keyword is a logical operator, and is used to reverse the result of the conditional statement.

a = 33
b = 200
if not a > b:
  print("a is NOT greater than b")
a is NOT greater than b
In [20]:
# if statements cannot be empty,but for some reason you have an if statement with no content, put in the pass statement to
# avoid getting an error.


a = 33
b = 200

if b > a:
  pass
In [ ]:
# Python program to illustrate short hand if
i = 10
if i < 15: print("i is less than 15")

image.png

Great Job !!

Congrats, you have completed the Basics.