0% found this document useful (0 votes)
29 views3 pages

Complete Python Syntax Reference

This document is a Python reference guide that lists various core functions, syntax, and their explanations along with examples and outputs. It covers topics such as data types, control structures, error handling, threading, and modules. The guide serves as a quick reference for Python programming concepts and functionalities.

Uploaded by

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

Complete Python Syntax Reference

This document is a Python reference guide that lists various core functions, syntax, and their explanations along with examples and outputs. It covers topics such as data types, control structures, error handling, threading, and modules. The guide serves as a quick reference for Python programming concepts and functionalities.

Uploaded by

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

Python Reference Guide

Package/Category Function/Syntax Detailed Explanation Example Output


Python Core print() Prints output to the console print('Hello World') Hello World
Python Core input() Takes input from the user name = input('Enter name: ') User types a value
Python Core len() Returns length of a sequence len([1,2,3]) 3
Python Core type() Returns the type of an object type(5) <class 'int'>
Python Core range() Generates a range of numbers list(range(0,5)) [0,1,2,3,4]
Python Core list.append() Add an item to a list lst = [1,2]; lst.append(3); lst [1,2,3]
Python Core list.extend() Extend list with another list lst = [1,2]; lst.extend([3,4]); lst [1,2,3,4]

Python Core list.pop() Remove and return item at index lst = [1,2,3]; lst.pop() 3
Python Core dict.get() Get value for a key safely d={'a':1}; d.get('a') 1
Python Core dict.items() Return list of key-value pairs d={'a':1,'b':2}; list(d.items()) [('a',1),('b',2)]
Python Core set.add() Add element to a set s={1,2}; s.add(3); s {1,2,3}
Python Core set.union() Return union of two sets {1,2}.union({2,3}) {1,2,3}
Python Core for loop Iterate over items in sequence for i in [1,2,3]: print(i) Prints 1,2,3
Python Core list comprehension Concise way to create lists [x*2 for x in range(3)] [0,2,4]
Python Core def Define a function def add(a,b): return a+b; add(2,3) 5

Python Core *args, **kwargs Pass variable number of arguments def f(*a, **k): print(a,k); f(1,2,x=3) (1,2) {'x':3}
Python Core class Define a class class Dog: pass; d=Dog(); type(d) <class '__main__.Dog'>
class C: def __init__(self,x): self.x=x;
Python Core __init__ Constructor method c=C(5); c.x 5
class C: @property def x(self): return
Python Core @property Define getter like attribute 42; C().x 42

try: 1/0
Python Core try/except Handle exceptions except ZeroDivisionError: print('error') error
Python Core raise Raise an exception raise ValueError('bad') ValueError: bad
f=open('file.txt','w'); f.write('hi');
Python Core open() Open a file f.close() Writes 'hi'

Python Core with open() Context manager for file with open('file.txt') as f: data=f.read() Reads file content
Python Core lambda Create anonymous function f=lambda x:x**2; f(3) 9
Python Core map() Apply function to sequence list(map(lambda x:x*2,[1,2,3])) [2,4,6]
Python Core filter() Filter sequence by function list(filter(lambda x:x>1,[1,2,3])) [2,3]
Package/Category Function/Syntax Detailed Explanation Example Output
Python Core zip() Combine sequences list(zip([1,2],[3,4])) [(1,3),(2,4)]
Python Core enumerate() Get index and value list(enumerate(['a','b'])) [(0,'a'),(1,'b')]
Python Core import math Import math module import math; math.sqrt(9) 3
import datetime;
Python Core datetime.datetime.now() Get current date and time datetime.datetime.now() Current datetime
Python Core os.listdir() List files in directory import os; os.listdir('.') ['file1','file2']
Python Core sys.argv Command line arguments import sys; print(sys.argv) List of arguments
def deco(f):
def w(): print('start'); f(); print('end');
return w
@deco
def hi(): print('hi')
Python Core decorator Modify function behavior hi() start hi end

Python Core generator Yield values lazily def gen(): yield 1; yield 2; list(gen()) [1,2]
Python Core yield from Delegate part of generator def g(): yield from [1,2,3]; list(g()) [1,2,3]
import asyncio
async def main(): return 42
Python Core async/await Async functions asyncio.run(main()) 42
import threading;
Threading import threading Import threading module print(threading.active_count()) Prints number of active threads
import threading; def worker():
print('Working');
t=threading.Thread(target=worker);
Threading threading.Thread Create and run a new thread t.start(); t.join() Working

lock = threading.Lock(); lock.acquire();


Threading threading.Lock Synchronization primitive for threads # critical section; lock.release() Controls access to shared resources

import asyncio; async def main():


Async async def Define an asynchronous function return 42; print(asyncio.run(main())) 42
async def say_hi(): await
Async await Wait for an async task asyncio.sleep(1); print('hi') Prints 'hi' after delay
Modules import Import a module import math; print(math.sqrt(16)) 4
Package/Category Function/Syntax Detailed Explanation Example Output

Modules from import Import specific function/class from math import sqrt; print(sqrt(9)) 3

Modules dir() List attributes/methods in module import math; print(dir(math)[:5]) Shows list of attributes

try: x=1/0
Handle errors and execute final except ZeroDivisionError: print('Error') Error
Error Handling try/except/finally block finally: print('Done') Done
Error Handling raise Exception Raise a custom exception raise ValueError('Invalid value') ValueError: Invalid value

Error Handling assert Trigger error if condition false assert 2>1 No output if true, AssertionError if false
import unittest
class T(unittest.TestCase):
def test_add(self):
Testing unittest Unit testing framework self.assertEqual(1+1,2) Test case created
Testing pytest Popular testing framework # in terminal: pytest test_file.py Runs all tests
Testing doctest Test by examples in docstrings import doctest; doctest.testmod() Runs examples in docstrings

You might also like