PYTHON
INTRODUCTION TO PYTHON
Python is a popular programming language. It was created by Guido van
Rossum, and released in 1991.
It is used for:
web development (server-side),
software development,
mathematics,
system scripting.
What can Python do Actually?
Python can be used on a server to create web applications.
Python can be used alongside software to create workflows.
Python can connect to database systems. It can also read and
modify files.
Python can be used to handle big data and perform complex
mathematics.
Python can be used for rapid prototyping, or for production-ready
software development.
Lets Get Started
This is print Function!
print("Hello, World!")
It is used to display Whatever value
is given with function bracket, ‘()’.
so the out put of the above code
will be Hello, World!
Now You Have Noticed Why There
is an “”, Or Double Quotes. It is to
assign that the value inside it is an
string or STR for short. You can use
single quotes, ‘’ too!
PYTHON SYNTAX
Python Indentation
Indentation refers to the spaces at the beginning of a code line.
Where in other programming languages the indentation in code is
for readability only, the indentation in Python is very important.
Python uses indentation to indicate a block of code.
For Example:
if 10 > 3:
print(“Its Greater”)
As you can see in the above there is a indentation before print to
indicate that the print function should be triggered when the if
statement is true. It could anything else other than “if”. We Will learn
more about if-else program later!
If the Indentation is not There then it will show as error as the if state
has no block to run too.
For Example:
if 10 > 3:
print(“Its Greater”)
This will show an Error!
The Number of Spaces is upto you!
But you have to use the same number of spaces in the same block of
code, otherwise Python will give you an error:
if 10 > 3:
print(“Its Greater”)
print(“Its 10”)
PYTHON COMMENTS
Comments can be used to explain Python code.
Comments can be used to make the code more readable.
Comments can be used to prevent execution when testing code.
Comments starts with a #, and Python will ignore them:
Example:
#This is a comment
print("Hello, World!")
There is another way of commenting!
instead of multi commenting like this:
#This is a comments
#This is the second comment
#This is the third comment
print("Hello, World!")
You can:
"""
This is a comments
This is the second comment
This is the third comment
"""
print("Hello, World!")
PYTHON VARIABLES
Variables are containers for storing data values.
A variable is created the moment you first assign a value to it.
For Example:
x=1
y=”Gagan"
print(x)
print(y)
Casting
If you want to specify the data type of a variable, this can be done
with casting.
For Example:
x = str(3) # x will be '3'
y = int(3) # y will be 3
z = float(3) # z will be 3.0
Variables do not need to be declared with any particular type, and can
even change type after they have been set.
so,
x=”sahil” is a string even x = “1”
is also string since we put in quotes
x=1 is an integer.
PYTHON DATATYPES
Built-in Data Types
In programming, data type is really important.
Variables can store data of different types, and different types can do
different things.
Here Are The Data Types:
Text Type:
str
Numeric Types:
int, float, complex
Sequence Types:
list, tuple, range
Mapping Type:
dict
Set Types:
set, frozenset
Boolean Type:
bool
Binary Types:
bytes, bytearray, memoryview
None Type:
NoneType
Getting the Data Type
You can get the data type of any object by using the type() function:
x=”1"
print(type(x)) #output will be str or string
PYTHON STRINGS
Strings in python are surrounded by either single quotation marks, or
double quotation marks.
'hello' is the same as "hello".
Multiline Strings
You can assign a multiline string to a variable by using three quotes:
a = """Python is reallly cool
and amazing. I want to learn
Python!"""
print(a)
String Length
To get the length of a string, use the len() function.
x=”sahil”
print(len(x)) #output will be 5
Slicing
You can return a range of characters by using the slice syntax.
Specify the start index and the end index, separated by a colon, to
return a part of the string.
x = "Hello, World!"
print(x[2:5])
The upper() method returns the string in upper case:
a = "Hello, World!"
print([Link]())
The lower() method returns the string in lower case:
a = "Hello, World!"
print([Link]())
PYTHON STRINGS 2
The strip() method removes any whitespace from the beginning or the
end:
a = " Hello, World! "
print([Link]()) # returns "Hello, World!"
The replace() method replaces a string with another string:
a = "Hello, World!"
print([Link]("H", "J"))
The split() method splits the string into substrings if it finds instances of
the separator:
a = "Hello, World!"
print([Link](",")) # returns ['Hello', ' World!']
String Concatenation
To concatenate, or combine, two strings you can use the + operator.
For Example:
Merge variable a with variable b into variable c:
a = "Hello"
b = "World"
c=a+b
print(c) #output will be HelloWorld
String Format
As we learned in the Python Variables chapter, we cannot combine
strings and numbers like this:
For Example:
age = 36
txt = "My name is John, I am " + age
print(txt) #this is an error
PYTHON STRINGS 3
But we can combine strings and numbers by using the format() method!
The format() method takes the passed arguments, formats them, and
places them in the string where the placeholders {} are:
Use the format() method to insert numbers into strings:
age = 36
txt = "My name is John, and I am {}"
print([Link](age)) #output will be My name is John, and i am 36
Escape Character
To insert characters that are illegal in a string, use an escape character.
An escape character is a backslash \ followed by the character you want
to insert.
An example of an illegal character is a double quote inside a string that
is surrounded by double quotes:
For Example:
You will get an error if you use double quotes inside a string that is
surrounded by double quotes:
txt = "We are the so-called "Vikings" from the north."
To fix this problem, use the escape character \":
For Example:
The escape character allows you to use double quotes when you
normally would not be allowed:
txt = "We are the so-called \"Vikings\" from the north."
\' Single Quote \f Form Feed
\\ Backslash \ooo Octal value
\n New Line \xhh Hex value
\r Carriage Return
\t Tab
\b Backspace
String Methods
capitalize()
Converts the first character to upper case
casefold()
Converts string into lower case
center()
Returns a centered string
count()
Returns the number of times a specified value occurs in a string
encode()
Returns an encoded version of the string
endswith()
Returns true if the string ends with the specified value
expandtabs()
Sets the tab size of the string
find()
Searches the string for a specified value and returns the position of
where it was found
format()
Formats specified values in a string
format_map()
Formats specified values in a string
index()
Searches the string for a specified value and returns the position of
where it was found
isalnum()
Returns True if all characters in the string are alphanumeric
isalpha()
Returns True if all characters in the string are in the alphabet
isascii()
Returns True if all characters in the string are ascii characters
isdecimal()
Returns True if all characters in the string are decimals
isdigit()
Returns True if all characters in the string are digits
String Methods 2
isidentifier()
Returns True if the string is an identifier
islower()
Returns True if all characters in the string are lower case
isnumeric()
Returns True if all characters in the string are numeric
isprintable()
Returns True if all characters in the string are printable
isspace()
Returns True if all characters in the string are whitespaces
istitle()
Returns True if the string follows the rules of a title
isupper()
Returns True if all characters in the string are upper case
join()
Joins the elements of an iterable to the end of the string
ljust()
Returns a left justified version of the string
lower()
Converts a string into lower case
lstrip()
Returns a left trim version of the string
maketrans()
Returns a translation table to be used in translations
partition()
Returns a tuple where the string is parted into three parts
replace()
Returns a string where a specified value is replaced with a specified
value
rfind()
Searches the string for a specified value and returns the last position
of where it was found
rindex()
Searches the string for a specified value and returns the last position
of where it was found
String Methods 3
rjust()
Returns a right justified version of the string
rpartition()
Returns a tuple where the string is parted into three parts
rsplit()
Splits the string at the specified separator, and returns a list
rstrip()
Returns a right trim version of the string
split()
Splits the string at the specified separator, and returns a list
splitlines()
Splits the string at line breaks and returns a list
startswith()
Returns true if the string starts with the specified value
strip()
Returns a trimmed version of the string
swapcase()
Swaps cases, lower case becomes upper case and vice versa
title()
Converts the first character of each word to upper case
translate()
Returns a translated string
upper()
Converts a string into upper case
zfill()
Fills the string with a specified number of 0 values at the beginning
Boolean Values
In programming you often need to know if an expression is True or
False.
You can evaluate any expression in Python, and get one of two answers,
True or False.
When you compare two values, the expression is evaluated and Python
returns the Boolean answer
Operators
Operators are used to perform operations on variables and values.
In the example below, we use the + operator to add together two
values:
print(68 + 1)
Python divides the operators in the following groups:
Arithmetic operators
Assignment operators
Comparison operators
Logical operators
Identity operators
Membership operators
Bitwise operators
Python Arithmetic Operators
Addition(+) -> x + y
Subtraction(-) -> x - y
Multiplication(*) -> x*y
t
Division(/) and Floor division(//) -> x/y and x//y(this is for no decimal to
be shown)
Modulus(%) -> x % y
Exponentiation(**) -> x ** y
Operators 2
Comparison Operators
Comparison operators are used to compare two values:
Equal(==) -> x == y
t»
Not equal(!=) -> x != y
Greater than(>) -> x > y
Less than(<) -> x < y
Greater than or equal to(>=) -> x >= y
Try it »
Less than or equal to(<=) -> x <= y
Python Logical Operators
Logical operators are used to combine conditional statements:
and(Returns True if both statements are true):
x < 5 and x < 10
or(Returns True if one of the statements is true)
x < 5 or x < 4
not(Reverse the result, returns False if the result is true)
not(x < 5 and x < 10)
Identity operators
Identity operators are used to compare the objects, not if they are
equal, but if they are actually the same object, with the same memory
location:
is(Returns True if both variables are the same object)
x is y
is not(Returns True if both variables are not the same object)
x is not y
Collections of data
List
Lists are used to store multiple items in a single variable.
Lists are one of 4 built-in data types in Python used to store collections
of data, the other 3 are Tuple, Set, and Dictionary, all with different
qualities and usage.
Lists are created using square brackets:
gaganlist = ["apple", "banana", "cherry"]
Tuple
A tuple is a collection which is ordered and unchangeable.
Tuples are written with round brackets.
gagantuple = ("apple", "banana", "cherry")
Sets
A set is a collection which is unordered, unchangeable*, and unindexed.
Set items are unchangeable, but you can remove items and add new
items.
Sets are written with curly brackets.
gaganset = {"apple", "banana", "cherry"}
Dictionaries
Dictionaries are used to store data values in key:value pairs.
A dictionary is a collection which is ordered*, changeable and do not
allow duplicates.
Dictionaries are written with curly brackets, and have keys and values:
thisdict = {
"brand": "Rolls Royce",
"model": "Gagan2.0",
"year": 2025
}
IF-ELIF-ELSE
Python Conditions and If statements
Python supports the usual logical conditions from mathematics:
Equals: a == b
Not Equals: a != b
Less than: a < b
Less than or equal to: a <= b
Greater than: a > b
Greater than or equal to: a >= b
Btw these could differ as well
These conditions can be used in several ways, most commonly in "if
statements" and loops.
An "if statement" is written by using the if keyword.
gagan_age = 15
sahil_age = 16
if sahil_age > gagan_age:
print("Sahil is greater than Gagan")
Elif
The elif keyword is Python's way of saying "if the previous conditions
were not true, then try this condition".
gagan_age = 15
sahil_age = 16
if sahil_age > gagan_age:
print("Sahil is greater than Gagan")
elif gagan_age == sahil_age:
print("Sahil is equal to Gagan")
IF-ELIF-ELSE 2
Else
The else keyword catches anything which isn't caught by the preceding
conditions.
gagan_age = 15
sahil_age = 16
if sahil_age > gagan_age:
print("Sahil is greater than Gagan")
elif gagan_age == sahil_age:
print("Sahil is equal to Gagan")
else:
print("Gagan is greater than Sahil")
Btw Remember That You can do If and Else or If and Elif only or just If
only As well.
LOOPS
Python Loops
Python has two loop commands:
while loops
for loops
The while Loop
With the while loop we can execute a set of statements as long as a
condition is true.
i=1
while i < 6:
print(i)
i += 1
LOOPS 2
The break Statement
With the break statement we can stop the loop even if the while
condition is true:
For Example --> Exit the loop when i is 3:
i=1
while i < 6:
print(i)
if i == 3:
break
i += 1
The continue Statement
With the continue statement we can stop the current iteration, and
continue with the next:
Foor Example --> Continue to the next iteration if i is 3:
i=0
while i < 6:
i += 1
if i == 3:
continue
print(i)
The else Statement
With the else statement we can run a block of code once when the
condition no longer is true:
For Example --> Print a message once the condition is false:
i=1
while i < 6:
print(i)
i += 1
else:
print("i is no longer less than 6")
Python 1 Done