Docsity
Docsity

Prepare for your exams
Prepare for your exams

Study with the several resources on Docsity


Earn points to download
Earn points to download

Earn points by helping other students or get them with a premium plan


Guidelines and tips
Guidelines and tips

It provides you all commands, Cheat Sheet of Artificial Intelligence

Very helpful for all to learn instantly

Typology: Cheat Sheet

2023/2024

Uploaded on 03/03/2024

parshav-singla
parshav-singla ๐Ÿ‡ฎ๐Ÿ‡ณ

2 documents

1 / 7

Toggle sidebar

This page cannot be seen from the preview

Don't miss anything!

bg1
#[Python Basics ] [ cheatsheet ]
1. Basic Syntax and Operations
โ—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: ")
2. Data Structures
โ—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)
3. Control Flow
โ—If Statement: if condition:
By: Waleed Mousa
pf3
pf4
pf5

Partial preview of the text

Download It provides you all commands and more Cheat Sheet Artificial Intelligence in PDF only on Docsity!

# [ Python Basics ] [ cheatsheet ]

1. Basic Syntax and Operations

โ— 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: ")

2. Data Structures

โ— 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)

3. Control Flow

โ— 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}

4. Functions and Modules

โ— 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

5. Error Handling

โ— 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")

6. File Handling

โ— 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:

10. Date and Time

โ— 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)

11. File Paths and Directories

โ— 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')

12. Environment and System

โ— 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'])

13. Networking

โ— 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))

14. Debugging and Profiling

โ— Print Debugging: print("Debug: ", variable) โ— Using pdb: import pdb; pdb.set_trace() โ— Profiling Python Code: import cProfile; cProfile.run('function()')

15. Testing

โ— 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)

16. Virtual Environments

โ— 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

17. Packaging and Distribution

โ— 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

18. Advanced String Formatting

โ— Formatted String Literals (f-strings): name = "World"; f"Hello, {name}!" โ— String Format Method: "{0}, {1}".format('Hello', 'World') โ— Percent (%) Formatting: "%s, %s" % ('Hello', 'World')

19. Comprehensions Beyond Lists

โ— 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)]}

20. Itertools and More Functional Tools

โ— Itertools for Combining Data: import itertools; itertools.chain([1, 2], [3, 4]) โ— Functional Programming Tools: map , filter , functools.reduce

21. Lambda Functions

โ— 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.

27. Regular Expressions

โ— 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')

28. Data Serialization

โ— 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)

29. Multithreading and Multiprocessing

โ— 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()

30. Asynchronous Programming

โ— 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