Python Basic Step by Steps Tutorial For Beginners With Examples and Explanation.

It is the year 2022, learning python has never been so easy, and if get the right resources to learn python basic, you will be on the right track to learning python. And times are running fast; if you want to keep yourself up to date, then prepare yourself with the right programming skills and techniques. 

To learn python programming is so easy compared to other programming languages out there. Here, you will find details of Python basic with lots of examples of python programming codes. So, without much introduction, let's start now to learn python basic step by step.

Python install or not?

The first thing you need to check is your laptop or desktop, whether it has to install Python or not. To check whether Python is installed, go to the command prompt and write - Python and hit the return or enter key. Just like this in below.

Last login: Sat Jan 22 16:33:15 on ttys000
citstudent@CIT-C0033699 ~ % python

if it is install it will show you like this with the current python version.

Last login: Sat Jan 22 16:33:15 on ttys000
citstudent@CIT-C0033699 ~ % python
Python 3.9.0 (default, Nov 21 2020, 14:01:50) 
[Clang 12.0.0 (clang-1200.0.32.27)] on darwin
Type "help", "copyright", "credits" or "license" for more information.

>>> 


And, if it's not installed, it will give you an error that the python program is not installed. To get out from this window >>> just write exit().


If your device python is not installed, go to the python download page -


To download Python go to that link -https://www.python.org/downloads/


And download the current version of Python on your device. Then, check again is it downloaded or not.


So, I think you are all set with the python download or have Python already on your device.


Next, you will ensure you have the right tools to write the python program. To do this, you can choose your favorite IDE like Spyder, Jupyter notebook, atom, or vs. code. If you ask me which I like, I would say for beginners to learn python programming, Jupyter notebook is convenient. But I like Spyder IDE for some reason, but I am not going to describe why I like Spyder IDE; maybe another time to explain.


IDE Choose

It would be best if you had an IDE to write your python programming code to learn python programming. Of course, you can write basic python code even in notepad. But for simplicity and error-free, it is preferable to write your python code in the IDE.  I prefer anaconda as it comes with all the required python IDE and package. So, if you want to install anaconda, go to the link-

Anaconda individual edition -https://www.anaconda.com/products/individual


Once you have downloaded the anaconda, you will see that I have attached the image when you open the anaconda application below.




There as can see that it comes jupyter, spyder and some others IDE and applications. From there, you can install your desired IDE. So, if you want to write a python program, first open an anaconda application, and, from there, you can open spyder or jupyter notebook. So, we are pretty much set now to write a python first program.

Writing a python program.

WOW, here comes to learn basic python. First, open your preferred IDE, open a new file, then write. 

print('Hi there')

Now, if you press the run button, you will see the result in the console of the IDE.


I have circled the area from there you can run and save the File, and bottom area, you can see the result.
Now, at this stage, you know how to write a python program, save it run it, and see the result. Meantime if you make any mistake, the IDE will point it out where exactly you made a mistake. So, I believe you can do it, and this is your journey to go to the end to finish the basic python step by step.

Python program best writing convention:

Whatever you do, there is a standard to follow, and if you follow the standard, that will be the acceptable wider community. So to write a python program there, you have to follow a standard that the python community follows throughout the world. To get all the criteria, you can follow the following website pep8.org. On the pep8.org site, you will be able to find all the standards with full detailed explanations. So if you follow from the beginning to learn python basic to advanced, you do not have to get stuck in the middle to change all of your standards again.

How to comment your python code?

Whenever you write a python basic code or advanced code, it is best to comment along with the code. If you do not comment out your code, that means if you come back later to see your code, you will be lost as you do not know what you wrote regarding that piece of code. So, the best practice is always to comment on your code to know exactly what this piece of code does whenever you come back. In Python, there are several ways you can comment on your code.

1. Block comment
2. Inline comment
3. Multi-line comment.

Inline comment example -

print('Hi there')#this is a comment

Block comment example 

# ===============================================================
# print('Hi there')
# print('Hi there')
# print('Hi there')
# print('Hi there')
#================================================================

Multi-line comment example -

'''
print('Hi there')
print('Hi there')
print('Hi there')
print('Hi there')
'''
There are shortcuts to do this you will find in the IDE Edit tab.
 

Python Variables and Types

This online python tutorial with python basic code examples and python code exercise will be vital for python beginners. In Python, you can not write a variable name as a numeral number like - 1, but you can write as a string numberOne or number_one. There are also standards to follow when writing a variable name in Python. Please follow the ppep8.org site to get the full details on that. You can write a keyword of the python-like int, list, sets, etc. You can follow when writing a variable name either came case or underscore in between two words. e.g - fruit_name or fruitName.

In Python, you do not have to mention variables type the way we do in Java programming like int, string, etc. In Python, just write the variable name, and if you want to find out the types use the type function, and you will be able to find out what type it is. Example 

number = 100
print(type(number))

If you run above two lines, it will show that the number is an int type in the console.
But if you do like this. 
number = 'one'
print(type(number))

It will show you number type in this time is a string.

Numbering in python

Whether you learn python basic or advanced python, you will find that python uses
only int, float, and complex types number types. In python, integer and
other data types are objects, that means we can create a new one by calling
methods.

Example of integer numbers
a = 100
b = -5
c = 0

Example of float numbers
a = 12.00
b = -2.00
c = 0.

Example of complex number
a = 22j

Integer and float numbers can be added together, and the result will be float. Example
a = 5.0 #float number
b = 2 #integer number

 c = a + b
 print('C=',c) # result will be float

Boolean types

Learning python online is never so easy these days once you have a device and online connection. However, In Python, boolean consider a number. Boolean types are True or False. True is 1 (one), and False is 0 (zero) 

% Modulas sign in python

It is called a modules sign, not a percent sign, as you know in math. So how modules work in Python suppose A is divided by B with C remaining.

 A = 17
 B = 3
 C = 17 % 3
print ('C', C) # will show remaing value

Python calculation order of operation same like as you do in the math PEMDAS

P = Parentheses

E = Exponents

M = Multiplication

D = Division

A = Addition

S = Subtract


Divide / sign - round down the number. Actually it is not really rounding down, rather it is just dropping

fractional part after decimal point. Example

x = 11.0
y = 4.0
z = 11.0/4.0
print('Z =',z) # will drop the fractional part

z = 11/4
print('Z=',z) # will drop the fractional part

String in python

So far, you have seen the basic python syntax and basic python numbering with examples. In Python, when you are writing a string, you can use either a single or double quote but stick to one, whichever you prefer. But if you use a single quote, it takes less time to type, you do not have to hold the shift key to write a single quote, but if you want to write double quotes, you have to hold the shift key on your keyboard.

Example of python code

name = 'mohammed'
my_name = "chowdhury" print('My name is', name + ' ' +my_name

from the above example, as you can see, you can use both single or double quotes
in your Python program.

However, if you want to write - it's as a string within a single quote then you have
to do like this you have to use backslash within the single quote, but if you use
double quotes, then you do not have to use backslash.

greeting = 'Hi it\'s Mohammed'
print(greeting)

greeting = "Hi it's Mohammed"
print(greeting)

If you want to write a long message within your quote and write on multiple lines, then use triple quotes for the long message. Example 

long_message = """ aaaaaaaaaaaaa bbbbbbbbbbbbbb.
cccccccccccc            
"""
print(long_message)

If you want to format the string in Python, you can do one of the ways like this-

my_name = 'Mohammed'
greeting = f'Hi , {my_name}'
print(greeting)

Here, f is simply referencing the my_name variable. Make sure if you follow that
way, then you have to use a second bracket or curly brace to reference the variable.


One thing to remember is if you use in your string at the first double quote and the
end-use single, then it will show an error, and the program will not run. You can not
mix string and int unless you convert it from a string to int or int to string vis verse.
Let me show you with an example -

my_name = 'mohammed' # it's a string
age = 27 # it's a integer
print(my_name + ' ' + my_age)

The above code will give you an error on the python console, as it will not be able to
run the program with string and int combination. To overcome this, you need to do
a small thing: convert the int to a string.

print(my_name + ' ' + str(my_age))

Same with string to int-

my_age = '27'
print(age , int(my_age))

Function in Python

If you want to reuse your code and want to organize your code into a different
chunk of the block, then the function is your answer. To create a function in Python,
there are some set of rules to follow, such as

def my_function():
    print('This is a function')

So, here def is a Python keyword you have to write before the function name.
Next is a function name. The convention is a small letter, either camel case or more
than one word, then underscore. Make sure the function name describes what this
function does. Then follow with () parenthesis then: colon. If any of the conventions
is missing, function creation is not correct.

After that, on the following line, indentation is significant in Python. You can set
indentation either space or a TAB. Lots of time, you need to pass an argument with
the function. So, now you are wondering how to do it?

How can I pass an argument with the function? Below is an example -
#function example with arguments        
def function_with_arguments(greeting, name):
    print('Hi, %s, I wish you all the best %s'%(greeting, name))
So you pass argument within your function greeting and name. Now, whenever you call that function, it will ask you to pass two string message with that like-

# calling function
function_with_arguments('As Salamu Alykum', 'Mohammed') 
that function will print that line
print('Hi, %s, I wish you all the best %s'%(greeting, name))

Because that line was inside the function.

How to use return statement within the function?
# return function example   
def adding_two_numbers(a, b):
    return a + b
The above function will add two numbers. So whenever you call that adding_two_numbers function, it will return two adding numbers results. But that result has to store another variable. After that, if you want to see the result of the two numbers, you have to use the print function.

# calling function that return
result_two_numbers = adding_two_numbers(5, 4)
# print the result of the function 
print(result_two_numbers) 
# example of function with arguments
def greeting(name, greeting):
    print(f'{name}, {greeting}')

greeting('Mohammed', 'Good Morning !!') #calling function
#example of default value passing with a argument  
def greeting_with_default_value(name = 'Mohammed', greeting= 'Good Night'):
    print(f'{name}, {greeting}')

#calling function    
greeting_with_default_value()
#example of getting error when function not getting required positional argument.
def greeting(name, greeting):
    print(f'{name}')

#calling function
greeting('Mohammed')
The above function will show an error as it required two arguments but got only one.
# variable scopes in python
def python_version_info():
python_version = '3.9' print(f'Python version info inside the function : {python_version}') # calling the function
python_version_info()
The python_version variable will only work inside the python_version_info()function,
and if you want to use the same variable outside the function, it will not work.
# example of getting error using function variable
# outside the function

print(f'Python version info outside the function : {python_version}')

Boolean Logic True | False

In python, 0(zero) is false, and the rest is true, even negative numbers. Empty
data structures like lists, sets, dictionaries. And tuple is False. But list, sets, tuple,
and dictionary. With items within are True. None is also False in Python.
#Example

print('10 > 5 is it true?:', 10 > 5 )

# To find out quickly either it is true or false use bool

print('\nNone is true or false?:', bool(None))
print(bool(10 > 5))
print(bool(10 < 5))
print(bool(-1)) # to check negative number true or false
print(bool(0))# to check 0 zero true or false

Empty string are also False

print(bool('Salam')) # with string true
print(bool('')) # empty string false

Empty list, sets, tuple and dict false
#list

print('\nEmpty list:',bool(list()))
print('Empty list:',bool([]))
print('list with items:',bool([1]))

#sets

print('\nEmpty sets:',bool(set()))
print('Sets with items:',bool({1}))

#tuple

print('\nEmpty tuple:',bool(()))
print('Tuple with items:',bool(1,))

#dictionary

print('\nEmpty dict:',bool(dict()))
print('Empty dict:',bool({}))
print('Dict with items:',bool({1:'apple'}))

Comparison Operator in Python

Comparisons example with numbers
> greater than sign
>= greater than equal to sign
< less than sign
<= less than equal to sign

print('100 < 200 =', 100 < 200)
print('100 <= 100 =', 100 <= 100)
print('100 < 50 =', 100 < 50)
print('100 <= 90 =', 100 <= 90)

print('\n') # to get a new line

print('200 > 100 =', 200 > 100)
print('200 >= 200 =', 200 >= 200)
print('200 > 500 =', 200 > 500)
print('200 >= 500 =', 200 >= 500)

print('-20 is greater than 20 ?:', -20 > 20)

Equality

Comparisons example with equals(==) and not equals(!=) will return boolean result either True or False. answer_one = 1 answer_two = 1 print('True or False:',answer_one == answer_two) answer_one = 5 answer_two = 1
print('True or False:',answer_one != answer_two)

answer_one = 'apple'
answer_two = 'apple'

print('True or False:',answer_one == answer_two)
print('True or False:',answer_one != answer_two)

Identity check 
is or is not key words. (is) is similar to == and (is not) is similar to !=

fruit_list_one = ['apple', 'banana'] 
fruit_list_two = ['apple', 'banana']

checking for equality
Checking for identity, both lists have different memory addresses, so checking for identity will give false results because both lists have different memory addresses.

print(fruit_list_one == fruit_list_two) # will give true or false result
print(fruit_list_one is fruit_list_two) # will give true or false result

is and is not checking for built in types like None, True and False

one = True
print('One is True :',one is True)

two = False
print('Two is false:',two is False)
print('Two is not true:', two is not False )

AND | NOT | OR Operator in Python

When writing the python code, you will face putting logic and, or not operator in Python. So it is very important to know how to use and, or, and not operator in Python. So I have added detailed examples you can follow here.

And examples
If both are true then and expression will be true 

answer_one = True
answer_two = True
print('True or False :', answer_one and answer_two)

If one the variable is false answer will be false
answer_one = False
answer_two = True
print('\nTrue or False :', answer_one and answer_two)

or operator example

If one of the variables is True answer will be true
answer_one = True
answer_two = True
print('\nTrue or False :', answer_one or answer_two)

answer_one = False
answer_two = True
print('\nTrue or False :', answer_one or answer_two)

If both false the result will be false
answer_one = False
answer_two = False
print('\nTrue or False :', answer_one or answer_two)

not operator examples

Not represent reverse in boolean if its true will return false, and if it is false will return false.
answer_one = True
print('\nTrue or False :', not answer_one)

answer_one = False
print('\nTrue or False :', not answer_one)

If Else elif in python

Almost within every ten lines of code, you will see if-else condition. This is because we need to make some decisions based on the condition in our daily life. So that is where we can use if-else elif conditions in python code.
Here, I have added detailed code examples of the if elif and else. 

if examples

number = 7

if number > 5:
     print('We are learning python basic')
The above condition will print out in the console. We set the number = 7 and, we set the condition number > 5, which is true. So, the condition is true, and it will execute the print statement. If the condition is less than or greater than 7, the condition will be false, and the print statement will not print on the console.  

How to use not operator with if

Either True or False- if the expression if is false then it will run

if not number > 11:
    print('We are learning python basic')
The above condition is saying that if not number > 11. It is a false statement. So, the condition will print out the statement.

How to use nested if

You can use as many as if else condition.
def find_out_about_number(number):
    if number > 7:
        print('Number is greater than 7')
        if number < 10:
            print('Number is less than 10')
    else:
        print('Number is ', number)            
# calling the function
find_out_about_number(8)
The above code will print the first two print statements if you run the above code. Because when we call the function, we passed number 8, which is greater than 7 and less than 10. But if you pass in the function, the number is 3; that else condition will print in the console. Because number 3 is not greater than 7, it will go to the other condition.

else - examples in python

def find_out_about_number(number): if number > 7: print('Number is greater than 7') else: print('Check your number again!!') # calling the function
find_out_about_number(3)
find_out_about_number(8)

elif - examples in python

def find_out_about_number(num): if num > 10: print('Number is greater than 10') elif num < 15: print('Number is less than 15') else: print('Check your number please!!') # calling the function find_out_about_number(8)
Play yourself with the code changing with a different number when you call the function.

List in python

How to Create an empty list in python examples. You can create a list in Python, either empty or with items in it. You can create an empty list either with a square bracket or parentheses. 
my_list = []
print('Example one :',type(my_list))
Type is built in function to check the type of the variables.
my_list_example = list()
print('Example two :',type(list()))

Example of creating list with items

How to create a list in Python with items? You will get a syntax error if you forget to put a comma between the list items.
my_list_with_int_items = [1, 2, 3, 4] # int value my_list_with_string_items = ['a', 'b', 'c', 'd'] # string items # printing the list items
print('List int items: ',my_list_with_int_items)
print('List string items:', my_list_with_string_items)

How to Find the length of the list in python?

print('List length :', len(my_list_with_int_items))
To find out the length of the list we simply can find out using the len() built in function in python. 

How to access list items?

To access a list of items, we use an index. Python list index starts at 0. my_fruit_list = ['apple', 'banana', 'orange', 'cherry'] Below is an example of finding the items from the list with the index no. print('Finding the specific items in the list:', my_fruit_list[3])
If you use the wrong index number, it will give an error message list is out of the index. The above my_fruit_list has four items, but I am trying to find index number 5, which is not available. That is why it will say the index is out of range.
print('Finding the specific items in the list:', my_fruit_list[5])

How to update a list item in python?

my_fruit_list[3] = 'watermelon' print('Up to date my fruit list now:', my_fruit_list)
In the above example, I am adding another item in the index number 3. So, my_fruit_list will show watermelon now instead of cherry.

We can create a valid list without a comma, but more readable option is to put a comma. See the difference. If you forget the bracket of the list, you will get a syntax error.
my_new_list = ['a' 'b' 'c' 'd']
print('My new list :', my_new_list)
my_list_without_closing_bracket = [1,2] #will get the syntax error
How to do or use Sort within list in python?
Below is the example

my_match_score = [175, 200, 193, 300, 122, 385]

#Original list
print('original my match score list :', my_match_score)

#Sorted list ascending order
print('Sorted my match score list ascending order:', sorted(my_match_score))

#Original list
print('original my match score list :', my_match_score)

# Descending order
print('Sorted my match score list descending order:', sorted(my_match_score, reverse=True))

#Original list
print('original my match score list :', my_match_score)

If you want to reverse the list order. you can use reverse() built in function.
my_match_score.reverse()
print('original my match score list :', my_match_score)
To find out more functions related to the list, you can use the built-in help function.
like - help(list.)
How to add an item in the list in python?
my_fruit_list = ['apple', 'apple', 'orange', 'cherry']
print('Original my fruit list:', my_fruit_list)
my_fruit_list.append('watermelon')
print('Updated My fruit list now :', my_fruit_list)

If you want to add items in a specific position inside the list, then use the insert() function of the list.

my_fruit_list.insert(1,'plum')
print('Updated my fruit list now:', my_fruit_list)

How to  add two list together in python?
To add two list together we can use the extend() built in function of python.
fruit_color_list = ['pink', 'yellow', 'red', 'red', 'green', 'red']
my_fruit_list.extend(fruit_color_list)
print('Updated the list :', my_fruit_list)

How to search an item in the list in python?
To search an item from the list in Python, we can use in operator or use the index number of an item. If you use an operator, it will give the result either true or false. But if you use an index number, it will give the result the actual items from the list.
print('pink' in my_fruit_list)
print('white' in my_fruit_list)
print('Item searching by index number :', my_fruit_list[1])
The below example will print the list is out of range. 
print('Item searching by index number :', my_fruit_list[12])
If you want to find out how many same numbers of the items in the list are exits. In that case, you can use the count() built-in function.
print('Number of same items in the list:',my_fruit_list.count('apple')) How to remove the items from the list in python?
If you use the remove(), the built-in function will remove the item from the list in Python. But we have to specify the item name. It takes exactly one argument. If the item is not on the list, it will give an error.

print('Removing an item from the list:', my_fruit_list.remove('apple')) print('Updated fruit list now:', my_fruit_list)
We can also use the pop() built-in function to remove an item from the list in Python. That function will remove the last item from the list. But if we give an index number, it can also delete that specific item. If the item we want to delete is not on the list, it will give an error.
print('Removing the last item from the list:',my_fruit_list.pop())
print('Removing the specific item from the list:',my_fruit_list.pop(1))
print('Updated fruit list now:', my_fruit_list)

Tuples in Python

  • Tuples are immutable. It is good for read-only data purposes.
  • Can not be added or changed or removed the items in it once it is created
  • It is good for once we know that we will not change the data in it

How to search in tuple?

  • my_tuple.index(items position or name) or item in my_tuple. The index number
can assess items

Disadvantage

  • To search any items, it is slow as it must be checked each item.
  • It can't be added or removed any item.
  • It cannot be sorted either.
How to create one item and empty tuple in python?

my_tuple = ()
print('To see what type it is :', type(my_tuple))

Please make sure if you create one item, tuple must be added one comma at the end; otherwise, it will not work.
my_tuple_with_one_item = (1,) print('To find out what type is it:',type(my_tuple_with_one_item)) How to create tuple with multiple items in python? student_result_details = ('Hasan','Math', 80, 'geography', 90, 'science', 95, 'total', 265 ) print('Student result details :', student_result_details) How to access tuple items in python?
If the index is too big compared to the tuple index size, it will give an error message—tuple index out of range.

print('Item access by the index number :', student_result_details[0])

Assigning tuple items- unpacking in python

studentName,subjectMath, mathMarks, subjectGegraphy, geographyMarks, subjectScience, scienceMarks , total, totalMarks = student_result_details
print('Studnet subject result grade :', studentName, totalMarks)

But we can not assign new items as we can not change them once the tuple is created. So if you add, we will get a type error 'tuple' object that does not support item assignment.

student_result_details[0] = 'English'

Set in Python

  • In Python, when you use sets in your coding, it can give you only one item, with no duplicate allowed within the set data structure in Python.
  • Sets data structure are very first compared to list and tuple in Python.
  • It has a powerful set operator - union, difference, and intersection.
  • It's very easy to compare items within sets.

How to create set?

  • my_sets = set() This is how to create an empty set
  • my_set = set{} But this will create a dictionary if we do like this.
  • my_set = set{1,2,3} But if we put items within it it will be set

To find out the what types it is you can do 
my_set = set()
print('What type is it?:', type(my_set))

my_set = {}
print('What type is it?:', type(my_set))
The above example will show you it is a dictionary not set as it was created with a  Curley brace. But if items are within curly brace, it will be considered a set in Python. And, if you want to create set with items this is how you will create.
my_set = {1,2,3,6}
print('What type is it?:', type(my_set))
print('Item within sets:', my_set)

How to search in sets?

Compared to list or tuple, if you want to find any items, set is very fast to search for an item. You use either loop or in operator to search an item in the set. 

How to add item in set?

You can use built in add() function to add an item in the set.
my_set.add(item) - use built in add function
my_fruit_set.add('plum')
print('Updated sets now:',my_fruit_set)

How to remove in set?


Again you can use the built-in discard() and remove() function to remove an item from the set. If you use -my_set. Discard (item) - use the built-in discard function if the item is available. If the item is not available, then no error will show. But if we use the remove() function and if the item is not available within the set, it will show an error message.


  • Set does not maintain order, so it is not sortable.
  • We can add or remove from sets.
my_fruit_set.discard('apple')
print('Updated sets now:', my_fruit_set)

To check discard function where items is not available
my_fruit_set.discard('watermelon')
print('Updated sets now:',my_fruit_set)

To check remove function

my_fruit_set.remove('watermelon')
my_fruit_set.remove('plum')
print('Updated sets now:',my_fruit_set)
Finding the length of the set
print('Length of the set is:', len(my_set))

Set will not allowed duplicate items. Here I am creating a new sets - 

my_fruit_set = {'apple', 'orange', 'apple'}
print('What is in my fruit set?:', my_fruit_set)
The above example will show only one apple and one orange even though there are two apple as it will not allow duplicate items in the set in python.
How to convert list to sets? my_fruit_list = ['apple', 'orange', 'cherry', 'watermelon', 'apple', 'orange'] print('Checking list itms:',my_fruit_list) Now, converting list to set - fruit_list_to_set=set(my_fruit_list) print('Checking my fruit list now:', fruit_list_to_set)
Another important thing to remember is that set can not keep the items in an order, and we can not access set items by the index number.
print(fruit_list_to_set[0]) 
If you try to access an item with the index number in the set, it will give you an error message. This is because the above print command will not run in the python console. As I mentioned earlier, that set does not support sorted either, but if you want to sort the same type of item, you can first convert the set to list or use the built-in function sorted() function to sort the item.
print('Testing set to sort:', sorted(fruit_list_to_set))

How to update a set?
We can add two sets, lists, tuples together that will update the set. But make sure not to use string to update the sets as it will create each string as a sequence.
programming_languages = {'python', 'java', 'c++'} rate_languages = {'5*', '4*', '3*'} programming_languages.update(rate_languages) print('After update the sets :', programming_languages) One thing to remember is never to use string to update sets. programming_languages.update('spyder') print('After update the sets :', programming_languages)

How to use set operations?


  • Example - first_set, second_set - created two sets
  • first_set.union(second_set) - first_set | second_set [this will create a new set with all the items from both sets]
  • first_set.intersection(second_set) - first_set & second_set [this will create a new set with only item which are available in both set]
  • first_set.difference(second_set) - first_set ^ second_set [this will create a new set that are not available in both set]
Creating to sets fruit_set = {'apple', 'orange', 'watermelon', 'plum', 'banana'} favorite_fruits = {'watermelon', 'mango', 'grape', 'dates', 'banana'} Example of sets operations

Union in python

print('Union example :', fruit_set | favorite_fruits)

Intersection in python

print('Intersection example :', fruit_set & favorite_fruits)

Difference in python

print('Difference example :', fruit_set ^ favorite_fruits)

Dictionary in Python

  • Dictionaries store data in key-value pairs.
  • Dictionary's value is mutable, but the key is not mutable.
  • Looking for keys in the dictionaries is very fast.
  • The dictionaries can not be accessed by the index number.
  • It can be accessed by the key.
  • To find out the length of the dictionaries, use build-in function - len(my_dict)
  • You can use the key as an int, string, tuple, but not as a set, list, or dictionary.
  • To access specific items, use a square bracket like - my_dict[1] - here, one inside the square bracket is a key, not an index number.
  • If a key is not inside the dictionaries will throw a key error message.
  • But if you use my_dict.get(key); no error will throw; rather, it will show the message none.

How to create dictionaries?

  • For empty dict like this - my_dict = {} or my_dict = dict()
  • Dictionaries with items my_dict = {1: ‘apple’, 2: ‘orange’, 3: ‘banana’}

my_dict = {} # empty dictionary
another_way_dict = dict() # empty dictionary

print('What type is it?', type(my_dict))
print('\nWhat type is it?', type(another_way_dict))

How to create dictionary with items?

my_dict_with_items = {1: 'apple', 2: 'banana', 3: 'orange'}

How to find out the length of the dictionary?

print('\n length of the dict:', len(my_dict_with_items))

How to search?

  • To find out the key like this - key in my_dict
  • To find all the keys and values, use the built-in function - my_dict.items()
  • To find out all the keys, only use the built-in function - my_dict.keys()
  • To find out all the values, only use the built-in function - my_dict.values()

How to find out the dictionary key is exits or not?

print('\nTo find out key exits or not:', 5 in my_dict_with_items) print('\nTo find out key exits or not:', 1 in my_dict_with_items) How to find out value by the key? print('\nTo find out the value:', my_dict_with_items[2]) print('\nTo find out the value:', my_dict_with_items[4])
The above line example will throw a key error.
print('\nTo find out the value:', my_dict_with_items.get(4)) 
The above line will not throw an error but rather it will give none message.

How to get all the keys and values of a dictionaries?

print('\nTo get all the keys and values from dict.:', my_dict_with_items.items())

How to get only keys from the dictionary?

print('\nTo get all the keys only from dict.:', my_dict_with_items.keys()) How to get only values from the dictionary? print('\nTo get all the keys only from dict.:', my_dict_with_items.values()) How to add new items in the dictionary? my_dict_with_items[6] = 'watermelon' # key value pairs example print('\nTo add new items in the dict',my_dict_with_items.items()) How to add or update two dictionary together? new_dict = {7: 'cucumber', 8: 'carrot'} my_dict_with_items.update(new_dict) print('\nUpdated dict now :', my_dict_with_items)

For Loop In Python

Let me show you detailed examples of using for loop in Python. At first, I have created a fruit list, and within the fruit list, there are many fruits inside the list. Now, if you want to check whether a fruit is available or not, we can use an operator in Python to find the item.
my_fruits_list = ['apple', 'orange', 'banana', 'watermelon'] print('Is this fruit in my list?:', 'apple' in my_fruits_list) Same thing we can do by the for loop in python.
for fruit in my_fruits_list:
    print(f'Fruit name is :{fruit}')
    

How to use range() function in for loop?

Here range 0 is inclusive I mean 0 will print it will start from 0 and 4 is exclusive I mean 4 will not print, it will stop to number 3
for number in range(11): print(f'Number is : {number}')
How to print specific numbers within the range we can specify start and end. For example, number 1 is inclusive here, and number 10 is exclusive.
for number in range(1, 10): print(f'Here number will print from 1 to 9: {number}') range() function another use specify start, end, increment for number in range(2, 20, 2): print(f'Number is :{number}')

How to print out the index of the items?

We can use the built in function enumerate to do that for index, fruit in enumerate(my_fruits_list): print(f'Fruit :{fruit} is at index no : {index}') How to use for loop in dictionary? my_fruit_dict= {1:'apple', 2:'orange', 3:'banana', 4:'watermelon'} for fruit in my_fruit_dict: print(f'That will return only keys of the dict.: {fruit}') for keys, values in my_fruit_dict.items(): print(f'Fruit :{values} is at {keys} ')
While loop in Python
While loop examples

number = 0
max_number = 5
while number <= max_number:
    print(f'the number is {number}')
    number += 1
    #number = number + 1
If you do not update the number variable, it will run forever. So, it is very important to update the variable. The above example we have updated with plus one.
How to use break statement in python?
Below I have created some examples of using break statements in Python. At first, we will see with a for a loop. Here, I have created a list which is fruit_list, with some fruit in the list.
fruit_list = ['apple', 'banana', 'orange', 'watermelon'] for fruit in fruit_list: print(f'The fruit name is :{fruit}') if fruit == 'orange': break
As you can see, the above example is if the condition was saying that whenever you get a match with fruit orange, you break the loop and get out of the loop. Now, we will see how to use the break statement in the while loop. 
* example -1
fruit = 'orange'
while True:
    if fruit in fruit_list:
        print(f'The fruit is found: {fruit}')
        break
    
* example -2
  
counter = 0
while True:
    counter = counter + 1
    if counter == 20:
        print(f'Count has been done to : {counter}')
        break
In the first example, we set fruit equal orange, and within the while condition, we are saying that if you find it true inside the if condition, then gets out of the while loop, and exactly that happened with the first example. Same with the second example, we set the if condition counter variable equal to 20 and update the counter variable each time with plus 1. So the moment it will be equal to 20, it will get out of the while loop.

How to use continue statement in python?

Using the continue statement inside the python code means that even if the condition is still met, the loop will continue to run. Below is an example of how to use the continue statement in Python.
fruit_list = ['apple', 'banana', 'orange', 'watermelon'] for fruit in fruit_list: if fruit == 'orange': continue print(f'The fruit name is :{fruit}')

How to use continue and break together?

for fruit in fruit_list:
    if len(fruit) !=6:
        continue
    print(f'The fruit name is : {fruit}')
    
    if fruit == 'orange':
        break

How to use return statement inside the loop?

def find_fruit(fruit_name):
    for fruit in fruit_list:
        print(fruit)
        if fruit == 'orange':
            return f'we found out the fruit :{fruit}'
I have done the above function because I have created a function within the function. I have to create a for loop, and within a for loop, I have run a list and created a condition that if you found fruit orange, then the return that fruit.
Calling the above function
print(find_fruit(fruit_list))

How to Read a file in Python?

When you want to read something in python programming and read it from a file on your hard disk or any device, you have to follow some rules. There are some files character that have their meaning in Python. Below I have included their meaning.

'r' - open for reading, and it is a default.
'w' - open for writing, but delete the first one if anything you wrote in the File.
'x' - open for new one creation, but fail it the File already exits
'a' - open for writing and adding more contents at the end of the file exits
'b' - open the File in binary mode
't' - open the File in text mode
'+' - open a file from disk for updating either reading or writing.

Always make sure the File is closed when you finish your program. The below examples are based on the current working directory.

Example 1. 
Reading a json file from the same directory.

my_file = open('sample1.json', 'r')
fruit = my_file.read()
print(fruit) # read and print entire file contents
my_file.close()

Example 2. 
Reading a text file example from the same directory.

my_file = open('reading_my_file.txt', 'r')
print(my_file.read())
my_file.close()

Example 3. 
Reading a text file example from the same directory. The below example its work like a try...catch ...finally. It will close the file automatically and you do not have to use close() to close the file.
with open('reading_my_file.txt', 'r' ) as my_file:
     fruit = my_file.read()
     print(my_file.read())

Example 4. 
Reading a text file example from same the directory.

file = open('reading_my_file.txt')
print(file.readline())# read only one line
print(file.readline(2))# read only specific character from a line
print(file.readlines())# reading all the lines and return as a list
file.close()

Example 5. 
Reading a text file example from the same directory. The below example will iterate or go through each text file line using a while loop.
with open('reading_my_file.txt', 'r') as my_file: line = my_file.readline() while line != '': # '' means empty string print(line, end='') line = my_file.readline() Example 6.
Reading a text file example iterating through for loop. This example is most recommend option.

with open('reading_my_file.txt','r') as my_file:
     for line in my_file.readlines():
         print(line, end='')

Example 7.
If you are more interested use more simplified options.
with open('reading_my_file.txt','r') as my_file:
    for line in my_file:
        print(line, end='')
    

How to Write to a file in Python?

You have to follow some rules whenever you want to write something in python programming and save it as a file on your hard disk or any device. Writing is a common task in python programming. Suppose you want to save any task; you have to write it to a file or other form. Below I have added a few examples of writing in the python programming language. 
How to write in a file with write() and writelines() function?
Example with writelines() function
with open('writing_my_file.txt', 'w') as my_writing_file:
     writing_file = my_writing_file.writelines('we are learning python basic.')
     my_writing_file.close()
Example with write() function
with open('writing_my_file.txt', 'w') as my_writing_file:
     writing_file = my_writing_file.write('we are learning python basic and how to writing to a file.')
     my_writing_file.close()
How to append in a file with write() and writelines() function?
Example with append writelines() function
with open('writing_my_file.txt', 'a') as my_writing_file: writing_file = my_writing_file.writelines('\nwe are learning python basic.') my_writing_file.close()
Example with append write() function
with open('writing_my_file.txt', 'a') as my_writing_file:
    writing_file = my_writing_file.write('\nwe are learning python basic and how to writing to a file.')
    my_writing_file.close()

How  to take user input in Python?
The beauty of the programming is the user interaction. So, whenever your program does user interaction, you need to get information from the user as input from your program. So, this is how you can take input from the user.
fruit = input('What fruit do you like?: ') print('I like ', fruit)
Input () built-in function always takes input as a string. So if you want a numeric number, you have to convert it to int format.
first_number = int(input('Enter a first number:')) second_number = int(input('Enter a second number:')) total = first_number + second_number print('Total is:', total)
Let's see what if, if you do not convert it to int format, how it looks like.

first_number = input('Enter a first number:')
second_number = input('Enter a second number:')
total = first_number + second_number
print('Total is:', total)

Try Except Finally in Python
To run your program nice and smoothly and get a better user experience, you have to put as much error-free code. To get a better user experience and crush free your program, use in your code try-catch and finally condition. Below I have added a number of examples of how to use try-catch and finally.
Example 1.
with open('reading_myy_file.txt','r') as my_reading_file:
        read_file = my_reading_file.read()
        print(read_file)
The above example will give an error and show lots of unnecessary messages to the user, which will frighten the user. To overcome this below example, we used try-catch.
Example 2.

try:
    with open('reading_my_file.txt','r') as my_reading_file:
        read_file = my_reading_file.read()
        print(read_file)
except:
    print('File not found error')
    
If the File is not exited in the above example, it will give a 'File not found error' message instead of a Python-generated unnecessary message in the console.

Example 3.
try:
    with open('reading_myy_file.txt','r') as my_reading_file:
        read_file = my_reading_file.read()
        print(read_file)
except FileNotFoundError as file_error:
    print(file_error)

The above example file name purposely wrote the wrong name to show the example demonstration. Therefore, if you want to practice the code as mentioned above example, make sure you create a file in the current directory.
Example 4.
try:
    with open('reading_myy_file.txt','r') as my_reading_file:
        read_file = my_reading_file.read()
        print(read_file)
except FileNotFoundError as file_error:
    print(file_error)
finally:
    print('This part will run, no amtter what happen up.')    

We can use as many as except to catch the error; also, we can use else within else block we can use try-catch block.

Skeleton of the try-except else finally.
#try:
    #some code
#except:
    #some code
#else:
    #try:
        #some code
    #except:
        #some code
#finally:
    #some code


Mohammed J Alom

Hi, Thank you so much for visiting my blog programming with mohammed. First, a little bit of myself, I graduated from MTU Munster Technological University with BSc (Hons) in Software Development. I am currently pursuing MSc in Artificial Intelligence. I am very interested in programming and love to learn new technologies and help and teach others.

Post a Comment (0)
Previous Post Next Post