Delete Variable

1
del <variable>

Useful String Functions

  • join - joins a list of strings with another string as a separator.
  • replace - replaces one substring in a string with another.
  • startswith and endswith - determine if there is a substring at the start and end of a string, respectively.
  • lower and upper - change the case of a string
  • split - the opposite of join, turning a string with a certain separator into a list.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
print("".join(["spam", "eggs", "ham"]))
#prints "spam, eggs, ham"

print(", ".join(["spam", "eggs", "ham"]))
#prints "spam, eggs, ham"

print("Hello ME".replace("ME", "world"))
#prints "Hello world"

print("This is a sentence.".startswith("This"))
# prints "True"

print("This is a sentence.".endswith("sentence."))
# prints "True"

print("This is a sentence.".upper())
# prints "THIS IS A SENTENCE."

print("AN ALL CAPS SENTENCE".lower())
#prints "an all caps sentence"

print("spam, eggs, ham".split(", "))
#prints "['spam', 'eggs', 'ham']"

String Formatting

https://docs.python.org/3.7/library/string.html#format-string-syntax

Some examples

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
name = "Vines"
score = 9

print("{} scores {} marks.".format(name,score))
#Vines scores 9 marks.

print("{1} scores {0} marks.".format(score,name))
#Vines scores 9 marks.

print("{0:s} scores {1:02d} marks.".format(name,score))
#Vines scores 09 marks.

print("{:s} scores {:04.1f} marks.".format(name,score))
#Vines scores 09.0 marks.

print("{:>20} scores {:.2f} marks.".format(name,score))
# Vines scores 9.00 marks.

Indexing Element / Slicing

In python, You can use [:] to extract multiple index.
So useful in extracting arrays and strings.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
print("Friday"[3]) # Prints a 'd'
print("Friday"[:3]) # Prints a 'Fri'
print("Friday"[3:]) # Prints a 'day'

array = [1,3,4,7,8,9]
print(array[3]) # Prints 7
print(array[0:3]) # Prints [1,3,4]
print(array[:3]) # Prints [1,3,4]
print(array[3:]) # Prints [7,8,9]
print(array[-1]) # Prints 9
print(array[1:3]) # Prints [3,4]
print(array[-2:]) # Prints [8,9]

# List slices can also have a third number representing the step
print(array[::2]) # Prints [1,4,8]
print(array[2:5:3]) # Prints [4]
print(array[2:6:3]) # Prints [4,9]

# Reverse Indexing
print(array[::-1]) # Prints [9, 8, 7, 4, 3, 1]
print(array[5:3:-1]) # Prints [9, 8]

List Functions

  • all and any - take a list as an argument, and return True if all or any (respectively) of their arguments evaluate to True (and False otherwise).
  • enumerate - used to iterate through the values and indices of a list simultaneously.
1
2
3
4
5
6
7
8
9
10
nums = [55, 44, 33, 22, 11]

if all([i > 5 for i in nums]):
print("All larger than 5")

if any([i % 2 == 0 for i in nums]):
print("At least one is even")

for v in enumerate(nums):
print(v)

Results:

1
2
3
4
5
6
7
8
9
>>>
All larger than 5
At least one is even
(0, 55)
(1, 44)
(2, 33)
(3, 22)
(4, 11)
>>>

Indentation

In C++, a code block is like this. You have curly brackets to warp the code body.

1
2
3
4
int main()
{
//Code
}

While in Python:

Python relies on identation (whitespace at the bebginning of a line) to define scope in the code.

Example:

1
2
3
4
a = 33
b = 200
if b > a:
print("b is greater than a") # code indentation here

Wrong Example:

1
2
3
4
a = 33
b = 200
if b > a:
print("b is greater than a") # Error: No identation

The indentation rule may seem unusual at first glance to programmers accustomed to C-like languages, but it is a deliberate feature of Python, and it’s one of the main ways that Python almost forces programmers to produce uniform, regular, and readable code. It essentially means that you must line up your code vertically, in columns, ac- cording to its logical structure. The net effect is to make your code more consistent and readable (unlike much of the code written in C-like languages).

To put that more strongly, aligning your code according to its logical structure is a major part of making it readable, and thus reusable and maintainable, by yourself and others. In fact, even if you never use Python after reading this book, you should get into the habit of aligning your code for readability in any block-structured language. Python underscores the issue by making this a part of its syntax, but it’s an important thing to do in any programming language, and it has a huge impact on the usefulness of your code.

Functions

Returning multiple values using function

normal function can only return ONE value/ object.

C++ Example

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
#include <iostream>
using namespace std;

void opt(int, int *, int *); //prototype

int main(){
int num, sqr, cub;
cout << "Input a number: ";
cin >> num;
opt(num, &sqr, &cub);
cout << "Square = "<< sqr << endl;
cout << "Cude = " << cub << endl;
return 0;
}

void opt(int n, int *pS, int *pC)
{
*pS = n*n;
*pC = n*n*n;
}

Python Example

1
2
3
4
5
6

def function():
return (0,0) # Or: return 0,0

x,y = function()

Skipping Parameter in Function

C++ Example

It is impossible to skip parameter in function.

Wrong Example:

1
2
3
4
5
6
7
8
9
10
11
int fun(int, int, int); //prototype

int fun(int a =1, int b = 2, int c = 3)
{
return a*b*c;
}

int main(){
int x = fun(c = 3); // error: ‘c’ was not declared in this scope
}

Python Example

1
2
3
4
5
6
7

def fun(a=1, b=2, c=3):
return a*b*c

x = fun(c = 10)
# ^ value of x is 1*2*10 = 20

Functions in runtime

If else + functions

The Python def is a true executable statement: when it runs, it creates a new function object and assigns it to a name. (Remember, all we have in Python is runtime; there is no such thing as a separate compile time.) Because it’s a statement, a def can appear anywhere a statement can—even nested in other statements. For instance, although defs normally are run when the module enclosing them is imported, it’s also completely legal to nest a function def inside an if statement to select between alternative definitions:

1
2
3
4
5
6
7
8
9
10
11
if boolvalue:
def function(): # Define func this way
doSomeThing()

else
def function(): # Or else this way
doSomeOtherThing()

...

function() # Call the version selected and built

Altering function

Unlike in compiled languages such as C, Python functions do not need to be fully defined before the program runs. More generally, defs are not evaluated until they are reached and run, and the code inside defs is not evaluated until the functions are later called.

1
2
3
4
5
def func():
doSomeThing()

funcWithCoolerName = func # Assign function object
funcWithCoolerName() # Call func again

*args and **kwargs in Python

Note: they have little or no relationship with argc and argv in C++.

*args

The special syntax *args in function definitions in python is used to pass a variable number of arguments to a function.
It is used to pass a non-keyworded, variable-length argument list.

  • The syntax is to use the symbol * to take in a variable number of arguments; by convention, it is often used with the word args.
  • What *args allows you to do is take in more arguments than the number of formal arguments that you previously defined. With *args, any number of extra arguments can be tacked on to your current formal parameters (including zero extra arguments).
  • For example : we want to make a multiply function that takes any number of arguments and able to multiply them all together. It can be done using *args.
  • Using the *, the variable that we associate with the * becomes an iterable meaning you can do things like iterate over it, run some higher order functions such as map and filter, etc.

Example

1
2
3
4
5
6
7
# *args for variable number of arguments 
def fun(*argv):
for arg in argv:
print (arg)

fun('V', 'I', 'N', 'E','S','NOTE')

Output

1
2
3
4
5
6
V
I
N
E
S
NOTE

Example with extra arguments

1
2
3
4
5
6
7
# *args with first extra argument 
def fun(arg1, *argv):
print ("First argument :", arg1)
for arg in argv:
print("Next argument through *argv :", arg)

fun('V', 'I', 'N', 'E','S','NOTE')

Output

1
2
3
4
5
6
First argument : V
Next argument through *argv : I
Next argument through *argv : N
Next argument through *argv : E
Next argument through *argv : S
Next argument through *argv : NOTE

**kwargs

**kwargs (standing for keyword arguments) allows you to handle named arguments that you have not defined in advance.
The keyword arguments return a dictionary in which the keys are the argument names, and the values are the argument values.

1
2
3
4
5
6
def my_func(x, y=7, *args, **kwargs):
print(kwargs)

my_func(2, 3, 4, 5, 6, a=7, b=8)
# Result:
# {'a': 7, 'b': 8}

Reference

Sololearn - Python
Learning Python: Powerful Object-Oriented Programming
*args and **kwargs in Python
Understanding Lists in Python 3
Function Annotations in Python