Python
Python
Why Python?
• Python works on different platforms (Windows, Mac, Linux, Raspberry Pi, etc).
• Python has a simple syntax similar to the English language.
• Python has syntax that allows developers to write programs with fewer lines than some other programming
languages.
• Python runs on an interpreter system, meaning that code can be executed as soon as it is written. This means
that prototyping can be very quick.
• Python can be treated in a procedural way, an object-oriented way or a functional way.
Python Version:
To check the Python version of the editor, we can find it by importing the sys module:
import sys
print(sys.version)
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.
if 5 > 2:
print("Five is greater than two!")
The number of spaces is up to you as a programmer, the most common use is four, but it has to be at least one.
if 5 > 2:
print("Five is greater than two!")
if 5 > 2:
print("Five is greater than two!")
We have to use the same number of spaces in the same block of code, otherwise Python will give us an error:
if 5 > 2:
print("Five is greater than two!")
print("Five is greater than two!")
Python Variables: In Python, variables are created when we assign a value to it:
x=5
y = "Hello, World!"
print(x)
print(y)
Comments:
Python has commenting capability for the purpose of in-code documentation.
Comments start with a #, and Python will render the rest of the line as a comment:
#This is a comment.
print("Hello, World!")
Variables do not need to be declared with any particular type, and can even change type after they have been
set.
x=4 # x is of type int
x = "Sachin“ # x is now of type str
Casting
If you want to specify the data type of a variable, this can be done with casting.
x = str(3)
y = int(3)
z = float(3)
print(x)
print(y)
print(z)
Get the Type:
We can get the data type of a variable with the type() function.
x=5
y = "Johnny"
print(type(x))
print(type(y))
x = "John"
print(x)
#double quotes are the same as single quotes:
x = 'John'
print(x)
print(a)
print(A)
Variable Names:
A variable can have a short name (like x and y) or a more descriptive name (age, carname, total_volume).
Multi Words Variable Names: Variable names with more than one word can be difficult to read.
There are several techniques you can use to make them more readable:
Camel Case : Each word, except the first, starts with a capital letter:
myVariableName = "John"
print(x)
print(y)
print(z)
print(a)
print(b)
print(c)
One Value to Multiple Variables: We can assign the same value to multiple variables in one line:
x = y = z = "Sachin Tendulkar"
print(x)
print(y)
print(z)
Output Variables:
x="Hello kolkata"
print(x)
Hello kolkata
x=123456789987456321
print(x)
123456789987456321
x=99.9999999999998
print(x)
99.9999999999998
x=x**x
print(x)
9.999999999988848e+199
x=3
x**x
27
x=x**x
print(x)
27
x**2
729
In the print() function, we output multiple variables, separated by a comma:
a="Python"
b="is"
c="very"
d="easy"
print(a,b,c,d)
Python is very easy
The best way to output multiple variables in the print() function is to separate them with commas, which even support different data
types:
print(x,a)
kaushik 13
Global Variables:
• Variables that are created outside of a function (as in all of the examples in the previous pages) are known as global variables.
• Global variables can be used by everyone, both inside of functions and outside.
x = "easy"
def myfunc():
print("Python is " + x)
myfunc()
If we create a variable with the same name inside a function, this variable will be local, and can only be used inside the function.
The global variable with the same name will remain as it was, global and with the original value.
x = "easy"
def f1():
x = "simple"
print("Python is " + x)
f1()
print("Python is " + x)
def myfunc():
global x
x = "legend"
myfunc()
print("Sachin is a " + x)
Python Data Types
Getting the Data Type: We can get the data type of any object by using the type() function:
x=5
y=5.55
z="sachin"
a=3j
b=True
print(type(x), type(y),type(z), type(a),type(b)) # <class 'int'> <class 'float'> <class 'str'> <class 'complex'> <class 'bool'>
i. int Int, or integer, is a whole number, positive or negative, without decimals, of unlimited length.
ii. float Float, or "floating point number" is a number, positive or negative, containing one or more decimals.
Float can also be scientific numbers with an "e" to indicate the power of 10.
iii. complex Complex numbers are written with a "j" as the imaginary part.
x=1
y = 35656222554887711
z = -3255522
print(type(x))
print(type(y))
print(type(z)) x = 1.10 x = 35e3
y = 1.0 y = 12E4
z = -35.59 z = -87.7e100
print(type(x)) print(type(x))
print(type(y)) print(type(y))
print(type(z)) print(type(z))
x = 3+5j
y = 5j
z = -5j
print(type(x))
print(type(y))
print(type(z))
Type Conversion: We can convert from one type to another with the int(), float(), and complex() methods:
print(x)
print(y)
print(z)
print(type(x))
print(type(y))
print(type(z))
Note: We cannot convert complex numbers into another number type.
Random Number: Python does not have a random() function to make a random number, but Python has a built-in module called
random that can be used to make random numbers:
Example: Import the random module, and display a random number between 1 and 100:
import random
print(random.randrange(1, 100))
Python Casting
Specify a Variable Type:
There may be times when you want to specify a type on to a variable. This can be done with casting. Python is an object-
orientated language, and as such it uses classes to define data types, including its primitive types.
int() - constructs an integer number from an integer literal, a float literal (by removing all decimals), or a string literal
(providing the string represents a whole number)
float() - constructs a float number from an integer literal, a float literal or a string literal (providing the string represents a float
or an integer)
str() - constructs a string from a wide variety of data types, including strings, integer literals and float literals
x = float(1)
x = str("s1")
y = float(2.8)
y = str(2)
z = float("3")
z = str(3.0)
w = float("4.2")
print(x) s1
print(x) 1.0
print(y) 2
print(y) 2.8
print(z) 3.0
print(z) 3.0
print(y+z) 23.0
print(w+x+y+z) 11.0
Python Strings
• Strings in python are surrounded by either single quotation marks, or double quotation marks.
• ‘kolkata' is the same as “kolkata".
• We can display a string literal with the print() function:
print("It's alright") It's alright
print("He is called 'Johnny'") He is called 'Johnny'
print('He is called "Johnny"') He is called "Johnny"
a = "Hello, World!"
print(a[8])
for x in "kolkata":
print(x)
Use it in an if statement:
Check if NOT : To check if a certain phrase or character is NOT present in a string, we can use the keyword not in.
Like many other popular programming languages, strings in Python are arrays of bytes representing unicode
characters.
However, Python does not have a character data type, a single character is simply a string with a length of 1.
Square brackets can be used to access elements of the string.
Looping Through a String: Since strings are arrays, we can loop through the characters in a string, with a for
loop.
m
y
I
n
d
i
a
Slicing: We 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.
Get the characters from position 3 to position 10 (not included):
Slice From the Start: By leaving out the start index, the range will start at the first character.
b = "PYTHON IS EASY"
print(b[:5]) # PYTHO
Slice To the End: By leaving out the end index, the range will go to the end.
b = "PYTHON IS EASY"
print(b[:5])
print(b[2:])
Negative Indexing :Use negative indexes to start the slice from the end of the string:
b = "sachin tendulkar"
print(b[-5:-1])
Python - Modify Strings
Python has a set of built-in methods that you can use on strings.
• Remove Whitespace :Whitespace is the space before and/or after the actual text, and very often you want to
remove this space.
a=" Python is very easy "
print(a.strip())
• Replace String: The replace() method replaces a string with another string
a = "Python is tough"
print(a.replace("tough", "very easy"))
• Split String :The split() method returns a list where the text between the specified separator becomes the list
items.
a = "PYTHON is easy"
b = a.split(" ")
print(b) # ['PYTHON', 'is', 'easy']
String Concatenation: To concatenate, or combine, two strings you can use the + operator.
a = "kaushik"
b = "goswami"
c= " "
c=a+c+b
print(c)
Python - Format – Strings: We cannot combine strings and numbers like this:
age = 36
txt = "My name is Virat, I am " + age
print(txt)
Traceback (most recent call last):
File "C:/Python/Python313/prime2.py", line 33, in <module>
txt = "My name is Virat, I am " + age
TypeError: can only concatenate str (not "int") to str
But we can combine strings and numbers by using f-strings or the format() method!
F-Strings: F-String was introduced in Python 3.6, and is now the preferred way of formatting strings.
To specify a string as an f-string, simply put an f in front of the string literal, and add curly brackets {} as
placeholders for variables and other operations.
age = 32 price = 100
txt = f"My name is Shubhman, I am {age}" txt = f"The price is {price} Rupees"
print(txt) print(txt)
Placeholders and Modifiers:
• A placeholder can contain variables, operations, functions, and modifiers to format the value.
• A placeholder can include a modifier to format the value.
• A modifier is included by adding a colon : followed by a legal formatting type, like .2f which means fixed
point number with 2 decimals:
price = 103.3037
txt = f"The price is {price:.3f} Rupees" // The price is 103.304 Rupees
print(txt)
Escape Character: To insert characters that are illegal in a string, use an escape character.
• Boolean Values: In programming you often need to know if an expression is True or False.
• We can evaluate any expression in Python, and get one of two answers, True or False.
• When we compare two values, the expression is evaluated and Python returns the Boolean answer:
a = 200
b = 300
if a < b:
print("b is greater than a")
else:
print("a is greater than b")
Evaluate Values and Variables: The bool() function allows you to evaluate any value, and give you True or False
in return,
print(bool("Hello")) True
print(bool(15)) True
print(bool(-1)) True
print(bool(0)) False
x = "Hello"
y = 15
z=0
print(bool(x)) True
print(bool(y)) True
print(bool(z)) False
Most Values are True: Almost any value is evaluated to True if it has some sort of content.
In fact, there are not many values that evaluate to False, except empty values, such as (), [], {}, "", the number 0,
and the value None. And of course the value False evaluates to False.
print(bool(False)) False
print(bool(None)) False
print(bool(0)) False
print(bool("")) False
print(bool(())) False
print(bool([])) False
print(bool({})) False
Functions can Return a Boolean: We can create functions that returns a Boolean Value:
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
These conditions can be used in several ways, most commonly in "if statements" and loops.
a = 33
b = 200
if b > a:
print("b is greater than a")
Indentation: Python relies on indentation (whitespace at the beginning of a line) to define scope in
the code. Other programming languages often use curly-brackets for this purpose.
a = 33
b = 200
if b > a:
print("b is greater than a")
Elif: The elif keyword is Python's way of saying "if the previous conditions were not true, then try
this condition".
a = 33
b = 33
if b > a:
print("b is greater than a")
elif a == b:
print("a and b are equal")
Else: The else keyword catches anything which isn't caught by the preceding conditions.
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 this example a is greater than b, so the first condition is not true, also the elif condition is not
true, so we go to the else condition and print to screen that "a is greater than b".
a = 200
b = 33
if b > a:
print("b is greater than a")
else:
print("b is not greater than a")
Short Hand If :If you have only one statement to execute, you can put it on the same line as the if
statement.
Short Hand If ... Else :If we have only one statement to execute, one for if, and one for else, we can
put it all on the same line:
a=2
b = 330
print("A") if a > b else print("B")
And: The and keyword is a logical operator, and is used to combine conditional statements:
Example: Test if a is greater than b, AND if c is greater than a:
a = 200
b = 33
c = 500
if a > b and c > a:
print("Both conditions are True")
Or: The or keyword is a logical operator, and is used to combine conditional statements:
Example: Test if a is greater than b, OR if a is greater than c:
a = 200
b = 33
c = 500
if a > b or a > c:
print("At least one of the conditions is True")
Not: The not keyword is a logical operator, and is used to reverse the result of the conditional
statement:
Example:Test if a is NOT greater than b:
a = 33
b = 200
if not a > b:
print("a is NOT greater than b")
Nested If: We can have if statements inside if statements, this is called nested if statements.
x = 41
if x > 10:
print("Above ten,")
if x > 20:
print("and also above 20!")
if x > 30:
print("and also above 30!!")
else:
print("but not above 20.")
Python Loops: Python has two primitive loop commands:
I. while loops
II. for loops
The while Loop: With the while loop we can execute a set of statements as long as a condition is true.
Note: remember to increment i, or else the loop will continue forever.
i=1
while i < 10:
The while loop requires relevant variables to be ready, in this example we need to define
print(i)
an indexing variable, i, which we set to 1.
i += 1
The break Statement: With the break statement we can stop the loop even if the while condition is
true:
i=1
while i < 10:
print(i)
if i == 5:
break
i += 1