Learn Python in 24 Hours For Beginners by S Basu
Learn Python in 24 Hours For Beginners by S Basu
PYTHON
IN
24 HOURS
FOR
BEGINNERS
Python Installation
Step 6: Now go to Control panel -> System and Security -> System ->
Advanced system settings -> Environment Variables -> Add Python
Installation location into your PATH variables.
Step 7: Open command prompt and with the help of python command check
whether installation is done correctly or not.
Open Notepad++ and create a new file (hello_world) and save the
file with .py extension
import statement in Python allows a Python file or module to access all the
codes present in another Python file or module.
Chapter 3 : Python variables, Datatypes &
Operators
Important points to note are:
But in Python, you do not have to declare the data type of a variable.
Python understands the data type of any variable simply from its value.
Output
When we run the above piece of code, Python shows the data types of
variable x, y and z.
Apart from data types like int, float and string, Python also has list, tuple
and dictionaries.
Python String slicing is the process of obtaining a sub string of the given
string.
Syntax:
string [ index_number_start (including its value) : index_number_stop
(excluding its value) ]
Example:
Open Notepad++ and create a new python file and write the following lines
of code.
Now run the above piece of code:
Code explanation:
In the above piece of code, the output of message[2:12] is : print values from
2 (including its value at index position 2) to 12 (excluding its value at index
position 12) alth is we
The output of message[:6] is : print values from start (index position 0,
including its value) to 6 (excluding its value at index position 6) Health
To print letters or values from the end of a string, minus sign is used. For
example: message[-1] will return h, message[-2] will return t and so on.
Syntax: len(string)
Syntax: string.lower()
Syntax: string.upper()
Syntax: string.strip()
Syntax: string.lstrip()
Syntax: string.rstrip()
Output:
Syntax: string.split( )
Output:
Syntax: string.replace(old,new)
Output:
10. join( ) string method returns a string by joining
all the elements of an iterable (lists, tuples and string) with the
delimiter.
Syntax: delimiter.join(iterable)
Output:
Example 1:
In the above example, the values passed to variable animal will fill the first
placeholder and the value passed to variable legs will fill the second
placeholder.
Output:
Example 2:
If you want to display a float number with two digits after the decimal dot,
formatting expression {:.2f} is used.
Output:
3.2: Python List
● A Python List is very similar to an Array. It contains a list of elements
separated by commas and its elements are written with square brackets
[ …. ].
● Python list are mutable meaning that we can modify list elements.
● A value from a List can be accessed from its index value.
Syntax for accessing the values from a List is:
List_name [ index_num ]
What is an Array?
In order to get the value Ford as output, we need to write print ( cars[2] )
Example:
Create a new Python file (variables.py) and write the following lines of code:
Code explanation:
● In the above piece of code, fruits is a List containing 6 elements. The
value at position 0 is “apple”, at position 1 is “orange” and so on.
Output: is app
3.2.1: Important and commonly used List methods
1. append( ) method inserts the element at the end of the list.
Syntax: list.append(element)
Output:
Output:
Output:
Example:
After running the above piece of code, we get an output of:
Code explanation:
When we create a tuple and assign new values into it. This is called packing a
tuple.
When we extract those values and store them into a variable. This is called
unpacking a tuple.
Output:
Output:
2. Update a record
To update a record, the syntax is same as insert a new record.
Output:
In the above piece of code, we see the new value (70) assigned to key John
replaces the old value (95).
3. Delete a record
Operator Description
+ Addition
- Subtraction
* Multiplication
/ Division
% Modulus. This sign returns the remainder.
Exponentiation. For example: 2 ** 3 means 2 to the power of 3
**
and that is equal to 8
Floor division. This operator returns only the whole integer
//
number. For example: 23 // 2 will give 11
Operator Description
== Equals: x = = y
!= Not Equals: x != y
< Less than: x < y
<= Less than or equal to: x <= y
> Greater than: x > y
>= Greater than or equal to: x >= y
3.5.3: Commonly used Logical Operators
Operator Description
Example:
and x = 123 and y = “John” executes certain block of code if both
statements are TRUE
Example:
or x = 123 or y = “John” executes certain block of code if one of
the statements is TRUE
Example:
in x = [ 123 , 345 ]
if 123 in x returns TRUE, then executes certain block of code
Example:
x = [ 123 , 345 ]
not in
if 12 not in x returns TRUE, then executes certain block of
code
Operator Description
= Example: x = 2, this means value 2 is assigned to x
+= This is same as x = x + 1. If value of x = 3, then the new
(x += 1) value of x is 3 + 1 = 4
-= This is same as x = x – 2. If value of x = 5, then the new value
(x -= 2) of x is 5 – 2 = 3
*= This is same as x = x * 5. If value of x = 2, then the new value
(x *= 5) of x is 2 * 5 = 10
/= This is same as x = x / 2. If value of x is 10, then the new
(x /= 2) value of x is 10 / 2 = 5
%= This is same as x = x % 2. If value of x is 10, then the new
(x %= 2) value of x is 10 % 2 = 0
Chapter 4 : Python Control Statements
The concept of control statements in Python is similar to any other
programming languages but it has some minor differences. They are:
if condition :
……..
elif condition :
……..
else :
…………
Execution flow:
Example 1:
Create a new Python file (test.py) and write the following lines of code:
You will notice that the above piece of code does not contain any
curly brackets. In Python indentation marks the beginning and end
of a block of code.
In the above example, after stating the if line of code (line 2), we
gave an indentation and wrote the line print("Output is Orange").
This indentation signifies that the print statement belongs to the if
block of code. Then after stating the elif line of code (line 4), we
gave an indentation and wrote the line print("Output is apple").
This one indentation again signifies that the print statement
belongs to the elif block of code. Then again we followed the same
process for else block of code.
In the above Python code, fruits is a List of 4 elements. Since the value at
position 1 is indeed “orange”, the if statement is satisfied and the elif and else
block of code are not checked anymore.
Example 2:
Code explanation:
The Line 2 of the above piece of code checks whether there is value present
in stocks List or not. If TRUE, execute the if block of code, else execute the
else block of code.
Output
Example:
Create a new Python file (loops.py) and write the following lines of code:
After running the above piece of code, we get an output of:
Now within if block of code, I gave two indentation to signify that the
line print("I wish to own tesla one day") belongs to if statement which
in turn belongs to the for loop.
We followed the same above process for elif and else block of codes.
3. The loop will go on till the length of the List car. The length of the
above List is 4, so the loop will happen 4 times.
Execution flow of the above piece of code:
Code explanation:
In the above piece of code we created a list of groceries and stored it in a
variable groceries. The list is a collection of mini lists.
In line for record in groceries:, we capture the mini lists. Then in line for
grocery_item in record: we loop and get the grocery items present in the
mini list.
The syntax is :
while condition :
……..
Example:
Code explanation:
Break
Break statements are used to break out of a loop if certain condition is
satisfied.
Example:
In the above example, the for loop will go on until the if condition is
satisfied. Once the if condition is satisfied the execution will stop because it
will encounter the break statement.
In the above piece of code, you will notice that once the continue statement
was encountered, the code at Line 9 was not printed and the control moved
back to the beginning of the loop.
Syntax:
def function_name ( ) :
……..
Example:
Code Explanation:
Example 1:
Let’s code a simple function. The function will take a list of number and
will check whether each number is prime or not.
A prime number is any number which is divisible by 2 and its remainder
return 0.
Important points to note from the above piece of code:
1. return keyword in python is used to return the value generated from its
function.
2. The two characters \n signifies that the current line ends and a new line
starts.
Output:
Example 2:
Let’s code one of my favorite programs.
In this program we will check whether a string is palindrome or not.
What is palindrome?
Palindrome is a word or sequence that reads the same backward as
forward. For example: Noon is palindrome.
Example 4:
Write a function which will only print letters (excluding the
punctuations) of the given string value.
Output:
Example 5:
Write a function which will update an existing dictionary with the
updated new dictionary.
Output:
class class_name :
def __init__(self) :
….
def method1 :
….
The syntax for creating an object of a class is:
class Hello:
def __init__(self) :
………………
…………
h = Hello( ) ,where h is the object of class Hello.
Example:
Output
class Parent:
……..
class Child (Parent):
…….
Example:
Code explanation:
Output
try:
……..
except:
………
finally:
………….
Example:
Code explanation:
Output
Chapter 9 : Other Important Topics
9.1: range ( ) function
Python range( ) function returns a sequence of integer numbers. In order to
traverse through the number we need for loop.
or
Example:
Code explanation:
Output
Code explanation:
In the above piece of code, we get the current local time using
localtime() function and then format the time using strftime( ) function
What is struct_time?
struct_time is a tuple containing 8 elements and they can be accessed by
their index value and attribute names.
The elements are as follows:
Index Attribute Value
0 tm_year Year – Example 2020
1 tm_mon Month- from 1 to 12
2 tm_mday Day of month – from 1 to 31
3 tm_hour Hour – from 0 - 23
4 tm_min Minutes – from 0 to 59
5 tm_sec Seconds – from 0 to 59
6 tm_wday Day of the week – from 0 to 6 – Monday 0,
Tuesday 1 and so on
7 tm_yday Day of the year – from 1 to 366
8 tm_isdst daylight saving flag (0, 1 or -1). A value
of 1 indicates that the daylight savings is in effect,
0 if daylight savings is not in effect and -1 if the
information is not available.
DEBUG
INFO
WARNING
ERROR
CRITICAL
1. level: This specifies the root severity level from which the
log messages will start displaying.
3. filemode: This specifies the mode in which the log file will
open. w means write mode The default is a, which means
append.
Example:
Code explanation:
In the above piece of code, we configured the logging from Line 2
– 5.
Code explanation:
Output 2: The second output is generated from letters module. Since the
letters module is running directly as the main python file so the variable
__name__ of letters module becomes equal to “__main__”, hence we get
the output “Letters module is not imported”