Moving to Python From C or Java [2]
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
andendswith
- determine if there is a substring at the start and end of a string, respectively.lower
andupper
- change the case of a stringsplit
- the opposite of join, turning a string with a certain separator into a list.
1 | print("".join(["spam", "eggs", "ham"])) |
String Formatting
https://docs.python.org/3.7/library/string.html#format-string-syntax
Some examples
1 | name = "Vines" |
Indexing Element / Slicing
In python, You can use [:] to extract multiple index.
So useful in extracting arrays and strings.
1 | print("Friday"[3]) # Prints a 'd' |
List Functions
all
andany
- 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 | nums = [55, 44, 33, 22, 11] |
Results:
1 | >>> |
Indentation
In C++, a code block is like this. You have curly brackets to warp the code body.
1 | int main() |
While in Python:
Python relies on identation (whitespace at the bebginning of a line) to define scope in the code.
Example:
1 | a = 33 |
Wrong Example:
1 | a = 33 |
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 |
|
Python Example
1 |
|
Skipping Parameter in Function
C++ Example
It is impossible to skip parameter in function.
Wrong Example:
1 | int fun(int, int, int); //prototype |
Python Example
1 |
|
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 | if boolvalue: |
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 | def func(): |
*args and **kwargs in Python
Note: they have little or no relationship with
argc
andargv
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 wordargs
. - 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 | # *args for variable number of arguments |
Output
1 | V |
Example with extra arguments
1 | # *args with first extra argument |
Output
1 | First argument : V |
**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 | def my_func(x, y=7, *args, **kwargs): |
Reference
Sololearn - Python
Learning Python: Powerful Object-Oriented Programming
*args and **kwargs in Python
Understanding Lists in Python 3
Function Annotations in Python