You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
num=int(input("Enter an integer"))
print("hello"*num)
result=eval(input("Enter an expression: ")) #if inputs 2 * 3 =, this outputs 6print(result)
Errors and Excpetions
Syntax errors: occur when Python can’t interpret our code, since we didn’t follow the correct syntax for Python
Exceptions: occur when unexpected things happen during execution of a program, even if the code is syntactically correct
Handling Errors
try: This is the only mandatory clause in a try statement. The code in this block is the first thing that Python runs in a try statement.
except: If Python runs into an exception while running the try block, it will jump to the except block that handles that exception.
else: If Python runs into no exceptions while running the try block, it will run the code in this block after running the try block.
finally: Before Python leaves this try statement, it will run the code in this finally block under any conditions, even if it's ending the program. E.g., if Python ran into an error while running code in the except or else block, this finally block will still be executed before stopping the program.
try:
# some codeexceptValueError:
# some codetry:
# some codeexcept (ValueError, KeyboardInterrupt):
# some codetry:
# some codeexceptValueError:
# some codeexceptKeyboardInterrupt:
# some codetry:
# some codeexceptExceptionase:
# some codeprint("Exception occurred: {}".format(e))
f=open('my_path/my_file.txt', 'r')
file_data=f.read()
f.close()
f=open('my_path/my_file.txt', 'w')
f.write("Hello there!")
f.close()
files= []
foriinrange(10000):
files.append(open('some_file.txt', 'r')) #too many open filesprint(i)
withopen('my_path/my_file.txt', 'r') asf:
file_data=f.read()
#We're the knights of the round table#We dance whenever we're ablecamelot_lines= []
withopen("camelot.txt") asf:
forlineinf:
camelot_lines.append(line.strip())
print(camelot_lines)
["We're the knights of the round table", "We dance whenever we're able"]
If you open an existing file in writing mode, any content that it had contained previously will be deleted. If you're interested in adding to an existing file, without deleting its content, you should use the append ('a') mode instead of write.
The with keyword allows you to open a file, do operations on it, and automatically close it after the indented code is executed, in this case, reading from the file
To avoid running executable statements in a script when it's imported as a module in another script, include these lines in an if __name__ == "__main__" block. Or alternatively, include them in a function called main() and call this in the if main block.
csv: very convenient for reading and writing csv files
collections: useful extensions of the usual data types including OrderedDict, defaultdict and namedtuple
random: generates pseudo-random numbers, shuffles sequences randomly and chooses random items
string: more functions on strings. This module also contains useful collections of letters like string.digits (a string containing all characters which are valid digits).
re: pattern-matching in strings via regular expressions
math: some standard mathematical functions
os: interacting with operating systems
os.path: submodule of os for manipulating path names
sys: work directly with the Python interpreter
json: good for reading and writing json files (good for web work)
Techniques for Importing Modules
frommodule_nameimportobject_namefrommodule_nameimportfirst_object, second_objectimportmodule_nameasnew_namefrommodule_nameimportobject_nameasnew_namefrommodule_nameimport*#do not do thisimportmodule_name#do thisimportpackage_name.submodule_name
Third-Party Libraries
To install a package using pip, just enter "pip install" followed by the name of the package in your command line like this: pip install package_name
Using a requirements.txt File
pip install -r requirements.txt
Larger Python programs might depend on dozens of third party packages. To make it easier to share these programs, programmers often list a project's dependencies in a file called requirements.txt
Useful Third-Party Packages
IPython - A better interactive Python interpreter
requests - Provides easy to use methods to make web requests. Useful for accessing web APIs.
Flask - a lightweight framework for making web applications and APIs.
Django - A more featureful framework for making web applications. Django is particularly good for designing complex, content heavy, web applications.
Beautiful Soup - Used to parse HTML and extract information from it. Great for web scraping.
pytest - extends Python's builtin assertions and unittest module.
PyYAML - For reading and writing YAML files.
NumPy - The fundamental package for scientific computing with Python. It contains among other things a powerful N-dimensional array object and useful linear algebra capabilities.
pandas - A library containing high-performance, data structures and data analysis tools. In particular, pandas provides dataframes!
matplotlib - a 2D plotting library which produces publication quality figures in a variety of hardcopy formats and interactive environments.
ggplot - Another 2D plotting library, based on R's ggplot2 library.
Pillow - The Python Imaging Library adds image processing capabilities to your Python interpreter.
pyglet - A cross-platform application framework intended for game development.
Pygame - A set of Python modules designed for writing games.
The Python Tutorial - This section of the official documentation surveys Python's syntax and standard library
The Python Language and Library References - The Language Reference and Library Reference are more technical than the tutorial, but they are the definitive sources of truth.
Third-Party Library Documentation - Third-party libraries publish their documentation on their own websites, and often times at https://readthedocs.org/.
The websites and blogs of prominent experts - The previous resources are primary sources, meaning that they are documentation from the same people who wrote the code being documented.
StackOverflow - This is a good place to find out more about your question or discover alternative search terms
Bug Trackers - Sometimes you'll encounter a problem so rare, or so new, that no one has addressed it on StackOverflow.
Random Web Forums - Sometimes your search yields references to forums that haven't been active since 2004, or some similarly ancient time.