Welcome to my journey of 100 days of coding . I will be documenting my journey from zero to advance in python
Projects Completed |
---|
1.Rock,paper and scissors |
2.Kaun bangega crorepati |
3.Coffee machine |
4.Betting on turtle race game |
5.Snake game |
6.Mile to km app |
7.Pomodoro app |
8.Password manager app |
9.Flash card app |
10.Kanye West Quote generator app |
11.Iss satellite checker |
Core python |
---|
1.Language Fundamentals |
2.Operators |
3.Input and Output statements |
4.Flow Control |
5.Strings |
6.List Data Structure |
7.Tuple Data Structure |
8.Set Data Structure |
9.Dictonary Data Structure |
10.Functions |
11.Modules |
12.Packages |
Today I learned some basics in python like data types in python and about typecasting in python. There are two types of typecasting in python
1.Implicit typecasting: conversion data types by program itself for e.g: a=10
b=2.0
sum=a+b
print(sum)
#sum will be in float because of implicit typecasting
- Explicit typecasting: conversion of data types by programmer is called explicit typecasting . for e.g :
a=10
b=2
sum=a+b
print(float(sum))
#sum is in integer and changed to float using explicit typecasting
Here is day2 codes I have learned about string slicing . String in python is similar to array .
name="Elephant"
length=len(name) #this len function provides the length of name
print(name[2:3]) #this print e
print(name[1:5]) #this print leph
#this above example is string slicing
This program greet you according to your time . It import time from your computer using
import time
strftime()
After that greeting is done using elif codition as seen below :
Match case is similar to switch case in c and c++ but there is no necesary of using break If you donot know about c and c++ Match case is used to select case according to option here is a sample program:
It is a sequence data types in python that is a collection of sequence of elements. for e.g:
lst=[1,2,56,"hari","alex",false]
Yes as you can see list can contains different data types.
Tuples is also similar to list but it cannot be changed (i.e immutable) Clear explanation of list is shown below
There are various method to perform with list that help in program some of them are:
It sort the list in ascending order
It gives index of first occurence of the list item
here output will be 1 for colours list and 3 for num list .
It counts number the number of items of given value
for e.g colors.count("green")
This will count number of time green occured in list colors
All others important list method are as follows :
Today we are going to learn about the tuples in python . Tuples are similar to list but it is immutable(i.e it cannot be changed). It also hold collection of data items . Tuples items are separated with comma and enclosed with small brackets for e.g:
tuple=(1,4,6,7)
tuple=(1)
print(type(tuple)) #this is printed as class int it should contain one , to be tuple
tuple=(1,)
print(type(tuple)) #this is printed as class tuple
Today I learned about the method on tuples . Tuples exactly is immutable so it does not have any method that changes data item but we can perform this by changing tuples into list changing data items and changing it to tuples . Although we can perform some operation like index,len,etc . Code for the method in tuples is shared below hope you get some insights .
f-string is a new string formatting mechanism that allow us to enter variable directly in between the string according to our format. for e.g:
val="geek"
print(f"{val} for {val} is a portal for {val}")
Python docstrings are the string literals that appears right after the definition of function,class,method or module. Its like comment but its not ignored by python interpreter and cannot be used anywhere it mostly used to describe function workflow
PEP 8 is a guidline in python programming that makes python readable,maintainable and consistent . It stands for Python Enhancement Proposals
Set is an unordered collection of data items in a single variable enclosed by curly braces and element separated by comma . Set doesnot contain duplicate item
Recursion is the special case in which function call itself directly or indirectly to meet desired result. such function is called recursive function
union() helps to find the union of two sets and update helps to update the sets value.
s1={1,4,5,7,9}
s2={1,4,6,7,8,9}
print(s1.union(s2))
s1.update(s2)
print(s1)
intersection() finds common value of two sets wherease intersection_update() update the sets with intersection.
symmetric_difference() gets items that are not similar on two sets and symmetric_difference_update() the sets with different items of two sets
difference() gets items that are not similar from original sets and difference_update() update the sets with difference items from original sets.
Some of other sets methods that we can use are:
Dictionaries are ordered collection of data items. They store multiple items in a single variable.Dictionaries items are key-value pairs that are separated by commas and enclosed with curly brackets.Dictionaries doesnot allow duplicate items.
dict={"name":"ram",
"age":"21"}
print=(dict)
There are lots of methods in dictionaries some of them are listed below:
The update() methods update the values of the key provided else creates a new key:value pairs if the key used in update doesn't exists in that dictionaries.
Example:
dict1={234:12,235:89,238:23}
dict2={234:17,239:45}
dict1.update(dict2)
Here,Since value of key 234 already exists i.e 12 gets overwrite as 17 dueto update methods
whereas new key value pair is updated on dict1 i.e 239:45.
sample program for update method is given below:
pop() methods is used to remove key value pairs from dictionary and del is used to remove entire dictionary.
For learning more about dictionaries
Today I am creating KBC(Kaun banega crorepati) using my concepts of loop and list . Here is the code ,Hope you get some insight
Exception handling is the way of dealing with unwanted errors in programs. one of the way of exception handling by using try and except
try:
#statements which could generate
#exception
except:
#Soloution of generated exception
try:
num = int(input("Enter an integer: "))
except ValueError:
print("Number entered is not an integer.")
Finally is also type of exception handling it is use when some statement or code had to be excecuted anyway . finally is executed no matter what error occured or not (it also executed if it is running after return 0)
try:
#statements which could generate
#exception
except:
#solution of generated exception
finally:
#block of code which is going to
#execute in any situation
In the above index is out of range so error occured and code inside except: is executed and after that code inside finally: is executed.Code inside finally: is executed whether error occurs or doesnot occurs.
In python, we can create custom error by using raise
keyword .
We raise error to throw the exception from program .
Lets see a example:
** Objective: **To throw error if user enter number not between 1-4.
There is a shorthand syntax for if...else statement that can be used when condition is simple and codeblocks to be executed is short.
Caution:
It is not used when codeblock is long and complex as this reduce code readability.
Here is a sample example :
lets get start with some difference betweem POP and OOP Procedure Oriented Programming(POP): Total activity is divided into multiple functions and we call those based on our requirements. Object Oriented Programming(OOp) : Total activity is divided into realtime entities called objects.
- Class : Class is a blueprint/model which contains different entity inside it like properties(variable) and method(actions) which is inherited by objects.
- Objects : Objects is the physical existence of class.
Here is a simplest program that reflects OOP in python :
Before performing any operation on file we have to know about the modes of file handling
- Read : 'r' it allows reading file
- Write : 'w' it allows to write in file
- Append : 'a' it allows to append in file
Here is simplest program to clear your basic in filehandling
You can practice more on file handling Click here for read in filehandling
You can practice more on file handling Click here for write in filehandling
Enumerate function is a built in function in pythons that allows you to loop over a sequence such as list,tuple,string and get the index
and value of element at the sametime. Some basic examples on how it works are shown below :
Importing in python is the process of loading code from a python module to the current script.This allows you to use functions and variables defined in the module in your current script. You can simply import any module by writing import followed by the name of the module. for e.g:
import math
After importing math function as shown above you can use various function provided by math module like sqrt(),floor() and manymore
sample:
import math
square_root=sqrt(9)
floor_number=floor(4.676)
from keyword is used to import specific function from module .
from math import sqrt
we can everything available on module by using from followed by module* But this isnot recommended because it make harder to understand where the specific function and variables are coming from.
from math import*
We can rename the module in python by the use of as keyword for e.g:
import pandas as pd
import math as m
Python has built in function dir that allow you to view all the functions and variable available in modules.It help to understand and explore new module .
for e.g:
import math
print(dir(math))
This is a common idom used in python to determine whether the module imported should run directly or use as module . So when we import any module it get executed
directly in our script and to avoid this direct execution we used __name__=="__main__"
.
one sample is given below:
We can see that welcome() function is running directly after importing side module in main script and output get printed twice one from direct execution of module and another from calling of function after importing module.
So the main use of __name__=="__main__"
is to import any module without running it functions directly.
This funcion is also known as anonymous function in python because it does have any name like function but behaves like function
syntax:
lambda_expression= lamda (parameter list)=expression
For e.g:
f= lambda a:a*a
print(f(5))
Above lamda function is used to find square
Web scraping refers to the extraction of data from a website. This information is collected and then exported into a format that is more useful for the user.
- first we will install request library by using requests library, we can fetch the content from the URL given
pip install requests
- Also we will install beautiful soup that helps to parse(change format) data and fetch the details the way we want. You can use a beautiful soup library to fetch data using Html tag, class, id, css selector and many more ways.
pip install beautifulsoup4
I am going to show you a sample of scrapping method and final results of it in excel file
- Scrapped website Link
- Code that has done scrapping is given below :
- beautiful data after scrapping:
You can learn more on HTTP and requests from here
Today we are applying our learning and scrapping data from website of tata ipl auction 2022
- Here is the sample code that does all our scrapping:
In python map,reduce and filters are built in function that allows you to apply a function to the sequence of element and returns a new sequence.These functions are called higher order function because they takes functions as arguments.
Note:we can use lamda fucntion to make it more easier and efficient
lets learn each of them .
- Map function Map function simply performs the function on the given iterable sequence and return a whole new sequence of data. syntax:
map(function,iterable)
- Filter Filter simply filter the sequential data according to our defined predicates(i.e function) and give us selected data that passes condition after filtering. syntax:
filter(predicate_function,iterable)
- Reduce
from functools import reduce
reduce(function,iterable)
Return is also similar higher oder function but it returns a single value output not a list or sequence of data and ```it needs to be imported from functools.
Today I created a project using python which is coffe machine. Click here for its code
Python has lots of library to use we can simply use it by installing it ,importing it and reading documentataion to use it.
Here is the sample of me using PrettyTable
library by installing it,importing it.
OOP is the main usecase of python and many other programming languages that solves realworld problems.
In Day16 We have discussed basic of object and class . Today we are going to discuss about different concepts of OOP in python like:
This function is always initiated when the class is being iniated . It passes values to object properties, or other operations that are necessary to do when the object is being created.
The str() function controls what should be returned when the class object is represented as a string.
Objects method is the function in objects. Let create a sample object method
Before learning about turtle graphics let us see about importing ways once.
Always remember to break down your poblem,write pseudo code and start coding . Here is a sample solution of problem that I created ,You can understand problem and solution by reading code and comments.
Output:
- code:
- Output:
Today I learned to create hirst painting which is sold in millon dollars in muesum using python. This learning is helping me to build strong problem solving and programming logic .
- Hirst painting : We have to create similar painting
- Code: My code is as follow
- Output : Here is final result
Using turlte I created a screen where user can draw and erase by themself
I have created a very fun project where six different color turtle are racing , you can bet on any color of turtle and at last winner turtle will be declared,If winner is similar to bet you will won . This projects has been very fun it uses many concepts of python like loop,list,modules. Here is a code for this project hope you get some insight
Today I started to create snake game and it challenge my logic to core mainly to create the movement of segment it was challenging.
- screen
- snake body
- segment movement , snake movement Here is a code which will be completed tomorrow for full game
Today I continued snake game and made snake to move according to botton,created food,made snake to eat food . It is still incomplete
- movement of snake
- food
- consuming food by snake You can check the code of till data here
Today I completed the snake game and in total it was awesome and very fun projects . Here is sample of how game looks like
You can check this game by
- first run this on terminal
pip install turtle
- And download this and run
Today I continued my learning on webscraping and scraped a website .
Today I scrapped tesla revenue where I learned about how to select specific table from many tables in website.
- use find_all to find all table and use indexing of table you want to retrieve , because find_all create list.
- scrapped website url
- Code
- csv file
click
Today I learned about how to createa and work on virtual environment.
Started to learn about streamlit which is a Interactive Data Visualization Web Application .
Here is a sample code to create webapp using streamlit.
Today I learned about list comphrension using it we can really reduce the line of codes.
List comprehension is a concise way to create lists in Python. It is a syntactic construct that allows you to create a new list by specifying an expression and an iterable, along with optional filters and conditions. Here's the general syntax:
new_list = [expression for item in iterable if condition]
Here is a sample program without using list comphrension vs with using list comphrension:
Using list comphrension:
Today I learned about dictionary comphrension , looping in pandas dataframe and solved some problem related to it.
syntax:
new_dict ={new_key:new_value for item in list }
we can also create a new dictionary from existing dictionary :
syntax:
new_dict ={new_key:new_value for (key,value) in dict.items() }
also we can use conditional statement as we did in list comphrension
syntax:
new_dict ={new_key:new_value for (key,value) in dict.items() if condition}
Here is a sample program for dictionary comphrension :
Here is a sample program for looping in pandas dataframe:
- The NATO phonetic alphabet is a standardized spelling alphabet used by NATO militaries and other organizations to communicate information over radio or telephone in a clear and unambiguous way. It uses a set of 26 code words, each representing one letter of the English alphabet, to avoid confusion between similar-sounding letters.
Here is a code for this nato phonetic code generator.
Today I learned about *args and **kwargs.
*args is used to pass a variable number of non-keyword arguments to a function. It allows you to pass any number of arguments to a function, which are then packed into a tuple. Here's an example:
def my_func(*args):
for arg in args:
print(arg)
my_func(1, 2, 3)
# Output: 1 2 3
**kwargs is used to pass a variable number of keyword arguments to a function. It allows you to pass any number of keyword arguments to a function, which are then packed into a dictionary. Here's an example:
def my_func(**kwargs):
for key, value in kwargs.items():
print(f"{key}: {value}")
my_func(name="John", age=30, city="New York")
# Output: name: John, age: 30, city: New York
Today I learned about strong typing and dynamic typing and built pomodoro app using python library tkinter. Python is strongly, dynamically typed.
- Strong typing means that the type of a value doesn't change in unexpected ways. A string containing only digits doesn't magically become a number, as may happen in Perl. Every change of type requires an explicit conversion.
- Dynamic typing means that runtime objects (values) have a type, as opposed to static typing where variables have a type. for e.g:
a = 5 #int
a= "ram" # string
In above program a is firstly integer and later assigning string chages it to string this is called dynamic typing.
You can check full code here
Today I made password mananger app using tkinter it save your details in file.txt using file handling and also can generate your password.
It is safer to save local than online .
click here for full code.
Today I updated some features in my password manager by using json.load() , json.dump() , json.update() technique. some details of updates are:
- data that user entered will be saved in json format .
- user can search their saved email and password .
- handle all exception that can crash program like if file doesnot exist it will be created using try and except.
click here for final app code
Today I made flash card app using tkinter , In this app you will be shown french word first and after 3 seconds you will be given it english translation . If you know answer and click tick button the word will not be shown again but if you didnot know answer and click cross button the word will be shown again.
Highlights of app
- You will select ✓(If you know) and ❌(if you dont know)
- The word you know will not be repeated
- The translation of french to english will be shown after 3 seconds.
some glimpse of app:
After 3 seconds it will show translation
click here for full code.
Today I learned about API and built some project using api
API
An api a set of commands,functions,protocols and object that programmer can use to create software or interact with an external system.
- API endpoints : API endpoints are the specific digital location where requests for information are sent by one program to retrieve the digital resource that exists there
- API requests : A request includes the URL of the API endpoint and an HTTP request method. The method indicates the action you want the API to perform. Here are some of the most common methods:
GET retrieves data from an API. POST sends new data to an API. PATCH and PUT update existing data. DELETE removes existing data.
Also I learned about HTTP Status code
- 1xx : Informational
- 2xx : Success
- 3xx : Redirection
- 4xx : Client error
- 5xx : Server error
I also built kanye west quote generator app using kanye.rest API
Kanye West Quote generator app
This program check ISS satellite if it is overhead you and its night then it will send email to your mail and tell you that iss is overhead.
Iss satellite checker
Here is a sample of code :
Today I revised my knowledge on intermediate Html before getting started with webscrapping and selenium .
- I got to know that tags under meta are very important thing for seo optimization.
- we should prefer
<strong>
in place of<bold>
tag , also<em>
in place of<i>
tag because they help you to highlight expressions that you think are important, and which represents a web page's interest.
Here is sample website I build today as part of learning using Html only.
Today I revised my knowledge about css before getting started with webscrapping in python.
CSS selector
- element selector
Directly selects Html element for styling
img
{
}
- class selector
Select element on the basis of it class name , One page can used same class name in different items.
.class_name
{}
- id selector
The id of an element is unique within a page, so the id selector is used to select one unique element!
#id_name
{}
Here is a sample css written that give you basic idea.
Today I learned more about intermediate css like display properties,css positioning,font-styling.
The display property is used to control how an HTML element is displayed on a webpage.
There are several possible values for the display property, including:
- block: Makes the element a block-level element and takes up the full width of its parent container.
- inline: Makes the element an inline-level element and takes up only as much width as necessary.
- inline-block: Makes the element an inline-level block container, meaning it behaves like an inline element but can have a width and height set.
- none: Hides the element from the page entirely, effectively removing it from the document flow.
- flex: Turns the element into a flex container, allowing for flexible layouts with child elements.
- grid: Turns the element into a grid container, allowing for grid-based layouts with child elements.
There are four main types of CSS positioning: static, relative, absolute, and fixed.
- Static positioning is the default position of elements on a webpage and they flow in the order they appear in the HTML document.
- Relative positioning allows elements to be positioned relative to their original position, with the use of the top, bottom, left, and right properties.
- Absolute positioning positions elements relative to their nearest positioned ancestor, or the document body if no ancestor is found.
- Fixed positioning positions elements relative to the browser window and the element stays in the same position even when the page is scrolled.
Today I revised by concepts on webscrapping and learn how to scrapped any website using css selector and also with html using beautifulsoup.
Here is a sample program that extracta all news and its details like link,upvote and atlast it display news with highest upvote.
Todat I completed a project in webscrapping where user inputs the date and get top 100 music of that date.
Here is a code snippet for the above program:
Output looks like:
Todat I created a program that scrape amazon webiste and send the price of product you selected to your email. In this project I learned following things
- to scrape website like amazon you have to pass header which you can generate from www.myhttpheader.com
- also learned about smtplib library used to send email in python.
Today I learned about selenium,Selenium is an open-source tool that automates web browsers.
Using selenium I created a program that automatically scrapped the require data from a website and store it json format.
Today I created bot using selenium that play web game called cookie clicker and upgrade item in enough points.
Today I get started with flask which is a framework in python. I learned about decorator,some basic of shell commands.Here is a snapshot of what I learned.
- Decorator Python decorators is a technique for changing the behavior of an existing function without changing actual code inside the function.
here is a sample of decorator and how it works
Here is a simplest way to create flask app:
Today I learned about debugg mode,working with flask url,and more about advnaced decorators.Below is some explanation and snapshot of what I learned today.
- Debugg mode:
When debug mode is on it allows automatic reload.
if __name__ == "__main__"
app.run(debug = True)
- Working with flask url:
You can modify flask url to work like you want here is sample
@app.route("/<name>/<int:number>")
def greet(name, number):
return (f"Hello {name}! You are {number} years old")
- rendering html elements with flask
- advanced decorators.
Here is a decorator that I created that check authenication of login
Here is snapshot all concept I used in sample flask app.
Provide flask template for creating website with simple and organized file structure.
we can use python functionalities in html file using '{{ }}' double braces. Its python file should be implemented in .py
Note: Template should be inside templates
file which is index.html file generally
here is sample code that use jinja methods to import python functionalities in website
day57 code
Today I learned about using multiline template and generating url in jinja and applied them on my server.
you can check full implementation on this day 58 code
- Multiline is usef for thing like using for loop , if else condition inside html file
<h1>{% for i in range(5): %} </h1>
<h2>{{ hello }}</h2>
{%endfor%}
- URL building with flask
<a href="{{ url_for('function_name',other parameter)}}">press</a>
Today, I learned about using Bootstrap to build responsive websites. Bootstrap is a popular front-end development framework that provides pre-built components and styles to help developers create beautiful, responsive websites quickly and easily.
To start building a website with Bootstrap, it's important to first create a mockup or wireframe of your website design. This can help you plan out the layout and structure of your website, and ensure that it meets your requirements and goals.
I also learned about some of the key features of Bootstrap that make it easy to create responsive websites. These include:
Grid system: Bootstrap's grid system is based on a 12-column layout, which can be easily customized to fit the needs of your website.
Responsive breakpoints: Bootstrap includes responsive breakpoints that allow you to adjust the layout of your website based on the size of the user's screen.
Pre-built components: Bootstrap provides a variety of pre-built components, such as navigation menus, forms, and modals, that can be easily customized to fit your website's design.
Overall, I found today's lesson on Bootstrap and mockups to be very helpful, and I'm excited to start building my own responsive websites using this framework. Tomorrow, I plan to dive deeper into the grid system and explore how to use it to create complex layouts.
Here is a sample of website that I built today.
Today, I created a falsk app that is used for iris flower classification based Decision tree algorithm and deployed it in flask server to make it user interactive.
Here is demo of project :
* Iris flower classificaiton webapp
- Today I learned about super() method in python which is used incase of multiple inheritance it allow us to call any method or function from parent class in base class. Here is a sample hope you get some insights
- Today I learned more on webscrapping especially dealing with loading more pages , I have scrapped around 1.1k articles from kathmandu post for a project using beautiful soup. You can deal with pagination using json file available in network developer tool. Since the kathmandu post didnot have proper json showing changes in pages I use selinum to automate the load more option and scrapped all data using beautiful soup.
- Today I started learning FastAPI and learn about FastAPI request methods , also worked on simple student register system where I added functionality for adding student, searching student a, searching course , updating passed student and displaying results using python and learned about some method of regex to manage desire input , used datetime module to check various condition of update status like if student has date of later than today or if the date is not correct format.
- Implemented logging in python which keep tracks of the exception or any failure in code which makes debugging a lot more easier as failure are easier to find by logging
- As a part of learning fast API today I built a webapp that accept image and using deep learning to model to classify it.