01 Python Basics
01 Python Basics
Data types
The data type is mainly the category of the data. There are basically 5 groups of main data types but
there are various other types available in python.
1. Numeric type:
a) Integer (int): Positive or negative whole numbers (without a fractional part).
For example: 10,1000000,-3
b) Floating-point (float): Any real numbers with “decimal” points or floating-point
representation.
For example: -3.1234, 100.3458998
b) List: It is an ordered collection of elements where the elements are separated with a comma (,)
and enclosed within square brackets []. The list can have elements with more than ode data
types.
For example: list with only integers [1, 2, 3] and a list with mixed data types [110, "CSE110",
12.4550, [], None]. Here, 110 is an integer, "CSE110" is a string, 12.4550 is a floating-point
number, [] is a list, None is NoneType.
Note: Details will be discussed later.
1
Data type checking
Mainly for debugging (code correcting) purpose type() function is used. It returns the type of
argument(object) passed as a parameter.
Example:
Code Output
type(110) int
type(123.456) float
type(True) bool
type(None) NoneType
print() function
the print() function is used for printing the value of an expression written inside the parentheses
(pair of an opening and closing first brackets). We shall discuss more about this after you have learned
what is a function in python. In a command-line interpreter, you may not need the print()
function, but when we write a set of code and want to see any text output on the screen, we use the
print() function. For example:
Code Output
2
print(123) 123
print(123.567) 123.567
Variable
Variables are containers for storing data values.
Here, student_name is a variable and it is holding or referring to the value “Jane”. Values are always
stored from the right side of the assignment(=) to the variable on the left side. Unlike other languages,
in python, we do not need to declare data types directly. The data type is decided by the interpreter
during the run-time.
one variable can be assigned values of different data types. Here, in this example, first 123 was put in
the container or variable named check. Then we replaced the value of the container from 123 to “Hi”
which is a string. For example:
Code Output
3
<class 'str'>
check = "Hi"
print(check)
print(type(check))
While naming the variables we need to follow certain rules and restrictions. These are called “Variable
naming conventions”. By following these our codes become more understandable by the Human
Readers (us). Few significant rules have been mentioned below.
Variable names-
● can have letters (A-Z and a-z), digits(0-9), and underscores (_).
● should maintain snake_casing. That means each word should be separated by underscores(_)
● cannot begin with digits
● cannot have whitespace and special signs (e.g.: +, -, !, @, $, #, %.)
● are case sensitive meaning ABC, Abc, abc are three different variables.
● have to be meaningful with the data stored in it.
● cannot be too lengthy and too general, need to have a balance
● should not be written with single alphabets. Minimum length should be 3.
● cannot be a reserved keyword for Python. There are a total of 35 keywords.
4
Basic operations and precedence
Now you know what data types are. A programming language uses ‘operations’ to manipulate the
data stored in variables to achieve the desired results. Basic operations in Python can be divided into
two parts: Unary (meaning it is done with one variable) and Binary (meaning it is done using two
variables or one variable and a single value of data).
Note: You cannot do any operation with None type.
Let’s explore each type of operation and understand what they do.
Unary operations
1. Unary + (plus): We use unary + (plus) operation by adding a ‘+’ before a variable or data. It
does not change the data. (Works with int, float, complex, and boolean. For booleans, True
and False will be valued as 1 and 0 respectively.) For example:
Code Output
x = 5 5
print(x) 5
print(+x)
2. Unary - (minus): We use unary - (minus) operation by adding a ‘-’ before a variable or data. It
produces the negative value of the input (equivalent to the multiplication with -1). (Works with
int, float, complex, and boolean. For booleans, True and False will be valued as 1 and 0
respectively.) For example:
Code Output
x = 5 5
print(x) -5
print(-x)
3. Unary ~ (invert): We use unary - (invert) operation by adding a ‘~’ before a variable or data. It
produces a bitwise inverse of a given data. Simply, for any data x, a bitwise inverse is defined
in python as -(x+1). (Works with int, and boolean. For booleans, True and False will be valued
as 1 and 0 respectively.) For example:
Code Output
5
x = 5 5
print(x) -6
print(~x)
Binary operation:
Operators are symbols that represent any kind of computation such as addition, subtraction, and etc.
The values or the variables the operator works on are called Operands.
1+2
1. Arithmetic operation
a. + (addition)
b. - (subtraction)
c. * (multiplication)
Code Output
print(2+3) 5
print(2-30) -28
print(2*30) 60
print(2.456789*30) 73.70367
d. / (division)
Division of numbers(float, int) yields a float
Code Output
print(4/2) 2.0
print(9/2) 4.5
print(-5/2) -2.5
print(30/4) 7.5
e. // (floor division)
Floor division of integers results in an integer.
If one of the operands is float, then the floor division
6
results in a float.
Code Output
print(30//4) 7
(here, from the previous example, we can
see, 30 divided by 4 yields 7.5. But while
using the floor division (//), it basically
discards the part after the decimal point
and returns a whole number by flooring the
value to the nearest integer number. Or we
can say that it returns the quotient value
after dividing)
print(10.5//2.5) 4.0
print(10.5//2) 5.0
print(10//2.5) 4.0
print(-5//2) -3
Here, -5 divide by 2 gives -2.5 . Since we
have used floor divide, it will take it to
the nearest (lower) integer, which is -3.
f. % (modulus)
Code Output
print(30%4) 2
(here, the percentage sign is called “modulus
operator” and it basically returns the
remainder by dividing the first number with the
second number. 30 divide by 4 yields quotient,4
and remainder 2. So the final output is 2)
7
(1) For negative values:
Code Output
print(-5%2) 1
Here, x = -5, y = 2
z = -5 - 2*(-5//2)
= - 5 - 2*(-3)
= - 5 +6
= 1
print(-5.5%2) 0.5
Here, x = -5.5 , y = 2
z = -5.5 - 2*(-5.5//2)
= - 5.5 - 2*(-3)
= - 5.5 +6
= 0.5
print(5%-2) -1
Here, x = 5, y = -2
z = 5 - (-2)*(5//-2)
= 5 - (-2)*(-3)
= 5 - (6)
= -1
Here, x = 5.5, y = -2
print(5.5%-2)
z = 5.5 - (-2)*(5.5//-2)
= 5.5 - (-2)*(-3.0)
= 5.5 - (6.0)
= - 0.5
8
Here, the x, dividend is broken into two parts such that, one part is
always positive between a and b.
Code Output
print(-5%2) 1
print(-5.5%2) 0.5
print(5%-2) -1
-0.5
print(5.5%-2)
Here, 5.5%-2 = (4+1.5)%-2 = [(4%-2) +
(1.5%-2)]%-2 = [0+ -1.5]%-2 = (-1.5)%-2=
(-2+0.5)%-2 =[(-2%-2) + 0.5%-2]= 0+ (-0.5) = -
0.5
g. ** (Exponentiation)
Basically it's the power operator (X**Y)= xY
Code Output
print(2**4) 16
print(-3**2) -9 (Here, - 32 = − 9 )
print(4**-2) 0.0625
Here, 4−2 = 1
= 1
42 16
9
1. Assignment operator
a. = (assign): It is used for putting value from the right side of the equal sign(=) to a
variable on the left side of the equal sign(=).
For example: number = 123.
Compound Example
Assignment
Operators Short-form full form
+= a += 7 a = a + 7
-= b -= 2 b = b - 2
*= c *= 3 c = c * 3
/= d /= 9 d = d / 9
%= e %= 2 e = e % 2
**= f **= 4 f = f ** 4
//= g //= 11 g = g // 11
2. Logical operator
a. and (logical AND)
b. or (logical OR)
c. not (Logical NOT)
Note: Details will be discussed in the branching chapter.
10
c. > (greater than)
d. < (less than)
e. >= (greater than or equal)
f. <= (less than or equal)
Note: Details will be discussed in the branching chapter.
4. Membership Operator
a. in: Returns True if the first value is in the second. Otherwise, returns False.
b. not in: Returns True if the first value is not in the second. Otherwise, returns False.
Example:
Code Output
5. Identity Operators
Identity operators check whether two values are identical or not.
a. is: Returns True if the first value is identical or the same as the second value.
Otherwise, returns False.
b. is not: Returns False if the first value is identical or the same as the second value.
Otherwise, returns True.
Example:
Code Output
11
7. Bitwise Operators [Note: will be covered in future courses]
Compound expression:
When we write an expression with two or more operations, it is called a compound expression. For example,
we may write 7+9*3 where we have both addition and multiplication operations in a single expression.
Determining the result of a compound expression is a little tricky. We need to think about what operation will
be executed first. To determine that the computer follows Operator precedence, a set of rules that dictates the
computer should be done first. For our example, 7+9*3 the multiplication operation will have higher
precedence and will be executed first. So the program will first calculate 9*3 which results in 27. Then it will
calculate 7+27, which will result in 34.
5*3+2-1*2
1+7/7*7
Operator precedence:
In the tale below precedence has been shown in descending order. Highest precedence at the top,
lowest at the bottom. Operators in the same precedence are evaluated from left to right.
x[index:index] Slicing
x[index] Subscription
** Exponentiation
~x Bitwise not
12
*, /, %, // Multiplication, division,
modulus, floor division
+, - Addition, subtraction
^ Bitwise XOR
| Bitwise OR
or Boolean OR
Example:
Output: True
Output: True
13
print(9 - 5 // 2 * 13 + 2 ** here, Exponentiation (**) has the
2) highest precedence. So, 2**2 will be
executed first
print(9 - 5 // 2 * 13 + 2 ** 2)
print(9 - 5 // 2 * 13 + 4)
print(9 - 2 * 13 + 4)
print(9 - 2 * 13 + 4)
print(9 - 26 + 4)
print(9 - 26 + 4)
print(-17 + 4)
print(-13)
Output: -13
print(1.5 * 10 // 2 + 8)
print(15.0 // 2 + 8)
print(15.0 // 2 + 8)
print(7.0 + 8)
print(7.0 + 8)
print(15.0)
Output: 15.0
14
print(-3 ** 2 * 2.0) here, ** has precedence over *.
print(-3 ** 2 * 2.0)
print(-9 * 2.0)
print(-9 * 2.0)
print(-18.0)
Output: -18.0
print(-3 ** ( 2 * 2.0))
print(-3 ** ( 4.0))
print(-3 ** 4.0)
print(-81.0)
Output: -81.0
Type Conversion:
Data types can be modified in two ways: Implicit (when the compiler changes the type of a data for
you) and Explicit (when you change the type of a data using type changing functions, it is called
“Type-casting” )
Note: What is the compiler will be explained later. Assume it to be like a teacher who checks your
code for any kind of mistakes and shows the problems(errors) and sometimes does type conversion
for you according to the computation need of a statement.
Operation Result
5.0 -3 2.0
4.0/5 0.8
4/5.0 0.8
4*3.0 12.0
15
5//2.0 2.0
7.0%2 1.0
Code Output
print(str(1)) 1
print(type(str(1))) <class 'str'>
print("=============") =============
1.555
print(str(1.555)) <class 'str'>
print(type(str(1)))
b. int(): constructs an integer number from various data types such as strings ( the input
string has to consist of numbers without any decimal points, basically whole numbers),
and float-point numbers (by rounding up to a whole number, basically it truncates the
decimal part). For example:
Code Output
print(int("12")) 12
print(type(int("12"))) <class 'int'>
print("=============") =============
12
print(int(12.34)) <class 'int'>
print(type(int(12.34)))
print(int("12.34")) ValueError
print(int("12b")) ValueError
c. float(): constructs a floating-point number from various data types such as integer
numbers, and strings (the input string has to be a whole number or a floating point
number). For example:
16
Code Output
print(float(12)) 12.0
print(type(float(12))) <class
print("=============") 'float'>
=============
print(float("34")) 34.0
print(type(float("34"))) <class
print("=============") 'float'>
=============
print(float("34.56789")) 34.56789
print(type(float("34.56789"))) <class
print("=============") 'float'>
=============
print(float("34.5b789")) ValueError
print(float("34b6")) ValueError
17
Input
For taking input from the user directly, Python has a special built-in function, input(). It takes a String
as a prompt argument and it is optional. It is used to display information or messages to the user
regarding the input. For example, “Please enter a number” is a prompt. After typing the data/input in
the designated inbox box provided by the IDE, the user needs to press the ENTER key, otherwise the
program will be waiting for the user input indefinitely. The input() function converts it to a string and
then returns the string to be assigned to the target variable.
Input Output
Here, from the example output, we can see that age has a String data type which was integer during
the initial data input phase. This implicit data conversion has taken place in the input() function. No
matter what data type we give as an input, this function always converts it to a string. So in order to
get a number as an input, we need to use explicit type conversion on the input value.
Input Output
18
number:12.75
You have entered:12.75
Data type is <class 'float'>
Input Output
19