0% found this document useful (0 votes)
4 views2 pages

Coding Cheat Sheety

The document provides an overview of basic programming concepts including data types, control structures, functions, and error handling in Python. It covers topics such as iteration with loops, defining functions with and without return values, and handling exceptions. Additionally, it discusses data structures like lists, tuples, sets, and dictionaries, along with file operations and class definitions.

Uploaded by

calvinshank38
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)
4 views2 pages

Coding Cheat Sheety

The document provides an overview of basic programming concepts including data types, control structures, functions, and error handling in Python. It covers topics such as iteration with loops, defining functions with and without return values, and handling exceptions. Additionally, it discusses data structures like lists, tuples, sets, and dictionaries, along with file operations and class definitions.

Uploaded by

calvinshank38
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/ 2

x = 10 # Integer # I t e r a t i n g with range # F u n c t i o n with return

x = 3.14 # Float for i in range (3) : def square ( x ) :


x = " Hello " # String print ( i ) return x ** 2
x = True # Boolean # I t e r a t i n g through a list print ( square (4) ) # Output : 16
colors = [ " red " , " green " , " blue " ] # F u n c t i o n without return
for color in colors : def d is pl a y_ me ss a ge () :
print ( color ) print ( " Hello ! " )
age = 25 # int # I t e r a t i n g through a string result = d is pl ay _ me ss a ge () # Prints " Hello !" but result is
pi = 3.14159 # float for char in " Python " : None
name = " Aiden " # str print ( char ) print ( result ) # Output : None
is_student = True # bool

count = 0 # Lambda f u n c t i o n
# Input example while count < 3: square = lambda x : x ** 2
name = input (" Enter your name : ") print ( count ) print ( square (5) ) # Output : 25
print ( f " Hello , { name }!") count += 1 # Lambda in built - in f u n c t i o n s
# Input as a number nums = [1 , 2 , 3 , 4]
age = int ( input (" Enter your age : ") ) # Convert input to int squared_nums = list ( map ( lambda x : x ** 2 , nums ) )
print ( f " You will be { age + 1} next year .") print ( squared_nums ) # Output : [1 , 4 , 9 , 16]

• break: Exits the loop immediately.

try :
# Correct indentation • continue: Skips the rest of the loop iteration.
# Code that may raise an e x c e p t i o n
if True :
except ExceptionType :
print (" This is indented .")
# Incorrect indentation ( will cause an error ) • pass: Does nothing; placeholder. # Code to handle the e x c e p t i o n
else :
# if True :
# E x e c u t e s if no e x c e p t i o n occurs
# print (" This is not indented correctly .")
finally :
# E x e c u t e s r e g a r d l e s s of whether an e x c e p t i o n occurs
# break example
for i in range (5) :
x = 10 if i == 3:
y = 3 break
try :
print ( x + y ) # 13 print ( i )
result = 10 / 0
print ( x - y) # 7 # c o n t i n u e example
except Z e r o D i v i s i o n E r r o r :
print ( x * y ) # 30 for i in range (5) :
print ( " Cannot divide by zero ! " )
print ( x / y ) # 3.333... if i == 3:
print ( x // y ) # 3 continue
print ( x % y) # 1 print ( i )
print ( x ** y ) # 1000 # pass example
try :
for i in range (5) :
x = int ( " abc " ) # Will raise V a l u e E r r o r
if i == 3:
result = 10 / 0
pass
except Z e r o D i v i s i o n E r r o r :
print ( i )
• /: Division (returns a float) print ( " Cannot divide by zero ! " )
except ValueError :
print ( " Invalid input ! " )
• //: Floor division (discards remainder)
def function_name ( parameters ) :
• %: Modulus (remainder after division) # F u n c t i o n body
return output def check_p ositive ( num ) :
• **: Exponentiation if num < 0:
raise ValueError ( " Number must be positive ! " )
return num
def greet ( name ) : try :
return f " Hello , { name }! " print ( check _positiv e ( -5) )
a , b = 10 , 3 except ValueError as e :
print ( greet ( " Aiden " ) ) # Output : Hello , Aiden !
print ( a + b ) # 13 ( A d d i t i o n ) print ( e ) # Output : Number must be positive !
print ( a - b ) # 7 ( Subtraction )
print ( a * b ) # 30 ( M u l t i p l i c a t i o n ) Positional Arguments:
print ( a / b ) # 3.333... ( Division )
print ( a // b ) # 3 ( Floor D i v i s i o n ) try :
print ( a % b ) # 1 ( Modulus ) def greet ( fname , lname ) :
age = int ( input ( " Enter your age : " ) )
print ( a ** b ) # 1000 ( E x p o n e n t i a t i o n ) print ( f " Hello , { fname } { lname }! " )
except ValueError :
print ( " Please enter a valid number ! " )
greet ( " John " , " Doe " ) # Hello , John Doe !
else :
print ( " Your age is : " , age )
x , y = 10 , 20
Default Arguments:
print ( x > 5 and y < 30) # True
print ( x > 15 or y < 30) # True
print ( not ( x > 5) ) # False def greet ( fname , lname = " Smith " ) : try :
print ( f " Hello , { fname } { lname }! " ) # Code that may raise an e x c e p t i o n
except ExceptionType :
greet ( " John " ) # Hello , John Smith ! # Code to handle the e x c e p t i o n
a , b = 15 , 10 else :
print ( a == b ) # False # E x e c u t e s if no e x c e p t i o n occurs
print ( a != b ) # True Keyword Arguments: finally :
print ( a > b ) # True # E x e c u t e s r e g a r d l e s s of whether an e x c e p t i o n occurs
print ( a <= b ) # False def greet ( fname , lname ) :
print ( f " Hello , { fname } { lname }! " ) Basic try-except Block:
greet ( lname = " Doe " , fname = " John " ) # Hello , John Doe !
a , b , c = 10 , 20 , 30 try :
# Combine a r i t h m e t i c and c o m p a r i s o n result = 10 / 0
print (( a + b ) > c ) # False Variable-Length Arguments: except Z e r o D i v i s i o n E r r o r :
# Combine c o m p a r i s o n and logical print ( " Cannot divide by zero ! " )
print (( a < b ) and ( b < c ) ) # True
def add_numbers (* args ) :
# Combine all three
return sum ( args ) Handling Multiple Exceptions:
print (( a + b == c ) or ( c % b == 0) ) # True
print ( add_numbers (1 , 2 , 3) ) # 6
try :
x = int ( " abc " ) # Will raise V a l u e E r r o r
result = 5 + 3 * 2 > 10 and not (4 % 2 != 0) Variable-Length Keyword Arguments: result = 10 / 0
# Step - by - step e v a l u a t i o n : except Z e r o D i v i s i o n E r r o r :
# 5 + 6 > 10 and not (0 != 0) print ( " Cannot divide by zero ! " )
# 11 > 10 and not False def print_details (** kwargs ) : except ValueError :
# True and True for k , v in kwargs . items () : print ( " Invalid input ! " )
# True print ( f " { k }: { v } " )
print ( result ) # True
print_details ( name = " John " , age =30)
# name : John def check_p ositive ( num ) :
# age : 30 if num < 0:
x = 10 raise ValueError ( " Number must be positive ! " )
if x > 5: return num
print ( " Greater than 5 " ) try :
if x % 2 == 0: # Positional arguments print ( check _positiv e ( -5) )
print ( " Even number " ) def add (a , b ) : except ValueError as e :
else : return a + b print ( e ) # Output : Number must be positive !
print ( " Odd number " ) print ( add (5 , 3) ) # Output : 8
grade = 85 # Default a r g u m e n t s
if grade >= 90: def power ( base , exponent =2) :
print ( " A " ) return base ** exponent • Lists: Ordered, mutable collections.
elif grade >= 80: print ( power (3) ) # Output : 9
print ( " B " ) print ( power (3 , 3) ) # Output : 27 • Tuples: Immutable ordered collections.
else : # Keyword a r g u m e n t s
print ( " C or lower " ) print ( power ( exponent =3 , base =2) ) # Output : 8
# Variable - length a r g u m e n t s • Sets: Unordered collections of unique items.
def multiply (* args ) :
result = 1 • Dictionaries: Key-value mappings for efficient re-
for num in args : trieval.
• for: Iterates over sequences like list, range, or str. result *= num
return result
• while: Repeats while a condition is True. print ( multiply (2 , 3 , 4) ) # Output : 24 • append(item): Add an item to the end.

• remove(item): Remove the first occurrence of an item.


• sort(): Sort the list in ascending order. • .writelines(iterable): Writes a list of strings.
class Animal :
def __init__ ( self , name ) :
self . name = name
my_list = [1 , 2 , 3] dog = Animal ( " Dog " )
with open ( " example . txt " , " w " ) as file :
my_list . append (4) # [1 , 2 , 3 , 4] print ( dog . name ) # Output : Dog
file . write ( " First line \ n " )
my_list . remove (2) # [1 , 3 , 4] file . write ( " Second line \ n " )
my_list . sort () # [1 , 3 , 4]

class Animal :
def speak ( self ) :
with open ( " example . txt " , " w " ) as file : return " I make a sound "
• count(item): Count occurrences of an item. file . write ( " Automatic closure example . " ) class Dog ( Animal ) :
def speak ( self ) :
• index(item): Find the first index of an item. return " Woof ! "
dog = Dog ()
• .seek(offset, whence): Move pointer. print ( dog . speak () ) # Output : Woof !

my_tuple = (4 , 5 , 6)
print ( my_tuple . count (5) ) # 1 • .tell(): Get current position.
print ( my_tuple . index (6) ) # 2 class Dog :
def speak ( self ) :
return " Woof ! "
with open ( " example . txt " , " r " ) as file : class Cat :
• add(item): Add an item. print ( file . read (5) ) def speak ( self ) :
print ( file . tell () ) return " Meow ! "
file . seek (0)
• discard(item): Remove an item (no error if not present). animals = [ Dog () , Cat () ]
print ( file . read () ) for animal in animals :
print ( animal . speak () ) # Output : Woof ! Meow !
• union(other): Combine sets.

• Count Words in a File:


my_set = {1 , 2 , 3} class BankAccount :
my_set . add (4) # {1 , 2 , 3 , 4} def __init__ ( self , balance ) :
with open ( " example . txt " , " r " ) as file :
other_set = {3 , 4 , 5} self . __balance = balance # Private a t t r i b u t e
content = file . read ()
print ( my_set . union ( other_set ) ) # {1 , 2 , 3 , 4 , 5} def deposit ( self , amount ) :
words = content . split ()
self . __balance += amount
print ( " Word count : " , len ( words ) )
def get_balance ( self ) :
return self . __balance
account = BankAccount (100)
• keys(): Get all keys.
account . deposit (50)
• Copy File Content: print ( account . get_balance () ) # Output : 150
• values(): Get all values.
with open ( " source . txt " , " r " ) as src , open ( " dest . txt
• items(): Get all key-value pairs. " , " w " ) as dest :
dest . write ( src . read () ) • Iterators: Objects implementing iter () and next ()
methods.

my_dict = { " a " : 1 , " b " : 2}


• Generators: Special iterators created with functions
print ( my_dict . keys () ) # d i c t _ k e y s ([ ’ a ’, ’b ’])
using the yield keyword.
print ( my_dict . values () ) # d i c t _ v a l u e s ([1 , 2])
my_dict . pop ( " b " ) # Removes " b ": 2 import math
print ( my_dict ) # { ’ a ’: 1} print ( math . sqrt (16) )
from math import sqrt
print ( sqrt (25) ) class Counter :
import random as rnd def __init__ ( self , low , high ) :
print ( rnd . randint (1 , 10) ) self . current = low
• lower(): Converts all characters to lowercase.
self . high = high
def __iter__ ( self ) :
• upper(): Converts all characters to uppercase. return self
import math def __next__ ( self ) :
• capitalize(): Capitalizes the first character. print ( math . pi ) if self . current > self . high :
print ( math . ceil (4.2) ) raise StopIteration
else :
value = self . current
s = " Hello , World ! " self . current += 1
print ( s . lower () ) # hello , world ! return value
# m y _ m o d u l e . py
print ( s . upper () ) # HELLO , WORLD ! counter = Counter (1 , 5)
def greet ( name ) :
print ( s . capitalize () ) # Hello , world ! for num in counter :
return f " Hello , { name }! "
print ( num )
# Main file
Syntax: string[start:end:step] import my_module
print ( my_module . greet ( " Aiden " ) )
s = " Hello , World ! " def count () :
print ( s [7:12]) # " World " yield 1
print ( s [:: -1]) # "! dlroW , olleH " ( r e v e r s e d ) yield 2
• Random Integers: random.randint(a, b) generates a ran- yield 3
dom integer between a and b. for num in count () :
print ( num )
• f-strings: Introduced in Python 3.6. • Random Floats: random.uniform(a, b) generates a ran-
dom float between a and b.
• format(): Uses placeholders.
squares = ( x **2 for x in range (5) )
• Random Choices: random.choice(sequence) selects a ran- for square in squares :
dom element from a sequence. print ( square )
name = " Aiden "
print ( f " My name is { name }. " )
import random
Use open() to open a file: print ( random . randint (1 , 10) ) # Random integer
print ( random . uniform (1.5 , 5.5) ) # Random float
• Modes: colors = [ " red " , " blue " , " green " ]
print ( random . choice ( colors ) ) # Random color

– "r": Read (default).


– "w": Write (overwrites file).
• random.shuffle(sequence): Shuffles a sequence in place.
– "a": Append (adds to existing content).
– "x": Create a file (fails if file exists). • random.sample(sequence, k): Selects k unique elements.
– "b": Binary mode.
– "t": Text mode (default).
nums = [1 , 2 , 3 , 4 , 5]
random . shuffle ( nums )
print ( nums )
file = open ( " example . txt " , " w " )
sample = random . sample ( nums , 3)
file . write ( " Hello , file ! " )
print ( sample )
file . close ()

• .read(): Reads entire content. • Simulating Dice Rolls:

• .readline(): Reads one line at a time. rolls = [ random . randint (1 , 6) for _ in range (5) ]
print ( " Dice rolls : " , rolls )
• .readlines(): Reads all lines into a list.

• Random Password Generator:


with open ( " example . txt " , " r " ) as file :
content = file . read () import string
print ( content ) password = ’ ’. join ( random . choices ( string .
ascii_letters + string . digits , k =12) )
print ( password )

• .write(content): Writes a string.

You might also like