1) List Comprehension:
is a useful way to create lists when elements obey simple rule.
e.g cubes = [i**3 for i in range(10)]
With conditional
cubes = [i**3 for i in range(10) if i%2==0]
2) String Formatting:
Syntax: 'some string {0} {1} {2}'.format(value1,value2,value3)
e.g.
msg = "{0} is my friend,{0} is my best friend. His nickname is {1} {2}".format('Bob','Tony','-hehe')
format can have any data that needs to be printed out.
3)Useful functions for strings:
','.join(list_of_string)
'Hello World'.replace('Hello','Sup')
'this is test string'.startswith('this')
'this is my string'.endswith('string')
'some string'.upper()
'ANOTHER STRING'.lower()
'this is a string again'.split(' ')
Some other functions
min(list or tuple), returns minimum number
max(list or tuple), returns maximum number
abs(-3), returns 3
sum(list or tuple), returns sum of all elements
all(list or tuple), returns true if all elements evaluate to true
any(list or tuple), returns true if any element evaluates to true
enumerate(list or tuple or string, start=value). adds a counter to an iterable and returns it in a form of enumerating object.
-------------
chr(interger), returns corresponding character to ASCII value
ord(character), returns corresponding ASCII value of character
Python
Type 2 of itertools
remember you have to import them using
from itertools import name_of_itertool
1)takewhile
Take values from iterable while the predicate function remains true,once predicate function returns false it will no
longer take values.
example:
lis=[2,4,1,8,6,14]
lis_even=list(takewhile(lambda x:x % 2 == 0,lis))
returns lis_even=[2,4]
2)accumulate
Returns a running total of values in iterable.
lis=[0,1,2,3]
lis_new=list(accumulate(lis))
returns lis_new=[0,1,3,6]
1)Recursive Functions:
Every recursive function has a base case that stops it from going into the fourth dimension(that's what I like to think 😅).
Example 1:
Recursive functions can be implemented with more than one function. Here's an example for checking even and odd numbers
Example 2:
Day 3 of #100DaysOfCode
Python.
Motivation, Don't Repeat Yourself.
1)Defining a function
def function_name(parameters_if_any):
"""indentation identifies the code block of a function"""
return data_if_any
Parameters: are variables in function definition.
Arguments: are the values put into parameters when functions are called.
Calling a function: function_name(arguments_if_any)
2)Modules
These are the codes written to perform useful tasks. Some modules are already part of standard library and others need to be
installed.
-To import an existing module e.g. math
import math #imports whole math module