Basic syntax from the python programming language
print("Content that you wanna print on screen")
var1 = input("Enter your name: ")
my_list = []
my_dict = {}
range(int_value)
Comments are used to make the code more understandable for programmers, and they are not executed by compiler or interpreter.
Single line comment
#This is a single line comment
Multi-line comment
'''This is a
multi-line
comment'''
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 (It adds a single quotation mark)
\'
Tab (It gives a tab space)
\t
Backspace (It adds a backspace)
\b
Octal value (It represents the value of an octal number)
\ooo
Hex value (It represents the value of a hex number)
\xhh
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
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.
variable_name = "String Data"
Slicing: Slicing refers to obtaining a sub-string from the given string.
var_name[n : m]
string_variable.isalnum()
string_variable.isalpha()
string_variable.isdecimal()
string_variable.isdigit()
string_variable.islower()
string_variable.isspace()
string_variable.isupper()
string_variable.lower()
string_variable.upper()
string_variable.strip()
A List in Python represents a list of comma-separated values of any data type between square brackets.
List
var_name = [element1, element2, and so on]
list.index(element)
list.append(element)
list.extend(iterable)
list.insert(position, element)
list.pop(position)
list.remove(element)
list.clear()
list.count(value)
list.reverse()
list.sort(reverse=True|False)
Tuples are represented as a list of comma-separated values of any data type within parentheses.
variable_name = (element1, element2, ...)
tuple.count(value)
tuple.index(value)
A set is a collection of multiple values which is both unordered and unindexed. It is written in curly brackets.
Set Creation: Way 1
var_name = {element1, element2, ...}
Set Creation: Way 2
var_name = set([element1, element2, ...])
set.add(element)
set.clear()
set.discard(value)
set.intersection(set1, set2 ... etc)
set.issubset(set)
set.pop()
set.remove(item)
set.union(set1, set2...)
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-name> = {<key>: value, <key>: value ...}
<dictionary>[<key>] = <value>
<dictionary>[<key>] = <value>
del <dictionary>[<key>]
len(dictionary)
dictionary.clear()
dictionary.get(keyname)
dictionary.items()
dictionary.keys()
dictionary.values()
dictionary.update(iterable)
The if statements are the conditional statements in Python, and these implement selection constructs (decision constructs).
if(conditional expression):
statements
if(conditional expression):
statements
else:
statements
if (conditional expression) :
statements
elif (conditional expression) :
statements
else :
statements
if (conditional expression):
statements
else:
statements
else:
statements
An iteration statement, or loop, repeatedly executes a statement, known as the loop body, until the controlling expression is false (0).
for <variable> in <sequence>:
statements_to_repeat
while <logical-expression> :
loop-body
for <var> in <sequence> :
statement1
if <condition> :
break
statement2
statement_after_loop
for <var> in <sequence> :
statement1
if <condition> :
continue
statement2
statement3
statement4
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 refers to reading or writing data from files. Python provides some functions that allow us to manipulate data in the files.
var_name = open("file name", "opening mode")
var_name.close()
read() # return one big string
read-lines # returns a list of lines
readline # returns one line at a time
write () # Used to write a fixed sequence of characters to a file
writelines() # Used to write a list of strings
file = open("Hello.txt", "a")
An exception is an unusual condition that results in an interruption in the flow of the program.
try and except: A basic try-catch block in python. When the try block throws an error, the control goes to the except block.
try:
[Statement body block]
raise Exception()
except Exception as e:
[Error processing block]
It is a programming approach that primarily focuses on using objects and classes. The objects can be any real-world entities.
class class_name:
#Statements
class Abhiraj: # Default constructor
def __init__(self):
self.name = "Abhiraj" # A method for printing data members
def print_me(self):
print(self.name)
<object-name> = <class-name>(<arguments>)
filter(function, iterable)
issubclass(class, classinfo)
Here are some of the advanced topics of the Python programming language like iterators and generators
iter_list = iter(['Harry', 'Aakash', 'Rohan'])
print(next(iter_list))
print(next(iter_list))
print(next(iter_list))
# A simple generator function
def my_gen():
n = 1
print('This is printed first')
# Generator function contains yield statements
yield n
n += 1
print('This is printed second')
yield n
n += 1
print('This is printed at last')
yield n
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
@name.setter
def name(self, value):
self.__name=value
@name.deleter #property-name.deleter decorator
def name(self, value):
print('Deleting..')
del self.__name