



Study with the several resources on Docsity
Earn points by helping other students or get them with a premium plan
Prepare for your exams
Study with the several resources on Docsity
Earn points to download
Earn points by helping other students or get them with a premium plan
Community
Ask the community for help and clear up your study doubts
Discover the best universities in your country according to Docsity users
Free resources
Download our free guides on studying techniques, anxiety management strategies, and thesis advice from Docsity tutors
Very helpful for all to learn instantly
Typology: Cheat Sheet
1 / 7
This page cannot be seen from the preview
Don't miss anything!
โ Print Statements: print("Hello, World!") โ Comments: # This is a single-line comment โ Multi-line Comments: '''This is a multi-line comment''' or """This is also a multi-line comment""" โ Variable Assignment: x = 10 โ Data Types: int , float , str , bool โ Type Checking: type(variable) โ Type Conversion: int("5") , str(20) โ Arithmetic Operations: + , - , ***** , / , // (integer division), % (modulus), ****** (exponentiation) โ Increment/Decrement: x += 1 , x -= 1 โ String Concatenation: 'Hello' + ' ' + 'World' โ String Multiplication: 'Python' * 3 โ Input from User: input("Enter your name: ")
โ List Creation: my_list = [1, 2, 3] โ Append to List: my_list.append(4) โ Insert into List: my_list.insert(1, 'a') โ Remove from List: my_list.remove('a') โ List Slicing: my_list[1:3] โ Sort List: sorted(my_list) , my_list.sort() โ Dictionary Creation: my_dict = {'key': 'value'} โ Access Dictionary Items: my_dict['key'] โ Add/Update Dictionary Item: my_dict['new_key'] = 'new_value' โ Remove Dictionary Item: del my_dict['key'] โ Tuple Creation: my_tuple = (1, 2, 3) โ Set Creation: my_set = {1, 2, 3} โ Add to Set: my_set.add(4) โ Remove from Set: my_set.remove(1)
โ If Statement: if condition:
โ If-Else Statement: if condition: else: โ If-Elif-Else Statement: if condition: elif condition: else: โ For Loop: for item in iterable: โ While Loop: while condition: โ Break: break โ Continue: continue โ Pass: pass โ List Comprehension: [expression for item in list] โ Dictionary Comprehension: {key: value for item in list}
โ Defining a Function: def my_function(): โ Function with Parameters: def my_function(param1, param2): โ Return Statement: return x โ Default Parameter Value: def my_function(param1, param2=5): โ Variable Length Arguments: def my_function(args):* , def my_function(kwargs): โ** Importing a Module: import math โ Importing Specific Functions: from math import sqrt โ Creating a Module: Save your functions in a .py file โ Using Pip: pip install package_name
โ Try-Except: try: except Exception: โ Multiple Except Blocks: try: except TypeError: except ValueError: โ Finally Block: try: except Exception: finally: โ Raise an Error: raise ValueError("A value error occurred")
โ Open a File: file = open('file.txt', 'r') โ Read a File: file.read() โ Write to a File: file = open('file.txt', 'w'); file.write("Hello, World!") โ Append to a File: file = open('file.txt', 'a'); file.write("Hello, again!") โ Close a File: file.close() โ With Statement (Context Manager): with open('file.txt', 'r') as file:
โ Current Date and Time: from datetime import datetime; datetime.now() โ Specific Date: from datetime import date; date(2020, 1, 1) โ Formatting Date and Time: datetime.now().strftime('%Y-%m-%d %H:%M:%S') โ Parsing Date and Time Strings: datetime.strptime('2020-01-01', '%Y-%m-%d') โ Timedelta Objects: from datetime import timedelta; timedelta(days=1)
โ List Files in Directory: import os; os.listdir('path/to/directory') โ Check if File Exists: os.path.exists('file.txt') โ Create a Directory: os.makedirs('new_directory') โ Change Current Working Directory: os.chdir('path/to/directory') โ Path Join: os.path.join('directory', 'file.txt')
โ System Commands: import os; os.system('command') โ Environment Variables: os.environ.get('VARIABLE_NAME') โ Current Working Directory: os.getcwd() โ Executing Shell Commands: import subprocess; subprocess.run(['ls', '-l'])
โ Simple HTTP Requests: import requests; response = requests.get('http://example.com') โ Parsing HTML: from bs4 import BeautifulSoup; soup = BeautifulSoup(response.text, 'html.parser') โ Socket Client: import socket; s = socket.socket(); s.connect(('hostname', port))
โ Print Debugging: print("Debug: ", variable) โ Using pdb: import pdb; pdb.set_trace() โ Profiling Python Code: import cProfile; cProfile.run('function()')
โ Writing Unit Tests: import unittest; class TestMyFunction(unittest.TestCase): โ Running a Test Case: if name == 'main': unittest.main() โ Assertions in Tests: self.assertEqual(function_to_test(input), expected_output)
โ Creating a Virtual Environment: python -m venv myenv โ Activating a Virtual Environment: source myenv/bin/activate (Linux/Mac), myenv\Scripts\activate (Windows) โ Deactivating a Virtual Environment: deactivate
โ Creating a Package: Organize your code in a directory with an init.py file. โ Setup Script: Writing a setup.py for package distribution. โ Installing Your Package: pip install. in your package directory. โ Uploading to PyPI: python setup.py sdist upload
โ Formatted String Literals (f-strings): name = "World"; f"Hello, {name}!" โ String Format Method: "{0}, {1}".format('Hello', 'World') โ Percent (%) Formatting: "%s, %s" % ('Hello', 'World')
โ Set Comprehensions: {x for x in 'hello world' if x not in 'aeiou'} โ Dictionary Comprehensions: {k: v for k, v in [('key1', 1), ('key2', 2)]}
โ Itertools for Combining Data: import itertools; itertools.chain([1, 2], [3, 4]) โ Functional Programming Tools: map , filter , functools.reduce
โ Importing with Alias: import numpy as np; np.array([1, 2, 3]) โ Creating a Package: Create a directory with an init.py file and other module files.
โ Matching Strings: import re; re.match('p', 'python') โ Search Within Strings: re.search('n', 'python') โ Replacing Strings: re.sub('python', 'cython', 'I love python') โ Compiling Patterns: pattern = re.compile('python'); pattern.findall('I love python')
โ JSON Serialization: import json; json.dumps({'name': 'John', 'age': 30}) โ JSON Deserialization: json.loads('{"name": "John", "age": 30}') โ Pickle Serialization: import pickle; pickle.dumps(obj) โ Pickle Deserialization: pickle.loads(pickled_data)
โ Creating Threads: from threading import Thread; t = Thread(target=function_name); t.start() โ Creating Processes: from multiprocessing import Process; p = Process(target=function_name); p.start() โ Joining Threads: t.join() โ Joining Processes: p.join()
โ Basic Coroutine: import asyncio; async def main(): await asyncio.sleep(1); print('done') โ Running Async Code: asyncio.run(main()) โ Async/Await with Functions: async def fetch_data(): data = await some_async_operation(); return data