Python
Python
This is important to note that if we want to print the first character of any
string in python, we do so by passing the index after the string. For example :
print("Hello"[0]) ===> o/p = h. This method of capturing an element from a string
is called as subscripting
#Data Types
#String
print("hello"[4])
#Integer
print(123 + 345)
#The underscores are treated as imaginary commas by the computer. Just like we
humans tend to put commas between large numbers.
123_345_332
#Float
3.14159
#type function -> this function can be used to find the type of the data.Not only
string we can convert string to int, int to float, and many more.
strr = len("Arya")
print(type(str))
#type conversion or type casting - basically the practice of converting a data from
a type to another type.
new_num_char = str(strr)
print(type(new_num_char))
#PEMDAS or BODMAS
()
**
*
/
+
-
Well actually multiplication and division both have equal priority, but it depends
which operation is written to the left first when it comes to prioritizing betweent
them.
print(3 * 3 + 3 / 3 - 3)
#always check the type of the input data before performing any operations
#if we want to add a variable or any other data type between a string, instead of
manually converting it to number, we can use something known as f string. Basically
before start of double quotes or as we say in python in front of start of double
quotes just add letter f and wrap your variable name inside {} wherever you use.
score = 0
isWinning = True
print(f"your score is {score}, your height is {score} and are you winning is
{isWinning}")
if a >b:
print()
else:
print()
list in python are just like arrays, the only difference is that lists can store
the data of multiple types such as number, strings, and negative index corresponds
to the last val starting like names[-1] will get the last value because -0 is
nothing in math.
list.append adds item to the last of the list
list.extends adds another list to the last of the list.
there are many methods that are available in the lists.
imp:
# Import the random module here
import random
# Split string method
names_string = input("Give me everybody's names, separated by a comma. ")
names = names_string.split(", ")
# :rotating_light: Don't change the code above :point_up_2:
#Write your code below this line :point_down:
name_length = len(names)
print(name_length)
final_name = random.randint(0, name_length-1)
final_name_val = names[final_name]
print(f"{final_name_val} is going to buy the meal today!")
we can use nested lists.
list1
lis2
nested = [list1, list2]
the two lists work as a 2d array or matrix
very imp day 4.3
# :rotating_light: Don't change the code below :point_down:
row1 = [":white_large_square:️
","️:white_large_square:️
","️
:white_large_square:️
"]
row2 = [":white_large_square:️",":white_large_square:️","️
:white_large_square:️"]
row3 = [":white_large_square:️️
",":white_large_square:️️
",":white_large_square:️️
"]
map = [row1, row2, row3]
print(f"{row1}\n{row2}\n{row3}")
position = input("Where do you want to put the treasure? ")
# :rotating_light: Don't change the code above :point_up_2:
#Write your code below this row :point_down:
horizontal = int(position[0])
vertical = int(position[1])
map[vertical - 1][horizontal-1] = "X"
#Write your code above this row :point_up_2:
# :rotating_light: Don't change the code below :point_down:
print(f"{row1}\n{row2}\n{row3}")
its colxrow not rowxcol in python
Arya
9:04 PM
fruits = ["apple", "pear", "orange"]
for i in fruits:
print(i)
print(i + " pie")
print(fruits)
#3rd arg in range fn defines the step size like how many steps should be added
for i in range(0, 10, 2):
print(i)
#add all numbers from 1 to 100
sum = 0
for i in range(1, 101):
sum = sum + i
print(sum)
also, the in returns true if it exists and returns false if it does not exists
programming_dictionary= {
"Bug": "A program which causes an error, usually a faulty program",
"Function": "A piece of code"
}
print(programming_dictionary["Bug"])
#if we want to add an item in the dictionary
programming_dictionary["Loop"] = "This is the added piece of data"
print(programming_dictionary)
#if we want to wipe an entire dictionary
new_dict = {}
programming_dictionary = new_dict
print(programming_dictionary)
# print(timmy)
# timmy.shape("turtle")
# timmy.color("blue")
# timmy.forward(100)
# my_screen = Screen()
# print(my_screen.canvheight)
# my_screen.exitonclick() #this is a method of the class Screen. and the object
my_screen
from prettytable import PrettyTable #read more in pypi documentation
table = PrettyTable()
table.align = "l"
table.field_names = ["Pokemon Name", "Type"]
table.add_row(["Pikachu", "Electric"])
table.add_row(["Oshawatt", "Water"])
table.add_row(["Charmander", "Fire"])
print(table)
#higher order functions in python are the functions that sit on the top of other
functions and return other functions result.eg:
def add(n1,n2):
return n1+ n2
def subtract(n1,n2):
return n1- n2
def divide(n1,n2):
return n1/ n2
def multiply(n1,n2):
return n1* n2
at a particular instance any object can be different from another and that is
called as a state of the object
the turtle coordinate system is just like a graph. If the height of the window is
set to 400, then this means +ve 200 on the y axis and -200 on y axis which means up
200 plus down 200 equals 400
# file = open("my_file.txt")
# contents = file.read()
# print(contents)
# file.close() #because opening a file in python takes resources of your system so
to free them after the work has been done
#write to file
# with open("my_file.txt", mode="w") as file:
# file.write("Heyyy!")
#if we want to not delete the file contents instead add to the contents, then we
add a as the mode, which means append
with open("my_file.txt", mode="a") as file:
file.write("\nAdded comment") #\n for new line
# if we open a file in WRITE mode and if it does not exists, it will create that
file for us
# with open("/Users/aryavats/Desktop/new_file.txt", mode="w") as file: #absolute
file path
# file.write("Something added")
9:55
lst[:5]
everything upto position 5 excluding 5
9:55
works for negatives as well
9:57
lst[0:3:2] -> here 2 is the increment step, it will give us every 2nd item or
alternate item from index 0 to 3(excluded)
9:57
lst[::2] --> same way but shorter way only specifying the increment step value
9:58
lst[::-1] ->this will swap the list, starting from end to beginning if -1 is the
increment step value (edited)
10:00
works for tuple as well
tp = ("a", "b", "c", "d", "e")
print(tp[2:4])
o/p = (c,d)
we will be handling different types of error and exceptions in python
#try
the try block is used to define something that might cause an exception. Something
that we are not sure of either
except - this is used in case of an exception, used in case if try goes wrong
finally is a block to carry out the operations in case of everything like mandatory
4
#filenotfound
try:
file = open("a.txt") #filenotfounderror
a_dictionary = {"key": "value"}
print(a_dictionary["sdjjd"])
except:
print("hello")
it is although never recommended to use except as except catches all the errors
and executes whats inside it, it has a very broad scope, for instance above, except
will ignore the first error as well as the second dictionary error(key not found),
so it is DANGEROUS.
try:
file = open("a.txt") #filenotfounderror
a_dictionary = {"key": "value"}
print(a_dictionary["sdjjd"])
except FileNotFoundError:
print("hello")
we can use multiple except blocks as well and also we can catch the error message
for each error like below:
#filenotfound
try:
file = open("a.txt") #filenotfounderror
a_dictionary = {"key": "value"}
print(a_dictionary["sdjjd"])
except FileNotFoundError:
open("a.txt", "w")
print("Halo")
except KeyError as error_message: #catching
print(f"the key: {error_message} does not exist")
#filenotfound
try:
file = open("a.txt") #filenotfounderror
a_dictionary = {"key": "value"}
print(a_dictionary["sdjjd"])
except FileNotFoundError:
open("a.txt", "w")
print("Halo")
except KeyError as error_message:
print(error_message)
else: #this will trigger only when try is successfull
content = file.read()
print(file)
raise #this is used to generate our own exceptions. format is like this
raise TypeError("this was an error")
# #filenotfound
#
# try:
# file = open("a.txt") #filenotfounderror
# a_dictionary = {"key": "value"}
# print(a_dictionary["sdjjd"])
# except FileNotFoundError:
# open("a.txt", "w")
# print("Halo")
# except KeyError as error_message:
# print(error_message)
# else: #this will trigger only when try is successfull
# content = file.read()
# print(file)
#
# finally: #run no matter what happens
# file.close()
# raise TypeError("This is an error that i made up")
#
#
fruits = eval(input())
# 🚨 Do not change the code above
# TODO: Catch the exception and make sure the code runs without crashing.
def make_pie(index):
try:
fruit = fruits[index]
except IndexError:
print("Fruit pie")
else:
print(fruit + " pie")
json.dump() is used to add json data to any file, can be used with open.
with open("creds.json", mode='w') as my_file:
json.dump(new_data, my_file, indent=4)
entry_password.delete(0, END) #delete the text in the entry from start
of range till end
entry_website.delete(0, END)
entry_email.delete(0, END)
import random
import pandas
#list comprehension
#a way to write shorthand for large statements for eg:
# new_list = [n+1 for n in numbers] #here n+1 is the new_num basically. Same as
above
#
# new = [n*2 for n in range(1, 5)]
# print(new)
}
df = pandas.DataFrame(students_dict)
print(df)
for (index, row) in df.iterrows(): #iterrows basically iterates through rows rather
than columns also included, index here is the index number and row is the row value
print(row)
# print(row["names"]) or row.names
if row["names"] == "Angela":
print(row["marks"])
Arya Vats
11:41 PM
we can give default arguments in python like:
def calculate(a=5, b=4, c=9):
return something
now if i call this fn, and specify no args or maybe only one arg like b = 1, then
it will change only that arg and rest all will be default
Arya Vats
12:07 AM
import tkinter
window = tkinter.Tk()
window.title("My first GUI")
window.minsize(width=500, height=300)
#label
Arya Vats
12:48 AM
def add(*args): #args is a tuple
#args[0] will be equal to 2
sum = 0
for n in args:
sum+= n
return sum
print(add(2,4,5))
class Car:
def __init__(self, **kwargs):
self.name = kwargs.get("name")
self.model = kwargs.get("model")
my_car = Car()
print(my_car.model) #if i dont provide a value in car class above upon
initialisation, it will throw error, better approach is to use kwargs.get["name"],
so in this case if i dont specify name it will not throw any error but will return
none.
Arya Vats
3:04 AM
import tkinter
window = tkinter.Tk()
window.title("My first GUI")
window.minsize(width=500, height=300)
#label
my_label.grid() #used to position. place can also be used but in that we need to
specify the x and y coordinates - takes in 2 arg, row and col, for eg, row 0, col
0, will be top left, and also pack and grid cannot be used together, its either
pack or grid.
def clicked():
inp = input.get()
my_label["text"] = inp
Arya Vats
3:11 AM
window.config(padx=10, pady=4)
to add padding to the main window on left and right
3:13
to add padding to specific widget, eg, my_label
my_label.config(padx, pady)
import smtplib
my_email = "[email protected]"
password = "fllg bljk ohva fspi"
# connection = smtplib.SMTP("smtp.gmail.com") #location of our email server
# connection.starttls()
# connection.login(user=my_email, password=password)
# connection.sendmail(from_addr=my_email,
# to_addrs="[email protected]",
# msg="Subject:Hello\n\nthis is the content of the email or the
body") #we add subject by typing subject: and we add bidy by prepending \n\n before
the body content after the subject.
#
# connection.close()
#we do not need to close the connection everytime, we can achieve auto close
similar to file open using with.
import datetime as dt
now = dt.datetime.now()
year = now.year
time = now.today().time()
day_of_week = now.weekday() #computers start counting from 0, so add one in the
weekday to get the actual value
print(day_of_week)
import smtplib
my_email = "[email protected]"
password = "fllg bljk ohva fspi"
# # connection = smtplib.SMTP("smtp.gmail.com") #location of our email server
# # connection.starttls()
# # connection.login(user=my_email, password=password)
# # connection.sendmail(from_addr=my_email,
# # to_addrs="[email protected]",
# # msg="Subject:Hello\n\nthis is the content of the email or
the body") #we add subject by typing subject: and we add bidy by prepending \n\n
before the body content after the subject.
# #
# # connection.close()
#
#
# #we do not need to close the connection everytime, we can achieve auto close
similar to file open using with.
#
#
# with smtplib.SMTP("smtp.gmail.com") as connection: #location of our email server
# connection.starttls()
# connection.login(user=my_email, password=password)
# connection.sendmail(from_addr=my_email,
# to_addrs="[email protected]",
# msg="Subject:Hello\n\nthis is the content of the email or
the body") #we add subject by typing subject: and we add bidy by prepending \n\n
before the body content after the subject.
import datetime as dt
import random
now = dt.datetime.now()
year = now.year
time = now.today().time()
day_of_week = now.weekday() #computers start counting from 0, so add one in the
weekday to get the actual value
print(day_of_week)
else:
print(":(")
import requests
my_lat = 51.507351
my_lng = -0.127758
parameters = {
"lat": my_lat,
"lng": my_lng
}
#the sunset api expects a parameter. Basically parameters in api are the queries
that we give to get a particular piece of data
response = requests.get(url="https://api.sunrise-sunset.org/json",
params=parameters)
print(response.json())
response.raise_for_status() #displays the status code along with the message
# the thing is that it will work fine, but HTML has to distinguish between some
symbols for eg >, "" because it needs to differentiate if these symbols are a part
of code or they are just text, so for that HTML
# uses certain encoding, such as "I disapprove of what you say, but I will
defend, here ", to know more we can go to
https://www.w3schools.com/html/html_entities.asp,
# anyways so to fix this we use the html module and use the.escape() method to fix
this.
q_text = html.unescape(self.current_question.text)
user_answer = input(f"Q.{self.question_number}: {q_text} (True/False): ")
age: int
# we have specified that age is of type int, now wherever i use age, it should
be of type int, eg
# def age_check(age):
# if age > 18:
# print("legal")
# else:
# print("not legal")
#
# we can also do this by specifying the type in the fn params:
# we can also set the return type of a function in python, for eg, if the
fn age_check returns string, then here is how we can specify it:
def age_check(age) -> str:
if age > 18:
return "hey"
else:
return "lol"
day 35 last video very important as it shows to type command involving multiple
api env vars in the script that will run to automate the python code
# the strftime method in python is used to format the date time to whatever format
we need, read documentation for this.
today = datetime.now()
formatted_date = today.strftime("%Y%m%d")
beautifulsoup is a parser for html and xml files, that is used for web scraping -
basically pulling data from websites.
lxmi parser is also a type of parser that is used with beautifulsoup. Read
documentation
just like we select the classes and subclass element in css like p a {}
we can target any element deep down like this only.
print(soup.select_one(selector="p a"))
a little filter url method which filters the data based on the query q
{% for topic in topics %}
<div>
<a href="{% url 'home' %}?q={{topic.name}}"> {{topic.name}}</a>
</div>
{% endfor %}
</div>
we will take the value of q from the request in the views part and we will use
that value to filter the data
q = request.GET.get("q")
rooms = Room.objects.filter(topic__name=q)
topic refers to the ForeignKey field in the Room model that links each room to a
specific topic.
name refers to the name field of the related Topic model, which represents the name
of the topic.
By using (topic__name=q), you are filtering the Room objects based on the name of
the topic associated with each room, where the topic's name matches the value of q
provided in the GET request.
So, if you want to retrieve all rooms, including those where topic__name is empty
or null, using .filter(topic__name__icontains=q) with an empty q value is a
suitable approach. It will include all rooms without any filtering based on the
topic name.
<a href="/">
<h1>Logo</h1>
</a>
<form method="GET" action="{% url 'home' %}">
<input type="text" name="q" />
</form>
<hr>
<input type="text" name="q" /> is an HTML input field of type "text." It's used to
allow users to input text. The name attribute is set to "q," which is the name of
the query parameter that will be included in the URL when the form is submitted.
Users can enter their search query in this text field.
When a user enters a search query and submits the form, the data will be sent to
the 'home' view as a query parameter. The 'home' view can then retrieve this query
parameter using request.GET.get("q") and use it to filter the list of rooms based
on the search query, as shown in your initial code.
If you want to use len() to get the count of objects in a queryset, you can convert
the queryset to a list and then use len() on the list. However, this approach is
less efficient than using .count() because it retrieves all the objects from the
database, which can be resource-intensive, especially for large querysets. Here's
how you can use len() with a queryset:
room_count = len(list(rooms))
In Django, when working with querysets, you should use the .count() method to get
the count of objects that match the query criteria. While Python's built-in len()
function can work with lists and other iterable objects, it doesn't provide an
efficient way to count objects in a queryset. Using .count() is more efficient
because it generates a SQL query that retrieves the count directly from the
database, whereas len() would fetch all the objects in the queryset and then count
them in Python.
So, it's recommended to use .count() when you want to get the count of objects in a
queryset. Here's the preferred way:
python
Copy code
room_count = rooms.count()
{% if request.user.is_authenticated %}
<a href="">Logout</a>
{% else %}
<a href="{% url 'login' %}">Login</a>
{% endif %}
from bs4 import BeautifulSoup
import lxml
The __main__ part is a common Python construct used to determine if the Python
script is being run directly or if it is being imported as a module into another
script. Here's how it works:
python
Copy code
if __name__ == '__main__':
# Code here will only run if the script is executed directly, not imported
app.run(debug=True)
Explanation:
__name__:
This line runs the Flask development server if the script is the main entry point.
The debug=True parameter enables debug mode, which provides additional information
and automatic reloading of the server when code changes are detected. In a
production environment, you would typically set debug=False.
Putting it all together, when you run a Python script, like the one with
app.run(debug=True), the script is considered the main entry point. The if __name__
== '__main__': block ensures that the development server is started only when the
script is run directly, not when it's imported as a module into another script.
This is a common practice to make the code reusable in different contexts.
#nesting of functions
def outer_function():
print("I am outer function")
def inner_function():
print("I am inner function")
inner_fn = outer_function()
inner_fn()
a decorator function is a function that wraps another function and gives that
function some functionality such as modifying the function and more.
import time
def delay_decorator(function):
def wrapper():
time.sleep(2)
function()
return wrapper
say_hello()
or instead of @decorator function:
wrapper = delay_decorator(say_hello)
wrapper()
import time
current_time = time.time()
print(current_time) # seconds since Jan 1st, 1970
def speed_calc_decorator(function):
def wrapper_function():
start_time = time.time()
function()
end_time = time.time()
print(f"function {function.__name__} executed in {end_time-start_time}")
return wrapper_function
@speed_calc_decorator
def fast_function():
for i in range(1000000):
i * i
@speed_calc_decorator
def slow_function():
for i in range(10000000):
i * i
fast_function()
slow_function()
render_template is also imported from flask along with Flask as it allows for
rendering the html templates into the browser
for flask, since it is a framework not a library it has its own set of rules:
all the html files go inside the template folder and all the static files(images
etc) go inside the static folder.
export FLASK_SECRET_KEY ='' # this is how you add a secret key to environment
sample_emails = [
['[email protected]', '[email protected]'],
['[email protected]', '[email protected]'],
['[email protected]', '[email protected]'],
['[email protected]', '[email protected]'],
]
In Python, the ** operator is used to unpack dictionaries. In the code snippet you
provided, **payload is used as an argument to the function create_user(). This
means that the contents of the dictionary payload are unpacked and passed to the
function create_user() as individual keyword arguments.