0% found this document useful (0 votes)
6 views

Python Notes

Notes of python tips collected over time

Uploaded by

xasihen391
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
6 views

Python Notes

Notes of python tips collected over time

Uploaded by

xasihen391
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 10

https://peps.python.

org/pep-0008/

1. Basic PEP8 Style Guide

def _internal_func():

return 42
The underscore prefix is meant as a hint to another programmer that a
variable or method starting with a single underscore is intended for internal
use. This convention is defined in PEP 8. This isn't enforced by Python.
Python does not have strong distinctions between “private” and “public”
variables like Java does.

https://dbader.org/blog/meaning-of-underscores-in-python

2. Getting help in the Python Interpreter

 To find out what attributes a type has:


1. dir(str)

2. dir(list)

3. dir(dict)

 To find out what Python builtin functions there are:


1. dir(__builtins__)

 Documentation for a Python command can be found with:


1. help(str)

2. help(str.replace)

3. help(dict.values)

3. Inputs

 A Python program can get user input via the input function:

 The input function halts the execution of the program and gets text
input from the user:
1. name = input("Enter your name: ")

 The input function converts any input to a string, but you can
convert it back to int or float:
1. experience_months = input("Enter your experience in months: ")

2. experience_years = int(experience_months) / 12

4. String Formatting
 You can format strings with (works both on Python 2 and 3):
1. name = "Sim"

2. experience_years = 1.5

3. print("Hi %s, you have %s years of experience." % (name, experience_years))

Output: Hi Sim, you have 1.5 years of experience.

 You can also format strings with (Python 3 only):


1. name = "Sim"

2. experience_years = 1.5

3. print("Hi {}, you have {} years of experience".format(name, experience_years))

Output: Hi Sim, you have 1.5 years of experience.

5. Loops

 For loops are useful for executing a command over a large number
of items.

 You can create a for loop like so:


1. for letter in 'abc':

2. print(letter.upper())

Output:

A
B
C

 The name after for (e.g. letter ) is just a variable name

 You can loop over dictionary keys:


1. phone_numbers = {"John Smith":"+37682929928","Marry Simpons":"+423998200919"}

2. for value in phone_numbers.keys():


3. print(value)

Output:

John Smith
Marry Simpsons

 You can loop over dictionary values:


1. phone_numbers = {"John Smith":"+37682929928","Marry Simpons":"+423998200919"}

2. for value in phone_numbers.values():

3. print(value)

Output:

+37682929928
+423998200919

 You can loop over dictionary items:


1. phone_numbers = {"John Smith":"+37682929928","Marry Simpons":"+423998200919"}

2. for key, value in phone_numbers.items():

3. print(key, value)

Output:

('John Smith', '+37682929928')

('Marry Simpons', '+423998200919')

 While loops will run as long as a condition is true:


1. while datetime.datetime.now() < datetime.datetime(2090, 8, 20, 19, 30, 20):

2. print("It's not yet 19:30:20 of 2090.8.20")

The loop above will print out the string inside print() over and over
again until the 20th of August, 2090.

6. List Comprehensions
 A list comprehension is an expression that creates a list by iterating
over another container.
 A basic list comprehension:
1. [i*2 for i in [1, 5, 10]]

Output: [2, 10, 20]

 List comprehension with if condition:


1. [i*2 for i in [1, -2, 10] if i>0]

Output: [2, 20]

 List comprehension with an if and else condition:


1. [i*2 if i>0 else 0 for i in [1, -2, 10]]

Output: [2, 0, 20]

7. Functions

 Functions can have more than one parameter:


1. def volume(a, b, c):
2. return a * b * c

 Functions can have default parameters (e.g. coefficient ):

1. def converter(feet, coefficient = 3.2808):


2. meters = feet / coefficient
3. return meters
4.
5. print(converter(10))

Output: 3.0480370641306997

Arguments can be passed as non-keyword (positional) arguments


(e.g. a ) or keyword arguments (e.g. b=2 and c=10 ):

1. def volume(a, b, c):


2. return a * b * c
3.
4. print(volume(1, b=2, c=10))

 An *args parameter allows the function to be called with an arbitrary


number of non-keyword arguments:
1. def find_max(*args):
2. return max(args)
3. print(find_max(3, 99, 1001, 2, 8))

Output: 1001

 An **kwargs parameter allows the function to be called with an


arbitrary number of keyword arguments:
1. def find_winner(**kwargs):
2. return max(kwargs, key = kwargs.get)
3.
4. print(find_winner(Andy = 17, Marry = 19, Sim = 45, Kae = 34))

Output: Sim

 Here's a summary of function elements:

8. File Processing

 You can read an existing file with Python:


1. with open("file.txt") as file:
2. content = file.read()
 You can create a new file with Python and write some text on it:
1. with open("file.txt", "w") as file:
2. content = file.write("Sample text")

 You can append text to an existing file without overwriting it:


1. with open("file.txt", "a") as file:
2. content = file.write("More sample text")

 You can both append and read a file with:


1. with open("file.txt", "a+") as file:
2. content = file.write("Even more sample text")
3. file.seek(0)
4. content = file.read()

9. Modules/Libraries

 Builtin objects are all objects that are written inside the Python
interpreter in C language.

 Builtin modules contain builtins objects.

 Some builtin objects are not immediately available in the global


namespace. They are parts of a builtin module. To use those objects
the module needs to be imported first. E.g.:
1. import time
2. time.sleep(5)
 A list of all builtin modules can be printed out with:
1. import sys
2. sys.builtin_module_names
 Standard libraries is a jargon that includes both builtin modules
written in C and also modules written in Python.

 Standard libraries written in Python reside in the Python installation


directory as .py files. You can find their directory path
with sys.prefix .

 Packages are a collection of .py modules.

 Third-party libraries are packages or modules written by third-party


persons (not the Python core development team).

 Third-party libraries can be installed from the terminal/command


line:
Windows:

pip install pandas or use python -m pip install pandas if that


doesn't work.

 Mac and Linux:

pip3 install pandas or use python3 -m pip install pandas if that


doesn't work.

10. Decorators in python

https://www.datacamp.com/tutorial/decorators-python
https://www.freecodecamp.org/news/python-decorators-explained-with-
examples/

11. Exception decorator

https://www.google.com/url?
sa=t&rct=j&q=&esrc=s&source=web&cd=&cad=rja&uact=8&ved=2ahUK
EwjG9rfM5ez5AhX9SUEAHbErCqUQtwJ6BAg2EAI&url=https%3A%2F
%2Fwww.youtube.com%2Fwatch%3Fv
%3DZsvftkbbrR0&usg=AOvVaw0eAcqAY-cEp7xu23J0-owa

12. Logging decorator

13. Retry decorator

https://medium.com/analytics-vidhya/retry-decorator-in-python-
55d0729755c7

14. Installing Libraries

when installing a new library for Python always make sure you install for the
right version e.g.
this will install on the default version - sudo python setup.py
install

this will install on a specific version (alias for latest version


of 3 -

sudo /usr/bin/python3 setup.py install

this will install on a specific version

sudo /usr/bin/python3.4 setup.py install


sudo /usr/bin/python2.7 setup.py install

15. Checking supported python runtime on Heroku


Please see the following link for the current supported runtime for Python
3. Make sure that your runtime.txt file contain that runtime.

https://devcenter.heroku.com/articles/python-runtimes#supported-
python-runtimes

16. Deploying a flask website to Heroku

Steps to deploy a static Flask website to Heroku

1. Create an account on www.heroku.com if you don't have one already.


2. Download and install Heroku Toolbelt from
https://devcenter.heroku.com/articles/heroku-cli
3. Install gunicorn with "pip install gunicorn". Make sure you're using pip from
your virtual environment if you have one.
4. Create a requirement.txt file in the main app directory where the main Python
app file is located. You can create that file by running "pip freeze >
requirements.txt" in the command line. Make sure you're using pip from your
virtual environment if you have one. The requirement.txt file should now contain a
list of Python packages.
5. Create a file named "Procfile" in the main app directory. The file should not
contain any extension. Then type in this line inside: "web: gunicorn script1:app"
where "script1" should be replaced with the name of your Python script and "app"
with the name of the variable holding your Flask app.
6. Create a runtime.txt file in the main app directory and type "python-3.5.1" inside.
If you're using Python 2, you may want to type in "python-2.7.11" instead.
7. Open your computer terminal/command line to point to the directory where the
Python file containing your app code is located.
8. Using the terminal, log in to Heroku with "heroku login"
9. Enter your Heroku email address
10. Enter your Heroku password
11. Create a new Heroku app with "heroku create myawesomeappname"
17. Initialize a local git repository with "git init"
18. Add your local application files to git with "git add ."
19. Tell git your email address with "git config --global user.email
"[email protected]"". Make sure the email address is inside quotes here.
20. Tell git your username (just pick whatever username) with "git config --global
user.name "whateverusername"". The username should be in quotes.
21. Commit the changes with "git commit -m "first commit"". Make sure "first
commit" is inside quotes.
22. Before pushing the changes to Heroku, tell heroku the name of the app you
want to use with "heroku git:remote --app myawesomeappname"
23. Push the changes to Heroku with "git push heroku master"
26. That should do it. Go ahead and open your app with "heroku open".

17. Checking Heroku logs

Troubleshooting
If you deployed your website on Heroku but when you visit the
website on the browser you see an error, you probably did something
wrong during the deployment.

No worries! You can see what you did wrong by looking at the server
logs. You can access the server logs by running the following in your
terminal:

heroku logs

This command will show a series of messages. Carefully read the


logs to understand what went wrong.

Upgrade Pip om macos


pip3 install --upgrade pip

You might also like