Basics: Showing Output To User
Basics: Showing Output To User
Basics
Basic syntax from the python programming language
Empty List
my_list = []
Empty Dictionary
my_dict = {}
Range Function
range function returns a sequence of numbers, eg, numbers starting from 0 to n-1 for range(0, n)
range(int_value)
Comments
Comments are used to make the code more understandable for programmers, and they are not
executed by compiler or interpreter.
1/17
Home - CodeWithHarry
Multi-line comment
'''This is a
multi-line
comment'''
Escape Sequence
An escape sequence is a sequence of characters; it doesn't represent itself when used inside
string literal or character.
Newline
Newline Character
\n
Backslash
It adds a backslash
\\
Single Quote
\'
Tab
\t
2/17
Home - CodeWithHarry
Backspace
It adds a backspace
\b
Octal value
\ooo
Hex value
\xhh
Carriage Return
Carriage return or \r is a unique feature of Python. \r will just work as you have shifted your
cursor to the beginning of the string or line.
\r
Strings
Python string is a sequence of characters, and each character can be individually accessed. Using
its index.
String
You can create Strings by enclosing text in both forms of quotes - single quotes or double-
quotes.
Slicing
3/17
Home - CodeWithHarry
var_name[n : m]
string_variable.isalnum()
isalpha() method
string_variable.isalpha()
isdecimal() method
string_variable.isdecimal()
isdigit() method
string_variable.isdigit()
islower() method
string_variable.islower()
isspace() method
string_variable.isspace()
4/17
Home - CodeWithHarry
isupper() method
string_variable.isupper()
lower() method
string_variable.lower()
upper() method
string_variable.upper()
strip() method
string_variable.strip()
List
A List in Python represents a list of comma-separated values of any data type between square
brackets.
List
Returns the index of the first element with the specified value
list.index(element)
5/17
Home - CodeWithHarry
append method
list.append(element)
extend method
Add the elements of a list (or any iterable) to the end of the current list
list.extend(iterable)
insert method
list.insert(position, element)
pop method
list.pop(position)
remove method
The remove( ) method removes the first occurrence of a given item from the list
list.remove(element)
clear method
list.clear()
count method
6/17
Home - CodeWithHarry
list.count(value)
reverse method
list.reverse()
sort method
list.sort(reverse=True|False)
Tuples
Tuples are represented as a list of comma-separated values of any data type within parentheses.
Tuple Creation
tuple.count(value)
index method
It searches the tuple for a specified value and returns the position.
tuple.index(value)
Sets
7/17
Home - CodeWithHarry
A set is a collection of multiple values which is both unordered and unindexed. It is written in
curly brackets.
set.add(element)
clear() method
set.clear()
discard() method
set.discard(value)
intersection() method
issubset() method
8/17
Home - CodeWithHarry
set.issubset(set)
pop() method
set.pop()
remove() method
set.remove(item)
union() method
set.union(set1, set2...)
Dictionaries
The dictionary is an unordered set of comma-separated key: value pairs, within {}, with the
requirement that within a dictionary, no two keys can be the same.
Dictionary
<dictionary>[<key>] = <value>
If the specified key already exists, then its value will get updated
9/17
Home - CodeWithHarry
<dictionary>[<key>] = <value>
del let to delete specified key: value pair from the dictionary
del <dictionary>[<key>]
It returns the length of the dictionary, i.e., the count of elements (key: value pairs) in the
dictionary
len(dictionary)
clear() method
dictionary.clear()
get() method
dictionary.get(keyname)
items() method
dictionary.items()
keys() method
dictionary.keys()
10/17
Home - CodeWithHarry
values() method
dictionary.values()
update() method
dictionary.update(iterable)
Conditional Statements
The if statements are the conditional statements in Python, and these implement selection
constructs (decision constructs).
if Statement
if(conditional expression):
statements
if-else Statement
if(conditional expression):
statements
else:
statements
if-elif Statement
if (conditional expression) :
statements
statements
else :
statements
if (conditional expression):
if (conditional expression):
statements
else:
statements
else:
statements
Iterative Statements
An iteration statement, or loop, repeatedly executes a statement, known as the loop body, until
the controlling expression is false (0).
For Loop
The for loop of Python is designed to process the items of any sequence, such as a list or a
string, one by one.
statements_to_repeat
While Loop
A while loop is a conditional loop that will repeat the instructions within itself as long as a
conditional remains true.
while <logical-expression> :
loop-body
Break Statement
The break statement enables a program to skip over a part of the code. A break statement
terminates the very loop it lies within.
statement1
if <condition> :
break
statement2
statement_after_loop
12/17
Home - CodeWithHarry
Continue Statement
The continue statement skips the rest of the loop statements and causes the next iteration to
occur.
statement1
if <condition> :
continue
statement2
statement3
statement4
Functions
A function is a block of code that performs a specific task. You can pass parameters into a
function. It helps us to make our code more organized and manageable.
Function Definition
def my_function(parameters):
# Statements
File Handling
File handling refers to reading or writing data from files. Python provides some functions that
allow us to manipulate data in the files.
open() function
close() function
var_name.close()
Read () function
read-lines
readline
Write () function
writelines()
Append () function
The append function is used to append to the file instead of overwriting it. To append to an
existing file, simply open the file in append mode (a):
Exception Handling
An exception is an unusual condition that results in an interruption in the flow of the program.
A basic try-catch block in python. When the try block throws an error, the control goes to the
except block.
try:
raise Exception()
14/17
Home - CodeWithHarry
except Exception as e:
OOPS
It is a programming approach that primarily focuses on using objects and classes. The objects
can be any real-world entities.
class
class class_name:
#Statements
class CodeWithHarry:
# Default constructor
def __init__(self):
self.name = "CodeWithHarry"
def print_me(self):
print(self.name)
object
Instantiating an object
<object-name> = <class-name>(<arguments>)
filter function
The filter function allows you to process an iterable and extract those items that satisfy a given
condition
filter(function, iterable)
15/17
Home - CodeWithHarry
issubclass function
issubclass(class, classinfo)
Iterator
print(next(iter_list))
print(next(iter_list))
print(next(iter_list))
Generator
def my_gen():
n = 1
yield n
n += 1
yield n
n += 1
yield n
Decorators
16/17
Home - CodeWithHarry
Decorators are used to modifying the behavior of function or class. They are usually called before
the definition of a function you want to decorate.
@property
def name(self):
return self.__name
setter Decorator
@name.setter
self.__name=value
Deletor Decorator
print('Deleting..')
del self.__name
17/17