├── GettingStarted.md
├── LICENSE
├── README.md
├── basics
├── README.md
├── examples
│ ├── .gitignore
│ └── print.py
├── input.md
├── print.md
└── variables.md
├── classes
└── README.md
├── datatypes
├── README.md
├── dict.md
├── examples
│ ├── .gitignore
│ ├── Numbers.py
│ ├── dict.py
│ ├── list.py
│ ├── sets.py
│ ├── string.py
│ └── tuples.py
├── list.md
├── numbers.md
├── sets.md
├── string.md
└── tuples.md
├── filehandling
└── README.md
├── flask
├── README.md
└── example
│ ├── app.py
│ ├── data
│ ├── notes.json
│ └── user.json
│ ├── static
│ └── style.css
│ └── templates
│ ├── dashboard.html
│ ├── index.html
│ ├── layout.html
│ └── notes.html
├── flowcontrol
├── README.md
├── controlKeywords.md
├── examples
│ ├── .gitignore
│ ├── filehandling
│ │ └── README.md
│ ├── for.py
│ └── tryExcept.py
├── for.md
├── ifelse.md
├── tryExcept.md
└── while.md
├── functions
├── README.md
└── examples
│ ├── .gitignore
│ ├── add_twice.py
│ ├── exclaim.py
│ ├── function_as_argument.py
│ ├── function_scope.py
│ └── functions_objects.py
└── operators
├── README.md
└── examples
├── .gitignore
├── ArithmeticOperators.py
├── BitwiseOperators.py
├── ComparisonOperators.py
├── IdentityOperators.py
├── LogicalOperators.py
└── MembershipOperators.py
/GettingStarted.md:
--------------------------------------------------------------------------------
1 | # GETTING STARTED WITH PYTHON
2 |
3 | ## For getting started with python visit the links provided
4 |
5 | * Main Website: https://www.python.org/
6 |
7 | * For Windows : https://www.youtube.com/watch?v=dX2-V2BocqQ&t=33s
8 |
9 | * For Mac : https://www.youtube.com/watch?v=dX2-V2BocqQ
10 |
11 | * For Linux: https://www.youtube.com/watch?v=LbrU4zOjmic
12 |
13 | Also for setting up with the environment variables: https://www.youtube.com/watch?v=Y2q_b4ugPWk
14 |
15 | * For more information on basics click [here](./basics).
16 |
--------------------------------------------------------------------------------
/LICENSE:
--------------------------------------------------------------------------------
1 | MIT License
2 |
3 | Copyright (c) 2018 ACM VIT
4 |
5 | Permission is hereby granted, free of charge, to any person obtaining a copy
6 | of this software and associated documentation files (the "Software"), to deal
7 | in the Software without restriction, including without limitation the rights
8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9 | copies of the Software, and to permit persons to whom the Software is
10 | furnished to do so, subject to the following conditions:
11 |
12 | The above copyright notice and this permission notice shall be included in all
13 | copies or substantial portions of the Software.
14 |
15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21 | SOFTWARE.
22 |
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 | # PyFlask
2 |
3 | A workshop organised by [ACM VIT](https:/acmvit.in) every year, during [Gravitas](http://www.vit.ac.in/files/gravitas18/home.html) (VIT University, Tech Fest). Before today, This workshop was ***PyGAE***, which included sessions on **Python Programming** and Creating Website Using **Google App Engine**, This time session was on Creating Website Using **Flask** (A light weight **Python** framework).
4 |
5 | ## What is ACM VIT?
6 |
7 | ACM VIT Student Chapter, a student organization which takes pride in conducting workshops for the student community, Helping the underprivileged, by collaborating with local organizational bodies in and around Vellore, to give them a head start with technology.
8 |
9 | Currently, We are also working with various projects with a vision to help the society, We will soon be launching some of these, once we are done with alpha testing.
10 |
11 | If you are looking to contribute or have any project idea which requires guidance and a team, Feel free to drop an email tech@vit.acm.org
12 |
13 | ## Why This Repository?
14 |
15 | Motive of this repository is to have a centralized way to access **PyFlask 2k18** materials, which may serve as a reference during and after the workshop.
16 |
17 | ## Contents
18 |
19 | * [Basics](./basics)
20 | * [How to take input](./basics/input.md)
21 | * [Printing output in Python](./basics/print.md)
22 | * [Variables in Python](./basics/variables.md)
23 |
24 | * [Datatypes](./datatypes)
25 | * [Numbers](./datatypes/numbers.md)
26 | * [Strings](./datatypes/string.md)
27 | * [Lists](./datatypes/list.md)
28 | * [Dictionaries](./datatypes/dict.md)
29 | * [Sets](./datatypes/sets.md)
30 | * [Tuples](./datatypes/tuples.md)
31 |
32 | * [Operators](./operators)
33 |
34 | * [Flow Control](./flowcontrol)
35 | * [If Else](./flowcontrol/ifelse.md)
36 | * [While Loop](./flowcontrol/while.md)
37 | * [For Loop](./flowcontrol/for.md)
38 | * [Try Except](./flowcontrol/tryExcept.md)
39 | * [Break, Pass, Continue](./flowcontrol/controlKeywords.md)
40 |
41 | * [Functions](./functions)
42 |
43 | * [Classes](./classes)
44 |
45 | * [File Handling](./filehandling)
46 |
47 | * [Flask](./flask)
48 |
49 | ## Copyright & License
50 |
51 | Copyright (c) 2018 ACM VIT, Registered Under [MIT LICENSE](./LICENSE)
--------------------------------------------------------------------------------
/basics/README.md:
--------------------------------------------------------------------------------
1 | # Basics
2 |
3 | Python is a general-purpose language. It has wide range of applications from Web development , scientific and mathematical computing to desktop graphical user Interfaces.
4 |
5 | Python is a powerful high-level, object-oriented programming language created by Guido van Rossum.
6 |
7 | The syntax of the language is clean and length of the code is relatively short. It's fun to work in Python because it allows you to think about the problem rather than focusing on the syntax.
8 |
9 | ## Reasons to Choose Python as First Language
10 |
11 | * Simple Elegant Syntax
12 |
13 | Programming in Python is fun. It's easier to understand and write Python code.
14 |
15 | * Not overly strict
16 |
17 | You don't need to define the type of a variable in Python. Also, it's not necessary to add semicolon at the end of the statement.
18 |
19 | Python enforces you to follow good practices (like proper indentation). These small things can make learning much easier for beginners
20 |
21 | * Great Community and Support
22 |
23 | Python has a large supporting community. There are numerous active forums online which can be handy if you are stuck.
24 |
25 | ## Basics comprises of the following
26 |
27 | * [Input](./input.md)
28 | * Input is used to read data from user. You call this function to tell the program to stop and wait for the user to key in the data.
29 |
30 | * [Print](./print.md)
31 | * The print() function prints the given object to the standard output device (screen) or to the text stream file.
32 |
33 | * [Variables](./variables.md)
34 | * In programming, variables can be used to store numbers, decimal numbers, results of arithmetic operations, words or sentences. In some programming languages, you do not need to specify what kind of value can be stored in a variable where as in some you must.
35 |
36 | **For more information on Basics:**
37 | You can check out more examples [here](./examples)
38 |
39 | ### For more information on DataTypes:
40 |
41 | * https://www.pythonforbeginners.com/input/
42 |
43 | * https://www.programiz.com/search/print
44 |
45 | * https://www.w3schools.com/python/python_variables.asp
46 |
--------------------------------------------------------------------------------
/basics/examples/.gitignore:
--------------------------------------------------------------------------------
1 | *.pyc
2 | !.gitignore
--------------------------------------------------------------------------------
/basics/examples/print.py:
--------------------------------------------------------------------------------
1 | import sys
2 | # Some Examples of the print function in python
3 |
4 | # Only _values_ as arguments
5 | a = 3.564
6 | print("a = ", a)
7 | print("a = \n", a)
8 | print("a = ", a)
9 | print("a = \n", a)
10 |
11 | ### _sep_ argument is used
12 | print("a","b")
13 | print("a","b",sep="")
14 | print(192,168,178,42,sep=".")
15 | print("a","b",sep=":-)")
16 |
17 |
18 | ### _end_ argument is used
19 | for i in range(4):
20 | print(i)
21 | for i in range(4):
22 | print(i, end=" ")
23 | for i in range(4):
24 | print(i, end=" :-) ")
25 |
26 | # _file_ argument is used
27 | fh = open("data.txt","w")
28 | print("42 is the answer, but what is the question?", file=fh)
29 | fh.close()
30 | # output into sys.stderr:
31 |
32 | print("Error: 42", file=sys.stderr)
33 |
34 | # _flush_ argument details
35 | #The file argument must be an object with a write(string) method; if it is not present or None, sys.stdout will be used. Whether output is buffered is usually determined by file, but if the flush keyword argument is true, the stream is forcibly flushed.
36 |
37 | #escape sequence examples
38 |
39 | print("Hello\nWorld") # New line
40 |
41 | print("Hello\tWorld") # Horizontal Tab
42 |
43 | print("Hello \'World\' ") # Single quote
44 |
45 | print("Hello \"World\" ") #Double quote
46 |
47 | print("Hello \\World") # BackSlash
--------------------------------------------------------------------------------
/basics/input.md:
--------------------------------------------------------------------------------
1 | # INPUT
2 |
3 | ## What is input?
4 |
5 | Input is used to read data from user.
6 |
7 | ## How to take input?
8 |
9 | There are two functions in Python that you can use to read data from the user: raw_input() and input()
10 |
11 | For python 2.x:
12 | input() is used to read integers.
13 | raw_input() is used to read text(strings) from the user.
14 |
15 | For python 3.x:
16 | input() is used to read strings.
17 | To read strings, it can be typecasted using int(input())
18 |
19 | Multiple inputs can be taken in one line using split()
20 |
21 | You can store the results from them into a variable.
22 |
23 | ## Syntax
24 |
25 | x = input()
26 | y = raw_input()
27 | a,b,c = input().split()
28 |
29 | ## Examples
30 |
31 | num=input("Enter a number: ")
32 |
33 | name=raw_input("Enter your name: ")
34 |
35 | You can check out more [examples](./examples) here.
36 |
37 | **For more information on Input:**
38 |
39 | https://www.pythonforbeginners.com/input/
40 |
41 |
--------------------------------------------------------------------------------
/basics/print.md:
--------------------------------------------------------------------------------
1 | ## What does print function do:
2 | The print function in Python is a function that outputs to your console window whatever you say you want to print out. At first blush, it might appear that the print function is rather useless for programming, but it is actually one of the most widely used functions in all of python.The reason for this is that it makes for a great debugging tool.
3 | "Debugging" is the term given to the act of finding, removing, and fixing errors and mistakes within code.
4 | If something isn't acting right, you can use the print function to print out what is happening in the program. Many times, you expect a certain variable to be one thing, but you cannot see what the program sees. If you print out the variable, you might see that what you thought was, was not.
5 |
6 | ## Print function syntax:
7 | print(value1, ..., sep=' ', end='\n', file=sys.stdout, flush=False)
8 | where parameters are seperated by a ,
9 |
10 | *Parameter Description*
11 | * object(s) Any object, and as many as you like. Will be converted to string before printed
12 | * sep='separator' (Optional)Specify how to separate the objects, if there is more than one. Default is ''
13 | * end='end' (Optional)Specify what to print at the end. Default is '\n' (line feed)
14 | * file (Optional)An object with a write method. Default is sys.stdout
15 | * flush (Optional)A Boolean, specifying if the output is flushed (True) or buffered (False). Default is False
16 |
17 | ## Use of escape sequence
18 | In Python strings, the backslash "\" is a special character, also called the "escape" character. It is used in representing certain whitespace characters: "\t" is a tab, "\n" is a newline, and "\r" is a carriage return. ... Finally, "\" can be used to escape itself: "\\" is the literal backslash character.
19 |
20 | Take a look at [Examples](./basics/examples/print.py) to make things more clear to you
21 |
22 | You can know more about the print function :
23 | 1. Print function use : https://pythonprogramming.net/python-tutorial-print-function-strings/
24 | 2. Syntax and attributes of print function : https://www.w3schools.com/python/ref_func_print.asp
25 | 3. Some examples of print function : https://www.programiz.com/python-programming/methods/built-in/print
--------------------------------------------------------------------------------
/basics/variables.md:
--------------------------------------------------------------------------------
1 | # Variables
2 | * Variables play a very important role in most programming languages, and Python is no exception.
3 | * A variable allows you to store a value by assigning it to a name, which can be used to refer to the value later in the program.
4 | * To assign a variable, use one equals sign. Unlike most lines of code we've looked at so far, it doesn't produce any output at the Python console.
5 | #### Example
6 |
7 | ```
8 | >>> x = 7
9 | >>> print(x)
10 | 7
11 | >>> print(x + 3)
12 | 10
13 | >>> print(x)
14 | 7
15 | ```
16 | _**NOTE** : You can use variables to perform corresponding operations, just as you did with numbers and strings. As you can see, the variable stores its value throughout the program._
17 |
18 | * Variables can be reassigned as many times as you want, in order to change their value.
19 | In Python, variables don't have specific types, so you can assign a string to a variable, and later assign an integer to the same variable.
20 | #### Example
21 | ```
22 | >>> x = 123.456
23 | >>> print(x)
24 | 123.456
25 | >>> x = "This is a string"
26 | >>> print(x + "!")
27 | This is a string!
28 | ```
29 | _**NOTE** : However, it is not good practice. To avoid mistakes, try to avoid overwriting the same variable with different data types._
30 | ## Variable Names
31 | * Certain restrictions apply in regard to the characters that may be used in Python variable names.
32 | * The only characters that are allowed are letters, numbers, and underscores. Also, they can't start with numbers.
33 | * Not following these rules results in errors.
34 | ```
35 | >>> this_is_a_normal_name = 7
36 |
37 | >>> 123abc = 7
38 | SyntaxError: invalid syntax
39 |
40 | >>> spaces are not allowed
41 | SyntaxError: invalid syntax
42 | ```
43 | ## Variable Assignment
44 | * Trying to reference a variable you haven't assigned to causes an error.
45 | * You can use the del statement to remove a variable, which means the reference from the name to the value is deleted, and trying to use the variable causes an error.
46 | * Deleted variables can be reassigned to later as normal.
47 |
48 | #### Example
49 | ```
50 | >>> foo = "a string"
51 | >>> foo
52 | 'a string'
53 | >>> bar
54 | NameError: name 'bar' is not defined
55 | >>> del foo
56 | >>> foo
57 | NameError: name 'foo' is not defined
58 | ```
59 | * You can also take the value of the variable from the user input.
60 | ```
61 | >>> foo = input("Enter a number: ")
62 | Enter a number: 7
63 | >>> print(foo)
64 | 7
65 | ```
66 |
--------------------------------------------------------------------------------
/classes/README.md:
--------------------------------------------------------------------------------
1 | # Classes
2 |
3 | Python is an “object-oriented programming language.” This means that almost all the code is implemented using a special construct called classes. Programmers use classes to keep related things together. This is done using the keyword “class,” which is a grouping of object-oriented constructs.
4 |
5 | ## What is a class?
6 |
7 | A class is a code template for creating objects. Objects have member variables and have behaviour associated with them. In python a class is created by the keyword class.
8 |
9 | An object is created using the constructor of the class. This object will then be called the instance of the class. In Python we create instances in the following manner:-
10 |
11 | ```python
12 | Instance = class(arguments)
13 | ```
14 | ## How to create a class ?
15 |
16 | The simplest class can be created using the class keyword. For example, let's create a simple, empty class with no functionalities.
17 |
18 | ```python
19 | >>> class Snake:
20 | ... pass
21 | ...
22 | >>> snake = Snake()
23 | >>> print(snake)
24 | <__main__.Snake object at 0x7f315c573550>
25 | ```
26 |
27 | ## Attributes in python
28 |
29 | A class by itself is of no use unless there is some functionality associated with it. Functionalities are defined by setting attributes, which act as containers for data and functions related to those attributes. Those functions are called methods.
30 |
31 | You can define the following class with the name Snake. This class will have an attribute name.
32 |
33 | ```python
34 | >>> class Snake:
35 | ... name = "python" # set an attribute `name` of the class
36 | ...
37 | ```
38 |
39 | You can assign the class to a variable. This is called object instantiation. You will then be able to access the attributes that are present inside the class using the dot . operator. For example, in the Snake example, you can access the attribute name of the class Snake.
40 |
41 | ```python
42 | >>> # instantiate the class Snake and assign it to variable snake
43 | >>> snake = Snake()
44 |
45 | >>> # access the class attribute name inside the class Snake.
46 | >>> print(snake.name)
47 | python
48 | ```
49 |
50 | ## Methods in python
51 |
52 | Once there are attributes that “belong” to the class, you can define functions that will access the class attribute. These functions are called methods. When you define methods, you will need to always provide the first argument to the method with a self keyword.
53 |
54 | ```python
55 | >>> class Snake:
56 | ... name = "python"
57 | ...
58 | ... def change_name(self, new_name): # note that the first argument is self
59 | ... self.name = new_name # access the class attribute with the self keyword
60 | ...
61 | ```
62 |
63 | Now, you can instantiate this class Snake with a variable snake and then change the name with the method change_name.
64 |
65 | ```python
66 | >>> # instantiate the class
67 | >>> snake = Snake()
68 |
69 | >>> # print the current object name
70 | >>> print(snake.name)
71 | python
72 |
73 | >>> # change the name using the change_name method
74 | >>> snake.change_name("anaconda")
75 | >>> print(snake.name)
76 | anaconda
77 | ```
78 |
79 | **For more information on Classes:**
80 |
81 | * https://www.hackerearth.com/practice/python/object-oriented-programming/classes-and-objects-i/tutorial/
82 |
83 | * https://www.w3schools.com/python/python_classes.asp
84 |
--------------------------------------------------------------------------------
/datatypes/README.md:
--------------------------------------------------------------------------------
1 | # DATATYPES
2 |
3 | The data type of a value is an attribute that tells what kind of data that value can have. Data types define particular characteristics of data used in software programs and inform the compilers about predefined attributes required by specific variables or associated data objects.
4 |
5 | ## Use Of DataTypes
6 |
7 | Data types are basically used for two reasons:
8 |
9 | * Knowing the type of data used for processing/returning. This helps both the programmer(not necessarily) and compiler use the values in the right form. Also the programmer can choose the data type according to the requirements like precision, integer values, range and sign.
10 |
11 | * Memory allocation: Every data type has a memory size associated with it. So proper utilisation of memory can be done when suitable data types are used.
12 |
13 | ## Available DataTypes In Python
14 |
15 | There are various data types in Python. Some of the important types are listed below:
16 | * [Numbers](./numbers.md)
17 | * Integers, floating point numbers and complex numbers falls under Python numbers category. They are defined as int, float and complex class in Python.
18 |
19 | * [List](./list.md)
20 | * List is an ordered sequence of items. It is one of the most used datatype in Python and is very flexible. All the items in a list do not need to be of the same type.
21 |
22 | * [Tuple](./tuples.md)
23 | * Tuple is an ordered sequence of items same as list.The only difference is that tuples are immutable. Tuples once created cannot be modified.
24 |
25 | * [Strings](./string.md)
26 | * String is sequence of Unicode characters. We can use single quotes or double quotes to represent strings. Multi-line strings can be denoted using triple quotes, ''' or """.
27 |
28 | * [Sets](./sets.md)
29 | * Set is an unordered collection of unique items. Set is defined by values separated by comma inside braces { }. Items in a set are not ordered.
30 |
31 | * [Dictionary](./dict.md)
32 | * Dictionary is an unordered collection of key-value pairs. It is generally used when we have a huge amount of data. Dictionaries are optimized for retrieving data. We must know the key to retrieve the value.
33 |
34 | You can check out more [examples](./examples) here.
35 |
36 | **For more information on DataTypes:**
37 | You can check out more examples [here](./examples).
38 |
39 | ### For more information on DataTypes:
40 |
41 | * https://www.programiz.com/python-programming/variables-datatypes
42 |
43 | * https://realpython.com/python-data-types/
44 |
45 | * https://www.techopedia.com/definition/3349/data-type
--------------------------------------------------------------------------------
/datatypes/dict.md:
--------------------------------------------------------------------------------
1 | ## Dictionary
2 | Dictionaries are Python’s implementation of a data structure that is more generally known as an associative array. A dictionary consists of a collection of key-value pairs. Each key-value pair maps the key to its associated value.
3 |
4 | ### Defining a dictionary
5 | You can define a dictionary by enclosing a comma-separated list of key-value pairs in curly braces ({}). A colon (:) separates each key from its associated value.
6 |
7 |
For eg
8 |
9 | `d = {
10 | : ,
11 | : ,
12 | .
13 | .
14 | .
15 | :
16 | }`
17 |
18 | You can also construct a dictionary with the built-in dict() function. The argument to dict() should be a sequence of key-value pairs. A list of tuple works well for this:
19 | `d = dict([
20 | (, ),
21 | (, , )
26 | ])`
27 | If the key values are simple strings, they can be specified as keyword arguments.
28 | `d = dict(
29 | = ,
30 | = =
35 | )`
36 | ## Accessing Dictionary values
37 |
38 | After defining a dictionary, we need to access the values assigned. Unlike list, we cannot access elements by their index numbers. So how to access them??
39 |
40 | In dictionary, a value is retrieved by specifying its corresponding key in square bracket. `([])`
41 |
For eg:
42 |
43 | `d[]`
44 |
45 | Alternatively, we can also use `d.get()`
46 |
47 | #### Updating an entry
48 | To update an entry, just assign a new value to the existing key, i.e.
49 | `d[] = `
50 |
51 | We can even create new entry in this fashion, i.e.,
52 | `d[] = `
53 |
54 | #### Deleting an entry
55 | Use `del` statement, specifying the key to delete, i.e.
56 | `del d[]`
57 |
58 | ## Built-in Dictionary Method
59 | As with strings and lists, there are several built-in methods that can be invoked on dictionaries. In fact, in some cases, the list and dictionary methods share the same name. (In the discussion on object-oriented programming, you will see that it is perfectly acceptable for different types to have methods with the same name.)
60 | ##### d.clear()
61 | `Clears a dictionary`
62 |
63 | ##### d.get([, ])
64 | `Returns the value for a key if it exists in the dictionary`
65 |
66 | ##### d.items()
67 | `Returns a list of key-value pairs in a dictionary`
68 |
69 | ##### d.keys()
70 | `Returns a list of keys in a dictionary`
71 |
72 | ##### d.values()
73 | `Returns a list of values in a dictionary`
74 |
75 | ##### d.pop([, ])
76 | `Removes a key from a dictionary, if it is present, and returns its value`
77 |
78 | ##### d.update()
79 | `Merges a dictionary with another dictionary or with an iterable of key-value pairs`
80 |
81 | Please refer `/datatypes/examples/dict.py` for more examples.
82 |
83 | For more details and information, please external links and tutorials:
84 | Basics: http://www.tutorialspoint.com/python/python_dictionary.htm
85 |
86 | Along with hands on tutorial: https://www.w3schools.com/python/python_dictionaries.asp
87 |
88 |
--------------------------------------------------------------------------------
/datatypes/examples/.gitignore:
--------------------------------------------------------------------------------
1 | *.pyc
2 | !.gitignore
--------------------------------------------------------------------------------
/datatypes/examples/Numbers.py:
--------------------------------------------------------------------------------
1 | #Complex numbers are written in the form, x + yj, where x is the real part and y is the imaginary part.
2 |
3 | #We can use the type() function to know which class a variable or a value belongs to and isinstance() function to check if it belongs to a particular class.
4 |
5 |
6 | a = 5
7 |
8 | # Output:
9 | print(type(a))
10 |
11 | # Output:
12 | print(type(5.0))
13 |
14 | # Output: (8+3j)
15 | c = 5 + 3j
16 | print(c + 3)
17 |
18 | # Output: True
19 | print(isinstance(c, complex))
20 |
21 |
22 |
23 | #Python provides operations involving fractional numbers through its fractions module.
24 |
25 | #A fraction has a numerator and a denominator, both of which are integers. This module has support for rational number arithmetic. We can create Fraction objects in various ways.
26 |
27 | import fractions
28 |
29 | # Output: 3/2
30 | print(fractions.Fraction(1.5))
31 |
32 | # Output: 5
33 | print(fractions.Fraction(5))
34 |
35 | # Output: 1/3
36 | print(fractions.Fraction(1,3))
37 |
38 |
39 | #While creating Fraction from float, we might get some unusual results. This is due to the imperfect binary floating point number representation as discussed in the previous section.Fortunately, Fraction allows us to instantiate with string as well. This is the preferred options when using decimal numbers.
40 |
41 | import fractions
42 |
43 | # As float
44 | # Output: 2476979795053773/2251799813685248
45 | print(fractions.Fraction(1.1))
46 |
47 | # As string
48 | # Output: 11/10
49 | print(fractions.Fraction('1.1'))
50 |
51 |
52 | #This datatype supports all basic operations. Here are few examples.
53 |
54 | from fractions import Fraction as F
55 |
56 | # Output: 2/3
57 | print(F(1,3) + F(1,3))
58 |
59 | # Output: 6/5
60 | print(1 / F(5,6))
61 |
62 | # Output: False
63 | print(F(-3,10) > 0)
64 |
65 | # Output: True
66 | print(F(-3,10) < 0)
67 |
68 |
69 |
70 |
71 | #Python offers modules like math and random to carry out different mathematics like trigonometry, logarithms, probability and statistics
72 |
73 |
74 | import math
75 |
76 | # Output: 3.141592653589793
77 | print(math.pi)
78 |
79 | # Output: -1.0
80 | print(math.cos(math.pi))
81 |
82 | # Output: 22026.465794806718
83 | print(math.exp(10))
84 |
85 | # Output: 3.0
86 | print(math.log10(1000))
87 |
88 | # Output: 1.1752011936438014
89 | print(math.sinh(1))
90 |
91 | # Output: 720
92 | print(math.factorial(6))
93 |
94 | ##Full list of functions available in python
95 |
96 | import random
97 |
98 | # Output: 16
99 | print(random.randrange(10,20))
100 |
101 | x = ['a', 'b', 'c', 'd', 'e']
102 |
103 | # Get random choice
104 | print(random.choice(x))
105 |
106 | # Shuffle x
107 | random.shuffle(x)
108 |
109 | # Print the shuffled x
110 | print(x)
111 |
112 | # Print random element
113 | print(random.random())
114 |
--------------------------------------------------------------------------------
/datatypes/examples/dict.py:
--------------------------------------------------------------------------------
1 | #Examples for dictionary
2 |
3 | #DEFINING DICTIONARY
4 | #by-default
5 | d = {
6 | 'City': 'Vellore',
7 | 'State': 'Tamil Nadu',
8 | 'Country': 'India',
9 | 'Continent': 'Asia'
10 | }
11 |
12 | #defining as a list of tuples
13 | d = dict([
14 | ('City', 'Vellore'),
15 | ('State', 'Tamil Nadu'),
16 | ('Country', 'India'),
17 | ('Continent', 'Asia')
18 | ])
19 |
20 | #as keyword arguments
21 | d = dict(
22 | City = 'Vellore',
23 | State = 'Tamil Nadu',
24 | Country = 'India',
25 | Continent = 'Asia'
26 | )
27 | ##ACCESSING VALUES
28 | d['City'] #gives you 'Vellore'
29 |
30 | #updating
31 | d['City'] = 'Chennai' #changes the value of key 'City' to 'Chennai'
32 |
33 | d['Gallaxy'] = 'Milky-Way Gallaxy' #adds a new key-value pair
34 |
35 | #deleting
36 | del d['Country'] #deletes the instance of key-value pair from d of key 'Chennai'
37 |
38 | d.pop('Country') #also returns the value of deleted key-value pair
39 |
40 | d.popitem() #removes the last item in the dictionary d
41 | ##USEFUL FUNCTIONS
42 | #clear
43 | d.clear() #empties the dictionary
44 |
45 | #update
46 | d.update({'Planet':'Earth'})
47 | '''This command adds an extra key-value pair to the dictionary
48 | It is analogous to "append" function for list.
49 | We can add any number of key-value pairs using update'''
50 |
51 | d.keys()
52 | d.values()
53 | '''to get keys and values
54 | Gives a list of keys and values in a dictionary'''
55 |
56 | d.items() #to get both keys and values
57 |
--------------------------------------------------------------------------------
/datatypes/examples/list.py:
--------------------------------------------------------------------------------
1 | #empty list
2 | my_list=[]
3 | #list of integers
4 | integers = [1,2,3]
5 | #list with mixed datatypes
6 | mixed = [1,"Hello",2.0]
7 | #nested list
8 | nested = [1,[1,2,3],3]
9 |
10 | print(integers[0]) # prints 1
11 |
12 | print(nested[1][1]) #prints 2
13 |
14 | print(integers[-1]) #prints 3
15 |
16 | my_list = ['h','e','l','l','o']
17 | # elements 3rd to 5th
18 | print(my_list[2:4])
19 |
20 | # elements beginning to 3rd
21 | print(my_list[:-2])
22 |
23 | # elements 3rd to end
24 | print(my_list[2:])
25 |
26 | # elements beginning to end
27 | print(my_list[:])
28 |
29 | odd = [2, 4, 6, 8]
30 |
31 | # change the 1st item
32 | odd[0] = 1
33 | # Output: [1, 4, 6, 8]
34 |
35 | print(odd)
36 |
37 | # change 2nd to 4th items
38 | odd[1:4] = [3, 5, 7]
39 | # Output: [1, 3, 5, 7]
40 |
41 | odd.append(9) #adds 9 at the end
42 |
43 | odd.extend([11,13]) # output : [1,3,5,7,9,11,13]
44 |
45 | print(odd + [15,17]) # we canalso use + to add the lists and it is known as concatenation
46 | # output [1,3,5,7,9,11,13,15,17]
47 |
48 | del odd[2] #deletes 5
49 |
50 | del odd[1:5] #delets multiple items
51 |
52 | del odd # deletes the list
53 |
54 | print(odd) #this gives an error
55 |
56 | my_list.remove('h') #removes 'h'
57 |
58 | my_list.pop(1) #deletes the element at the index 1
59 |
60 | my_list.pop() #deletes the element which is in the ending
61 |
62 | #defining my_list again
63 | my_list = [3, 8, 1, 6, 0, 8, 4]
64 |
65 | # Output: 1
66 | print(my_list.index(8)) #gives the index of the first occurence of 8
67 |
68 | # Output: 2
69 | print(my_list.count(8)) #counts the number of times 8 comes in the list
70 |
71 | my_list.sort() # sorts the list in ascending order
72 |
73 | # Output: [0, 1, 3, 4, 6, 8, 8]
74 | print(my_list)
75 |
76 | my_list.reverse() #reverses the given list
77 |
78 | # Output: [8, 8, 6, 4, 3, 1, 0]
79 | print(my_list)
80 |
81 | pow2 = [2 ** x for x in range(10)] #list comprehension is used to create a list
82 |
83 | # Output: [1, 2, 4, 8, 16, 32, 64, 128, 256, 512]
84 | print(pow2)
85 |
86 | new_list = [x+y for x in ['Python ','C '] for y in ['Language','Programming']]
87 |
88 | print(new_list)
89 | #output is ['Python Language','Python Programming','C Language','C Programming]
--------------------------------------------------------------------------------
/datatypes/examples/sets.py:
--------------------------------------------------------------------------------
1 | # initialize my_set
2 | my_set = {1,3}
3 | print(my_set)
4 | # add an element
5 | # Output: {1, 2, 3}
6 | my_set.add(2)
7 | print(my_set)
8 | # add multiple elements
9 | # Output: {1, 2, 3, 4}
10 | my_set.update([2,3,4])
11 | print(my_set)
12 | # discard an element
13 | # Output: {1, 2, 3}
14 | my_set.discard(4)
15 | print(my_set)
16 | # clear my_set
17 | #Output: set()
18 | my_set.clear()
19 | print(my_set)
20 | # initialize A and B
21 | A = {1, 2, 3, 4, 5}
22 | B = {4, 5, 6, 7, 8}
23 | # union of sets
24 | # Output: {1, 2, 3, 4, 5, 6, 7, 8}
25 | print(A | B)
26 | A.union(B)
27 | # Output: {1, 2, 3, 4, 5, 6, 7, 8}
28 | # intersection of sets
29 | # Output: {4, 5}
30 | print(A & B)
31 | A.intersection(B)
32 | #Output: {4, 5}
33 | # difference of sets
34 | # Output: {1, 2, 3}
35 | print(A - B)
36 | A.difference(B)
37 | # Output: {1, 2, 3}
38 | # initialize A and B frozen sets
39 | A = frozenset([1, 2, 3, 4])
40 | B = frozenset([3, 4, 5, 6])
41 | # operations on frozen sets
42 | A.isdisjoint(B)
43 | # Output: False
44 | A.difference(B)
45 | # Output: frozenset({1, 2})
46 | A | B
47 | # Output: frozenset({1, 2, 3, 4, 5, 6})
48 | A.add(3)
49 | # Output: will show error "AttributeError: 'frozenset' object has no attribute 'add'"
50 |
--------------------------------------------------------------------------------
/datatypes/examples/string.py:
--------------------------------------------------------------------------------
1 | # Python Strings Examples
2 |
3 | # capitalize
4 | str = "this is string example....wow!!!";
5 | print "str.capitalize() : ", str.capitalize()
6 |
7 | str.capitalize() : This is string example....wow!!!
8 |
9 | #count
10 | str = "this is string example....wow!!!";
11 | sub = "i";
12 | print "str.count(sub, 4, 40) : ", str.count(sub, 4, 40)
13 | sub = "wow";
14 | print "str.count(sub) : ", str.count(sub)
15 |
16 | str.count(sub, 4, 40) : 2
17 | str.count(sub) : 1
18 |
19 | #endswith
20 | str = "this is string example....wow!!!";
21 | suffix = "wow!!!";
22 | print str.endswith(suffix)
23 | print str.endswith(suffix,20)
24 | suffix = "is";
25 | print str.endswith(suffix, 2, 4)
26 | print str.endswith(suffix, 2, 6)
27 |
28 | True
29 | True
30 | True
31 | False
32 |
33 | #find
34 | str1 = "this is string example....wow!!!";
35 | str2 = "exam";
36 | print str1.find(str2)
37 | print str1.find(str2, 10)
38 | print str1.find(str2, 40)
39 |
40 | 15
41 | 15
42 | -1
43 |
44 | #isalnum
45 | str = "this2009"; # No space in this string
46 | print str.isalnum()
47 | str = "this is string example....wow!!!";
48 | print str.isalnum()
49 |
50 | True
51 | False
52 |
53 | #isalpha
54 | str = "this"; # No space & digit in this string
55 | print str.isalpha()
56 | str = "this is string example....wow!!!";
57 | print str.isalpha()
58 |
59 | True
60 | False
61 |
62 | #isdigit
63 | str = "123456"; # Only digit in this string
64 | print str.isdigit()
65 | str = "this is string example....wow!!!";
66 | print str.isdigit()
67 |
68 | True
69 | False
70 |
71 | #islower
72 | str = "THIS is string example....wow!!!";
73 | print str.islower()
74 | str = "this is string example....wow!!!";
75 | print str.islower()
76 |
77 | False
78 | True
79 |
80 | #isalnum
81 | str = u"this2009";
82 | print str.isnumeric()
83 | str = u"23443434";
84 | print str.isnumeric()
85 |
86 | False
87 | True
88 |
89 | #isupper
90 | str = "THIS IS STRING EXAMPLE....WOW!!!";
91 | print str.isupper()
92 | str = "THIS is string example....wow!!!";
93 | print str.isupper()
94 |
95 | True
96 | False
97 |
98 | #len
99 | str = "this is string example....wow!!!";
100 | print "Length of the string: ", len(str)
101 |
102 | Length of the string: 32
103 |
104 | #islower
105 | str = "THIS IS STRING EXAMPLE....WOW!!!";
106 | print str.lower()
107 |
108 | this is string example....wow!!!
109 |
110 | #strip
111 | str = "0000000this is string example....wow!!!0000000";
112 | print str.strip( '0' )
113 |
114 | this is string example....wow!!!
115 |
116 | #replace
117 | str = "this is string example....wow!!! this is really string"
118 | print str.replace("is", "was")
119 | print str.replace("is", "was", 3)
120 |
121 | thwas was string example....wow!!! thwas was really string
122 | thwas was string example....wow!!! thwas is really string
123 |
124 | #join
125 | s = "-";
126 | seq = ("a", "b", "c"); # This is sequence of strings.
127 | print s.join( seq )
128 |
129 | a-b-c
130 |
131 | #split
132 | str = "Line1-abcdef \nLine2-abc \nLine4-abcd";
133 | print str.split( )
134 | print str.split(' ', 1 )
135 |
136 | ['Line1-abcdef', 'Line2-abc', 'Line4-abcd']
137 | ['Line1-abcdef', '\nLine2-abc \nLine4-abcd']
--------------------------------------------------------------------------------
/datatypes/examples/tuples.py:
--------------------------------------------------------------------------------
1 | # Creating Tuples
2 |
3 | college=("VIT","DTU","IIT")
4 |
5 | # Another method for creating tuples
6 |
7 | Laptops=tuple(("Macbook-Air","Macbook-Pro","HP-Pavillion"))
8 | print(Laptops)
9 | #This will print the Laptops tuple
10 |
11 | # Accessing Tuples
12 | ACM_WEB=("Aditya","Shubham","Rakshit")
13 | print(ACM_WEB[0])
14 | #This will print Aditya
15 |
16 | # Immutablity of Tuples
17 | #**Example1**
18 |
19 | ACM_WEB=("Aditya","Shubham","Rakshit")
20 | ACM_WEB[0]="Shivank"
21 | print(ACM_WEB)
22 | #This will still print the original tuple
23 |
24 | #**Example2**
25 | pokemon=("Pickachu","Charizard","Blastoise")
26 | pokemon[3]="Mr.Mime"
27 | #This will raise an error
28 | print(pokemon)
29 |
30 | # Looping Through a Tuple
31 | sports=("Cricket","Football","Basketball")
32 | for x in sports:
33 | print(x)
34 |
35 | # Calculating Tuple Length
36 | pokemon=("Pickachu","Charizard","Blastoise")
37 | pokemon[3]="Mr.Mime"
38 | #This will raise an error
39 | print(pokemon)
40 |
41 | # Deleting Tuple
42 | pokemon=("Pickachu","Charizard","Blastoise")
43 | del pokemon
44 | #This will delete the Tuple
45 |
46 | # count() method of tuples
47 |
48 | # vowels tuple
49 | vowels = ('a', 'e', 'i', 'o', 'i', 'o', 'e', 'i', 'u')
50 |
51 | # count element 'i'
52 | count = vowels.count('i')
53 | #The ouput will be :3
54 |
55 | # index() method of tuples
56 |
57 | # vowels tuple
58 | vowels = ('a', 'e', 'i', 'o', 'i', 'u')
59 |
60 | # element 'e' is searched
61 | index = vowels.index('e')
62 |
63 | # index is printed
64 | print('The index of e:', index)
65 |
66 | # element 'i' is searched
67 | index = vowels.index('i')
68 |
69 | # only the first index of the element is printed
70 | print('The index of i:', index)
71 |
--------------------------------------------------------------------------------
/datatypes/list.md:
--------------------------------------------------------------------------------
1 | # LIST
2 |
3 | ## What is list?
4 |
5 | * It is the most versatile datatype in python. It includes comma separated values that are enclosed in square brackets. List is a type of mutable sequence in python.
6 |
7 | * Every element in the list is assigned a number i.e. index/position starting from 0.
8 |
9 | * We can perform slicing, indexing, adding, multiplying and other functions on list.
10 |
11 | * The items in the list need not be of same type.
12 |
13 | ### Creating an empty list:
14 |
15 | list_name = []
16 |
17 | Example:
18 | Mybooks = []
19 | L1 = []
20 |
21 | ### Creating a list with items:
22 |
23 | Listname = [item1, item2, item3]
24 |
25 | Example :
26 | L2 = [1,2,3,4,5]
27 | S = [‘15BIT001’, ‘XYZ’, 99.9] #shows that the items need not be of the same type.
28 |
29 | ### Accessing Values in the list
30 |
31 | We can use the index operator [] to access an item in a list. Index starts from 0. So, a list having 5 elements will have index from 0 to 4.
32 |
33 | Like L1[3] points to the 4th element from left in L1.
34 |
35 | Python also allows negative indexing for its sequences. The index of -1 refers to the last item, -2 to the second last item and so on.
36 |
37 |
38 | ### Slicing lists in Python
39 |
40 | We can access a range of items in a list by using the slicing operator (colon). If we want to access a range, we need two index that will slice that portion from the list.
41 |
42 | ### How to change or add elements to a list?
43 |
44 | * We can use assignment operator (=) to change an item or a range of items.
45 |
46 | * We can add one item to a list using append() method or add several items using extend()method.
47 |
48 | * We can also use + operator to combine two lists. This is also called concatenation.(here,provided both the elements are lists)
49 |
50 | * The * operator repeats a list for the given number of times.
51 |
52 | * We can insert one item at a desired location by using the method insert() .
53 |
54 | * How to delete or remove elements from a list?
55 |
56 | * We can delete one or more items from a list using the keyword del. It can even delete the list entirely.
57 |
58 | * We can also delete items in a list by assigning an empty list to a slice of elements.
59 |
60 | * We can use remove() method to remove the given item or pop() method to remove an item at the given index.
61 |
62 | * The pop() method removes and returns the last item if index is not provided.
63 |
64 | ## Python List Methods
65 |
66 | Methods that are available with list object in Python programming are tabulated below.
67 | They are accessed as list.method(). Some of the methods have already been used above
68 |
69 | ### Python List Methods
70 |
71 | * append() - Add an element to the end of the list
72 |
73 | * extend() - Add all elements of a list to the another list
74 |
75 | * insert() - Insert an item at the defined index
76 |
77 | * remove() - Removes an item from the list
78 |
79 | * pop() - Removes and returns an element at the given index
80 |
81 | * clear() - Removes all items from the list
82 |
83 | * index() - Returns the index of the first matched item
84 |
85 | * count() - Returns the count of number of items passed as an argument
86 |
87 | * sort() - Sort items in a list in ascending order
88 |
89 | * reverse() - Reverse the order of items in the list
90 |
91 | * copy() - Returns a shallow copy of the lis
92 |
93 |
94 | ## Built-in Functions with List
95 |
96 | Built-in functions are used with list to perform different tasks.
97 |
98 | Function|Description
99 | --------|-----------
100 | all()|Return True if all elements of the list are true (or if the list is empty).
101 | any()|Return True if any element of the list is true. If the list is empty, return False.
102 | enumerate()|Return an enumerate object. It contains the index and value of all the items of list as a tuple.
103 | len()|Return the length (the number of items) in the list.
104 | list()|Convert an iterable (tuple, string, set, dictionary) to a list.
105 | max()|Return the largest item in the list.
106 | min()|Return the smallest item in the list
107 | sorted()|Return a new sorted list (does not sort the list itself).
108 | sum()|Return the sum of all elements in the list.
109 |
110 | ## List Comprehension
111 |
112 | List comprehension consists of an expression followed by ‘for statement’ inside square brackets.
113 |
114 | A list comprehension can optionally contain more ‘for’ or ‘if statements’. An optional ’if statement’ can filter out items for the new list.
115 |
116 | The list comprehensions are easy to code and likely to run faster than the conventional methods of creating lists.
117 |
118 | You can read more about lists on:
119 | https://www.geeksforgeeks.org/python-list/
120 | https://www.tutorialspoint.com/python/python_lists.htm
121 |
122 |
--------------------------------------------------------------------------------
/datatypes/numbers.md:
--------------------------------------------------------------------------------
1 |
2 | # Numbers
3 |
4 | Number data types store numeric values. They are immutable data types, means that changing the value of a number data type results in a newly allocated object.
5 |
6 | Number objects are created when you assign a value to them. For example −
7 |
8 | var1 = 1
9 |
10 | var2 = 10
11 |
12 | You can also delete the reference to a number object by using the **del** statement. The syntax of the del statement is −
13 |
14 | del var1[,var2[,var3[....,varN]]]]
15 |
16 | You can delete a single object or multiple objects by using the **del** statement. For example −
17 |
18 | del var
19 |
20 | del var\_a, var\_b
21 |
22 | Python supports four different numerical types −
23 |
24 | - **int (signed integers)** − They are often called just integers or ints, are positive or negative whole numbers with no decimal point.
25 | - **long (long integers )** − Also called longs, they are integers of unlimited size, written like integers and followed by an uppercase or lowercase L.
26 | - **float (floating point real values)** − Also called floats, they represent real numbers and are written with a decimal point dividing the integer and fractional parts. Floats may also be in scientific notation, with E or e indicating the power of 10 (2.5e2 = 2.5 x 102 = 250).
27 | - **complex (complex numbers)** − are of the form a + bJ, where a and b are floats and J (or j) represents the square root of -1 (which is an imaginary number). The real part of the number is a, and the imaginary part is b. Complex numbers are not used much in Python programming.
28 |
29 | ### Examples
30 |
31 | Here are some examples of numbers
32 |
33 | | **int** | **long** | **float** | **complex** |
34 | | --- | --- | --- | --- |
35 | | 10 | 51924361L | 0.0 | 3.14j |
36 | | 100 | -0x19323L | 15.20 | 45.j |
37 | | -786 | 0122L | -21.9 | 9.322e-36j |
38 | | 080 | 0xDEFABCECBDAECBFBAEL | 32.3+e18 | .876j |
39 | | -0490 | 535633629843L | -90. | -.6545+0J |
40 | | -0x260 | -052318172735L | -32.54e100 | 3e+26J |
41 | | 0x69 | -4721885298529L | 70.2-E12 | 4.53e-7j |
42 |
43 | - Python allows you to use a lowercase L with long, but it is recommended that you use only an uppercase L to avoid confusion with the number 1. Python displays long integers with an uppercase L.
44 | - A complex number consists of an ordered pair of real floating point numbers denoted by a + bj, where a is the real part and b is the imaginary part of the complex number.
45 |
46 | ##
47 | # Number Type Conversion
48 |
49 | Python converts numbers internally in an expression containing mixed types to a common type for evaluation. But sometimes, you need to coerce a number explicitly from one type to another to satisfy the requirements of an operator or function parameter.
50 |
51 | - Type **int(x)** to convert x to a plain integer.
52 | - Type **long(x)** to convert x to a long integer.
53 | - Type **float(x)** to convert x to a floating-point number.
54 | - Type **complex(x)** to convert x to a complex number with real part x and imaginary part zero.
55 | - Type **complex(x, y)** to convert x and y to a complex number with real part x and imaginary part y. x and y are numeric expressions
56 |
57 | ##
58 | # Mathematical Functions
59 |
60 | Python includes following functions that perform mathematical calculations.
61 |
62 | | **Sr.No.** | **Function & Returns ( description )** |
63 | | --- | --- |
64 | | 1 | [**abs(x)**](https://www.tutorialspoint.com/python/number_abs.htm)The absolute value of x: the (positive) distance between x and zero. |
65 | | 2 | [**ceil(x)**](https://www.tutorialspoint.com/python/number_ceil.htm)The ceiling of x: the smallest integer not less than x |
66 | | 3 | [**cmp(x, y)**](https://www.tutorialspoint.com/python/number_cmp.htm)-1 if x \< y, 0 if x == y, or 1 if x \> y |
67 | | 4 | [**exp(x)**](https://www.tutorialspoint.com/python/number_exp.htm)The exponential of x: ex |
68 | | 5 | [**fabs(x)**](https://www.tutorialspoint.com/python/number_fabs.htm)The absolute value of x. |
69 | | 6 | [**floor(x)**](https://www.tutorialspoint.com/python/number_floor.htm)The floor of x: the largest integer not greater than x |
70 | | 7 | [**log(x)**](https://www.tutorialspoint.com/python/number_log.htm)The natural logarithm of x, for x\> 0 |
71 | | 8 | [**log10(x)**](https://www.tutorialspoint.com/python/number_log10.htm)The base-10 logarithm of x for x\> 0. |
72 | | 9 | [**max(x1, x2,...)**](https://www.tutorialspoint.com/python/number_max.htm)The largest of its arguments: the value closest to positive infinity |
73 | | 10 | [**min(x1, x2,...)**](https://www.tutorialspoint.com/python/number_min.htm)The smallest of its arguments: the value closest to negative infinity |
74 | | 11 | [**modf(x)**](https://www.tutorialspoint.com/python/number_modf.htm)The fractional and integer parts of x in a two-item tuple. Both parts have the same sign as x. The integer part is returned as a float. |
75 | | 12 | [**pow(x, y)**](https://www.tutorialspoint.com/python/number_pow.htm)The value of x\*\*y. |
76 | | 13 | [**round(x [,n])**](https://www.tutorialspoint.com/python/number_round.htm) **x** rounded to n digits from the decimal point. Python rounds away from zero as a tie-breaker: round(0.5) is 1.0 and round(-0.5) is -1.0. |
77 | | 14 | [**sqrt(x)**](https://www.tutorialspoint.com/python/number_sqrt.htm)The square root of x for x \> 0 |
78 |
79 | ##
80 | # Random Number Functions
81 |
82 | Random numbers are used for games, simulations, testing, security, and privacy applications. Python includes following functions that are commonly used.
83 |
84 | | **Sr.No.** | **Function & Description** |
85 | | --- | --- |
86 | | 1 | [**choice(seq)**](https://www.tutorialspoint.com/python/number_choice.htm)A random item from a list, tuple, or string. |
87 | | 2 | [**randrange ([start,] stop [,step])**](https://www.tutorialspoint.com/python/number_randrange.htm)A randomly selected element from range(start, stop, step) |
88 | | 3 | [**random()**](https://www.tutorialspoint.com/python/number_random.htm)A random float r, such that 0 is less than or equal to r and r is less than 1 |
89 | | 4 | [**seed([x])**](https://www.tutorialspoint.com/python/number_seed.htm)Sets the integer starting value used in generating random numbers. Call this function before calling any other random module function. Returns None. |
90 | | 5 | [**shuffle(lst)**](https://www.tutorialspoint.com/python/number_shuffle.htm)Randomizes the items of a list in place. Returns None. |
91 | | 6 | [**uniform(x, y)**](https://www.tutorialspoint.com/python/number_uniform.htm)A random float r, such that x is less than or equal to r and r is less than y |
92 |
93 | ##
94 | # Trigonometric Functions
95 |
96 | Python includes following functions that perform trigonometric calculations.
97 |
98 | | **Sr.No.** | **Function & Description** |
99 | | --- | --- |
100 | | 1 | [**acos(x)**](https://www.tutorialspoint.com/python/number_acos.htm)Return the arc cosine of x, in radians. |
101 | | 2 | [**asin(x)**](https://www.tutorialspoint.com/python/number_asin.htm)Return the arc sine of x, in radians. |
102 | | 3 | [**atan(x)**](https://www.tutorialspoint.com/python/number_atan.htm)Return the arc tangent of x, in radians. |
103 | | 4 | [**atan2(y, x)**](https://www.tutorialspoint.com/python/number_atan2.htm)Return atan(y / x), in radians. |
104 | | 5 | [**cos(x)**](https://www.tutorialspoint.com/python/number_cos.htm)Return the cosine of x radians. |
105 | | 6 | [**hypot(x, y)**](https://www.tutorialspoint.com/python/number_hypot.htm)Return the Euclidean norm, sqrt(x\*x + y\*y). |
106 | | 7 | [**sin(x)**](https://www.tutorialspoint.com/python/number_sin.htm)Return the sine of x radians. |
107 | | 8 | [**tan(x)**](https://www.tutorialspoint.com/python/number_tan.htm)Return the tangent of x radians. |
108 | | 9 | [**degrees(x)**](https://www.tutorialspoint.com/python/number_degrees.htm)Converts angle x from radians to degrees. |
109 | | 10 | [**radians(x)**](https://www.tutorialspoint.com/python/number_radians.htm)Converts angle x from degrees to radians. |
110 |
111 | ##
112 | # Mathematical Constants
113 |
114 | The module also defines two mathematical constants −
115 |
116 | | **Sr.No.** | **Constants & Description** |
117 | | --- | --- |
118 | | 1 | **pi** The mathematical constant pi. |
119 | | 2 | **e** The mathematical constant e. |
--------------------------------------------------------------------------------
/datatypes/sets.md:
--------------------------------------------------------------------------------
1 | # SETS
2 |
3 | **What are sets?**
4 |
5 | Set is an unordered collection of unique items. Set is defined by values separated by comma inside braces { }. Items in a set are not ordered.
6 |
7 | **Why use sets?**
8 |
9 | Set have unique values. They eliminate duplicates. Python’s set class represents the mathematical notion of a set. The elements in the set are immutable(cannot be modified) but the set as a whole is mutable. The major advantage of using a set, as opposed to a list, is that it has a highly optimized method for checking whether a specific element is contained in the set.
10 |
11 | **Python Frozenset**
12 |
13 | Frozenset is a new class that has the characteristics of a set, but its elements cannot be changed once assigned. This datatype supports methods like difference(), intersection(), union(), etc. Being immutable it does not have method that add or remove elements.
14 |
15 | ## Methods for Sets
16 |
17 | **1. add(x) and update(x) Method:**
18 |
19 | We can add single element using the add() method and multiple elements using the update()method. The update() method can take tuples, lists, strings or other sets as its argument.
20 |
21 | Eg.people = {"Jay", "Idrish", "Archil"}
22 | people.add("Daxit")
23 |
24 | **2. union(s) Method:**
25 |
26 | Returns a union of two set.Using the ‘|’ operator between 2 sets is the same as writing set1.union(set2)
27 | Eg.
28 | people = {"Jay", "Idrish", "Archil"}
29 | vampires = {"Karan", "Arjun"}
30 | population = people.union(vampires)
31 | you could also use
32 | population = people|vampires
33 |
34 | **3.intersect(s) Method:**
35 |
36 | Returns an intersection of two sets.The ‘&’ operator can also be used in this case.
37 | victims = people.intersection(vampires)
38 | you could also use
39 | victims=people & vampires
40 |
41 | **4. difference(s) Method:**
42 |
43 | Returns a set containing all the elements of invoking set but not of the second set. We can use ‘-‘ operator here.
44 | safe = people.difference(vampires)
45 | you can also use
46 | safe= people – vampires
47 |
48 | **5. clear() Method:**
49 |
50 | Empties the whole set.
51 | victims.clear()
52 |
53 | **Sets and frozen sets support the following operators:**
54 |
55 | key in s #containment check
56 |
57 | key not in s #non-containment check
58 |
59 | s1 == s2 #s1 is equivalent to s2
60 |
61 | s1 != s2 #s1 is not equivalent to s2
62 |
63 | s1 <= s2 #s1is subset of s2 s1 < s2 # s1 is proper subset of s2 s1 >= s2 # s1is superset of s2
64 |
65 | s1 > s2 #s1 is proper superset of s2
66 |
67 | s1 | s2 #the union of s1 and s2
68 |
69 | s1 & s2 #the intersection of s1 and s2
70 |
71 | s1 – s2 #the set of elements in s1 but not s2
72 |
73 | s1 ˆ s2 #the set of elements in precisely one of s1 or s2
74 |
75 | ## Website refrences:
76 |
77 | https://www.programiz.com/python-programming/set
78 |
79 | https://www.geeksforgeeks.org/sets-in-python/
80 |
81 | https://www.learnpython.org/en/Sets
82 |
83 | ## Youtube refrences:
84 |
85 | https://www.youtube.com/watch?v=482kbk1x04w
86 |
87 | https://www.youtube.com/watch?v=sBvaPopWOmQ
88 |
89 | https://www.youtube.com/watch?v=yXIlZGX7Eqk
90 |
91 | https://www.youtube.com/watch?v=Nh6n_4RYcUg
--------------------------------------------------------------------------------
/datatypes/string.md:
--------------------------------------------------------------------------------
1 | # Python strings.
2 |
3 | * Python treats ' ' and " " same unlike c++
4 |
5 | * Does not support character type : characters are also stored treated as strings of length 1
6 |
7 | * Accessing substring and concatenating it with another string
8 |
9 | * var = "Pyflask"
10 | var1 = var [:2] + "thon"
11 | This initializez var1 with the value as "python" . (Note [:2] means starting from the first position (0th index) and terminating before 3rd element (2nd index) )
12 | * x var[1:2] , var[5:10] ?
13 |
14 | * escape charaters maybe used
15 |
16 | * non printable characters that can be represented by backslash notation
17 | * Eg: "\a", "\b" etc.
18 |
19 | * Built in string methods
20 |
21 | * str.capitalize ():
22 | > Capitalizes first letter of string
23 | * str.count(substr,start_index,end_index_optional):
24 | >Counts how many times str occurs in string or in a substring of string if starting index beg and ending index end are given.
25 | * str.endswith(substr):
26 | >Determines if string or a substring of string (if starting index beg and ending index end are given) ends with suffix; returns true if so and false otherwise.
27 | * str.find(str,start_index,end_index):
28 | >Determine if str occurs in string or in a substring of string if starting index beg and ending index end are given returns index if found and -1 otherwise.
29 | * str.isalnum():
30 | >Returns true if string has at least 1 character and all characters are alphanumeric and false otherwise.
31 | * str.isalpha():
32 | >Returns true if string has at least 1 character and all characters are alphabetic and false otherwise.
33 | * str.isdigit():
34 | >Returns true if string contains only digits and false otherwise.
35 | * str.islower():
36 | >Returns true if string has at least 1 cased character and all cased characters are in lowercase and false otherwise.
37 | * str.isnumeric():
38 | >Returns true if a unicode string contains only numeric characters and false otherwise.
39 | * str.isupper():
40 | >Returns true if string has at least one cased character and all cased characters are in uppercase and false otherwise.
41 | * len(str):
42 | >Returns the length of the string
43 | * str.lower():
44 | >Converts all uppercase letters in string to lowercase.
45 | * str.strip():
46 | >Performs both left strip and right strip on string.
47 | * str.replace(old_str, new_str)
48 | >Replaces all occurrences of old in string with new or at most max occurrences if max given.
49 | * str.join(str):
50 | >Merges (concatenates) the string representations of elements in sequence seq into a string, with separator string.
51 | * str.split():
52 | >Splits string according to delimiter str (space if not provided) and returns list of substrings; split into at most num substrings if given.
53 |
54 |
55 | # References
56 |
57 | https://www.tutorialspoint.com/python3/python_strings.htm
58 | https://docs.python.org/3/tutorial/introduction.html#strings
59 |
--------------------------------------------------------------------------------
/datatypes/tuples.md:
--------------------------------------------------------------------------------
1 | # TUPLES
2 |
3 | ## Definition And Creating Tuples
4 |
5 | A tuple is a collection which is ordered and unchangeable. In Python tuples are written with round brackets.
6 |
7 | For example:-
8 | ```python
9 | college=("VIT","DTU","IIT")
10 | ```
11 | ### Another method for creating tuples:-
12 | ```python
13 | Laptops=tuple(("Macbook-Air","Macbook-Pro","HP-Pavillion"))
14 | print(Laptops)
15 | #This will print the Laptops tuple
16 | ```
17 | ## Accessing Tuples
18 |
19 | Accessing tuples is quite easy .We just need to make use of the index number of the item
20 |
21 | For example:-
22 | ```python
23 | ACM_WEB=("Aditya","Shubham","Rakshit")
24 | print(ACM_WEB[0])
25 | #This will print Aditya
26 | ```
27 |
28 | #### NOTE:- Tuples are immutable.Once you create a tuple, you can't change it.
29 |
30 | For example:-
31 | ```python
32 | ACM_WEB=("Aditya","Shubham","Rakshit")
33 | ACM_WEB[0]="Shivank"
34 | print(ACM_WEB)
35 | #This will still print the original tuple
36 | ```
37 | #### The value will remain the same
38 |
39 | ## Looping Through a Tuple
40 |
41 | A simple way to loop through a tuple is using a for loop
42 |
43 | For example:-
44 | ```python
45 | sports=("Cricket","Football","Basketball")
46 | for x in sports:
47 | print(x)
48 | ```
49 | ## Adding Items to Tuples
50 |
51 | It is really important to know that we cannot add items to a tuple once we create it
52 |
53 | For Example:-
54 | ```python
55 | pokemon=("Pickachu","Charizard","Blastoise")
56 | pokemon[3]="Mr.Mime"
57 | #This will raise an error
58 | print(pokemon)
59 | ```
60 | ## Calculating Tuple Length
61 |
62 | We make use of the len() method
63 |
64 | For Example:-
65 | ```python
66 | pokemon=("Pickachu","Charizard","Blastoise")
67 | print(len(pokemon))
68 | #It will print 3
69 | ```
70 | ## Removing Items from a Tuple
71 |
72 | You cannot remove items from a tuple but you can delete the tuple itself.
73 |
74 | For Example:-
75 | ```python
76 | pokemon=("Pickachu","Charizard","Blastoise")
77 | del pokemon
78 | #This will delete the tuple
79 | ```
80 | ## Tuple Methods
81 |
82 | Python has a few builtin methods for tuples such as
83 | **count()**
84 | It basically returns count of an item in a tuple
85 | for example:-
86 | ```python
87 | # vowels tuple
88 | vowels = ('a', 'e', 'i', 'o', 'i', 'o', 'e', 'i', 'u')
89 |
90 | # count element 'i'
91 | count = vowels.count('i')
92 |
93 | ```
94 | **index()**
95 | Searches the tuple for a specified value and returns the position of where it was found
96 | ```python
97 | # vowels tuple
98 | vowels = ('a', 'e', 'i', 'o', 'i', 'u')
99 |
100 | # element 'e' is searched
101 | index = vowels.index('e')
102 |
103 | # index is printed
104 | print('The index of e:', index)
105 |
106 | # element 'i' is searched
107 | index = vowels.index('i')
108 |
109 | # only the first index of the element is printed
110 | print('The index of i:', index)
111 | ```
112 | *The output for this piece of code will be*:-
113 |
114 | The index of e: 1
115 | The index of i: 2
116 |
117 | For Further references :-
118 | https://www.youtube.com/watch?v=NI26dqhs2Rk
119 |
--------------------------------------------------------------------------------
/filehandling/README.md:
--------------------------------------------------------------------------------
1 | # FILE-HANDLING
2 |
3 | Python supports file handling and allows users to handle files i.e., to read and write files, along with many other file handling options, to operate on files. The concept of file handling has stretched over various other languages, but the implementation is either complicated or lengthy, but alike other concepts of Python, this concept here is also easy and short. Python treats file differently as text or binary and this is important. Each line of code includes a sequence of characters and they form text file. Each line of a file is terminated with a special character, called the EOL or End of Line characters like comma {,} or newline character. It ends the current line and tells the interpreter a new one has begun. Let’s see how to read and write files.
4 |
5 | ## open() function
6 |
7 | We use open () function in Python to open a file in read or write mode. As explained above, open ( ) will return a file object. To return a file object we use open() function along with two arguments, that accepts file name and the mode, whether to read or write. So, the syntax being: open(filename, mode). There are three kinds of mode, that Python provides and how files can be opened:
8 |
9 | * “ r “, for reading.
10 |
11 | * “ w “, for writing.
12 |
13 | * “ a “, for appending.
14 |
15 | * “ r+ “, for both reading and writing.
16 |
17 | The mode argument is not mandatory. If not passed, then Python will assume it to be “ r ” by default. Let’s look at this program and try to analyze how the read mode works:
18 |
19 | ```python
20 | # a file named "hello", will be opened with the reading mode.
21 | file = open('hello.txt', 'r')
22 | # This will print every line one by one in the file
23 | for each in file:
24 | print (each)
25 | ```
26 |
27 | There is more than one way to read a file in Python. If you need to extract a string that contains all characters in the file then we can use file.read(). The full code would work like this:
28 | ```python
29 | # Python code to illustrate read() mode
30 | file = open(“file.text”, “r”)
31 | print file.read()
32 | ```
33 |
34 | ## write() function
35 |
36 | Let’s see how to create a file and how write mode works:
37 | To manipulate the file, write the following in your Python environment:
38 |
39 | ```python
40 | # Python code to create a file
41 | file = open('hello.txt','w')
42 | file.write("This is the write command")
43 | file.write("It allows us to write in a particular file")
44 | file.close()
45 | ```
46 |
47 | The close() command terminates all the resources in use and frees the system of this particular program.
48 |
49 | ## append() mode
50 |
51 | Let’s see how the append mode works:
52 |
53 | ```python
54 | # Python code to illustrate append() mode
55 | file = open('geek.txt','a')
56 | file.write("This will add this line")
57 | file.close()
58 | ```
59 |
60 | There are also various other commands in file handling that is used to handle various tasks like:
61 |
62 | * rstrip(): This function strips each line of a file off spaces from the right-hand side.
63 | * lstrip(): This function strips each line of a file off spaces from the left-hand side.
64 |
65 | It is designed to provide much cleaner syntax and exceptions handling when you are working with code. That explains why it’s good practice to use them with a statement where applicable. This is helpful because using this method any files opened will be closed automatically after one is done, so auto-cleanup.
66 | Example:
67 |
68 | ```python
69 | # Python code to illustrate with()
70 | with open(“file.txt”) as file:
71 | data = file.read()
72 | # do something with data
73 | ```
74 |
75 | ## with() function
76 |
77 | We can also use write function along with with() function:
78 |
79 | ```python
80 | # Python code to illustrate with() alongwith write()
81 | with open(“file.txt”, “w”) as f:
82 | f.write(“Hello World!!!”)
83 | ```
84 |
85 | ## split() function
86 |
87 | We can also split lines using file handling in Python. This splits the variable when space is encountered. You can also split using any characters as we wish. Here is the code:
88 |
89 | ```python
90 | # Python code to illustrate split() function
91 | with open(“file.text”, “r”) as file:
92 | data = file.readlines()
93 | for line in data:
94 | word = line.split()
95 | print word
96 | ```
97 |
98 |
99 | To know more about File handling:
100 |
101 | https://www.geeksforgeeks.org/file-handling-python/
102 |
103 | https://www.pythonforbeginners.com/files/reading-and-writing-files-in-python
104 |
105 | https://www.w3schools.com/python/python_file_handling.asp
106 |
107 |
108 |
109 |
--------------------------------------------------------------------------------
/flask/README.md:
--------------------------------------------------------------------------------
1 | # Flask
2 |
3 | Flask is a web framework for python, which offers you certain functions to operate or deliver data over the web. It is light weight and is very useful to get any app up and runing in no time.
4 |
5 | # Why Flask?
6 |
7 | Being light and utlizing speed of development in python, Flask is very usefu and efficient as well.
8 |
9 | # What are templates?
10 |
11 | While sending HTML as response from a request function from flask app, It is common to put dynamic data in that page, Say you need to show new posts which have been put in the database, You can generate the page dynamically by string formatiing and certain operators but using this apporach is highly inefficient and slows down the development curve,
12 |
13 | This is where templates come into picture, Basically you pass variables while rendering templates and write some python code to play with those variables, It eases the stuff down.
14 |
15 | # Lifting flask server
16 |
17 | ```python
18 | from flask import Flask
19 |
20 | app = Flask(__name__)
21 |
22 | app.run(host="0.0.0.0", port=3004)
23 | ```
24 |
25 | # Registering a route
26 |
27 | ```python
28 | from flask import Flask
29 |
30 | app = Flask(__name__)
31 |
32 | @app.route("/your/path")
33 | def routeFunc():
34 | return "Hello World", 200
35 |
36 | app.run(host="0.0.0.0", port=3004)
37 | ```
38 |
39 | # Using Templates
40 |
41 | Refer [example](./example)
42 |
43 | # References
44 |
45 | * https://pymbook.readthedocs.io/en/latest/flask.html
46 | * https://www.tutorialspoint.com/flask/
47 | * https://www.youtube.com/watch?v=zRwy8gtgJ1A
48 | * https://www.udemy.com/python-flask-tutorial-step-by-step/ (Free Course)
--------------------------------------------------------------------------------
/flask/example/app.py:
--------------------------------------------------------------------------------
1 | from flask import Flask, url_for, session, render_template, request, redirect
2 | import json
3 |
4 | app = Flask(__name__)
5 | app.secret_key = "PyFlask_2k18_1516"
6 |
7 | @app.route("/", methods = ["GET"])
8 | def index():
9 |
10 | if("loggedIn" in session.keys() and session["loggedIn"] == True):
11 | return redirect("/dashboard"), 302
12 |
13 | return render_template("index.html"), 200
14 |
15 | @app.route("/login", methods = ["POST"])
16 | def login():
17 | username = request.form["username"]
18 | password = request.form["password"]
19 |
20 | loginData = open("data/user.json", "r+")
21 | jsonData = loginData.read()
22 | loginData.close()
23 | print(jsonData)
24 |
25 | if jsonData is not "":
26 |
27 | dataDictionary = json.loads(jsonData)
28 | if username in dataDictionary.keys() and dataDictionary[username] == password:
29 | session["loggedIn"] = True
30 | session["username"] = username
31 | return redirect(url_for("dashboard"), 302)
32 |
33 | elif username in dataDictionary.keys() and dataDictionary[username] is not password:
34 | return render_template("index.html", message = "Invalid Username/Password", error = True)
35 |
36 | else:
37 | dataDictionary[username] = password
38 | loginData = open("data/user.json", "w+")
39 | loginData.write(json.dumps(dataDictionary))
40 | loginData.close()
41 | return render_template("index.html", message = "Successful Signup", error = False)
42 |
43 | else:
44 | jsonData = {username:password}
45 | loginData = open("data/user.json", "w+")
46 | loginData.write(json.dumps(jsonData))
47 | loginData.close()
48 | return render_template("index.html", message = "Successful Signup", error = False)
49 |
50 |
51 | @app.route("/dashboard", methods = ["GET"])
52 | def dashboard():
53 | if("loggedIn" in session.keys() and session["loggedIn"] is not True):
54 | return render_template("index.html", message = "Unauthorized", error = True), 401
55 | return render_template("dashboard.html")
56 |
57 | @app.route("/addnote", methods = ["POST"])
58 | def addnote():
59 | if("loggedIn" in session.keys() and session["loggedIn"] is not True):
60 | return render_template("index.html", message = "Unauthorized", error = True), 401
61 | title = request.form["title"]
62 | note = request.form["note"]
63 | username = session["username"]
64 | notesData = open("data/notes.json", "r+")
65 | jsonData = notesData.read()
66 | notesData.close()
67 | notesData = open("data/notes.json", "w+")
68 | if jsonData is not "":
69 | notes = json.loads(jsonData)
70 | if username not in notes.keys():
71 | notes[username] = {}
72 | if title not in notes[username].keys():
73 | notes[username][title] = note
74 | notesData.write(json.dumps(notes))
75 | notesData.close()
76 | return render_template("dashboard.html", message = "Note added successfully", error = False), 201
77 | else:
78 | notes = json.loads(jsonData)
79 | notesData.write(json.dumps(notes))
80 | notesData.close()
81 | return render_template("dashboard.html", message = "Note with title '{}', already exists".format(title), error = True)
82 | else:
83 | notes = {username:{title: note}}
84 | notesData.write(json.dumps(notes))
85 | notesData.close()
86 | return render_template("dashboard.html", message = "Note added successfully", error = False), 201
87 |
88 | @app.route("/getnotes", methods = ["GET"])
89 | def getnotes():
90 | if("loggedIn" in session.keys() and session["loggedIn"] is not True):
91 | return render_template("index.html", message = "Unauthorized", error = True), 401
92 | notesData = open("data/notes.json", "r+")
93 | jsonData = notesData.read()
94 | notesData.close()
95 | if jsonData is not "":
96 | notes = json.loads(jsonData)
97 | if session["username"] not in notes.keys():
98 | return render_template("notes.html", notes = {}, message = "No notes added yet", error = True)
99 | return render_template("notes.html", notes = notes[session["username"]])
100 | else:
101 | return render_template("notes.html", notes = {}, message = "No notes added yet", error = True)
102 |
103 | @app.route("/logout", methods = ["GET"])
104 | def logout():
105 | if("loggedIn" in session):
106 | del session["loggedIn"]
107 | del session["username"]
108 | return redirect("/"), 302
109 |
110 |
111 | if __name__ == "__main__":
112 | app.run("127.0.0.1", "3004", debug = True)
--------------------------------------------------------------------------------
/flask/example/data/notes.json:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/ACM-VIT/PyFlask_2k18/2103e54e3c284712767c319b8629e0f6ccd997ec/flask/example/data/notes.json
--------------------------------------------------------------------------------
/flask/example/data/user.json:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/ACM-VIT/PyFlask_2k18/2103e54e3c284712767c319b8629e0f6ccd997ec/flask/example/data/user.json
--------------------------------------------------------------------------------
/flask/example/static/style.css:
--------------------------------------------------------------------------------
1 | body{
2 |
3 | margin: 0px;
4 | background: lightgreen
5 |
6 | }
7 |
8 | .nav {
9 |
10 | border:1px solid royalblue;
11 | margin: 0;
12 | margin-bottom: 111px;
13 | padding: 11px;
14 | text-align: center;
15 | color: royalblue;
16 | background: rgb(147, 218, 241)
17 |
18 | }
19 |
20 | .form {
21 |
22 | text-align: center;
23 |
24 | }
25 |
26 | .form input{
27 |
28 | background: white;
29 | height: 25px;
30 | width: 250px;
31 | border: none;
32 | padding-left: 2px
33 |
34 | }
35 |
36 | .form textarea{
37 |
38 | background: white;
39 | width: 250px;
40 | border: none;
41 | padding-left: 2px
42 |
43 | }
44 |
45 | .form input[type="submit"]{
46 |
47 | width: 200px;
48 | color: royalblue;
49 | background: rgb(147, 218, 241);
50 | border: 1px solid royalblue;
51 | padding-left: 0;
52 | cursor: pointer
53 |
54 | }
55 |
56 | .form-label{
57 |
58 | text-align: center;
59 | color: royalblue;
60 | margin-bottom: 25px;
61 |
62 | }
63 |
64 | .message-success{
65 |
66 | width: 500px;
67 | color: rgb(21, 156, 21);
68 | background: rgb(113, 231, 102);
69 | text-align: center;
70 | padding: 11px;
71 | border: 1px solid rgb(21, 156, 21);
72 |
73 | }
74 |
75 | .message-error{
76 |
77 | width: 500px;
78 | color: rgb(214, 29, 29);
79 | background: rgb(235, 138, 126);
80 | text-align: center;
81 | padding: 11px;
82 | border: 1px solid rgb(214, 29, 29);
83 |
84 | }
85 |
86 | .logout{
87 |
88 | background: rgb(177, 31, 31);
89 | color: white;
90 | border: none;
91 | font-size: 25px;
92 | border-radius: 7px;
93 | cursor: pointer;
94 |
95 | }
96 |
97 | .note-title{
98 |
99 | color: royalblue;
100 | background: white;
101 | border: 1px solid royalblue;
102 | height: 25px;
103 | padding: 11px;
104 | width: 500px;
105 | padding-bottom:0;
106 | text-align: center;
107 | font-size: 20px;
108 | font-weight: bold;
109 |
110 | }
111 |
112 | .note-body{
113 |
114 | color: royalblue;
115 | background: white;
116 | border: 1px solid royalblue;
117 | border-top: none;
118 | padding: 11px;
119 | width: 500px;
120 | padding-bottom:0;
121 | text-align: center;
122 | font-size: 20px;
123 |
124 | }
--------------------------------------------------------------------------------
/flask/example/templates/dashboard.html:
--------------------------------------------------------------------------------
1 | {% extends "layout.html" %}
2 |
3 | {% block title %} notesManager - Dashboards {% endblock %}
4 |
5 | {% block body %}
6 |
7 |
21 |
22 |
25 |
26 | {% endblock %}
--------------------------------------------------------------------------------
/flowcontrol/README.md:
--------------------------------------------------------------------------------
1 | # Flow Control
2 |
3 | Alternatively control flow (when referring to computer programming) is the order function calls, instructions, and statements are executed or evaluated when a program is running. Many programming languages have what are called control flow statements used to determine what section of code is run in a program at a given time.
4 |
5 | ## Types Of Flow Control Statments
6 |
7 | * [If-Else statement](./ifelse.md)
8 |
9 | This is the most simple form of the branching statements.
10 |
11 | It takes an expression in parenthesis and an statement or block of statements. if the expression is true then the statement or block of statements gets executed otherwise these statements are skipped.
12 |
13 | * [While loop](./while.md)
14 |
15 | The most basic loop is the while loop. A while statement is like a repeating if statement. Like an If statement, if the test condition is true: the statments get executed. The difference is that after the statements have been executed, the test condition is checked again. If it is still true the statements get executed again.This cycle repeats until the test condition evaluates to false.
16 |
17 | * [For loop](./for.md)
18 |
19 | For loop is similar to while, it's just written differently.Executes a sequence of statements multiple times and abbreviates the code that manages the loop variable.
20 |
21 | * [EXCEPTION HANDLING Try Except](./tryExcept.md)
22 |
23 | The **try** block lets you test a block of code for errors.
24 | The **except** block lets you handle the error.
25 | The **finally** block lets you execute code, regardless of the result of the try- and except blocks.
26 |
27 | When an error occurs, or exception as we call it, Python will normally stop and generate an error message.
28 | These exceptions can be handled using the try statement.
29 |
30 |
31 | You can check out more [examples](./examples) here.
32 |
33 |
34 | **For more information look into**
35 |
36 | https://www.tutorialspoint.com/python/python_loops.htm
37 |
38 | https://www.w3schools.com/python/python_try_except.asp
39 |
40 | https://www.tutorialspoint.com/python/python_while_loop.htm
41 |
42 | https://www.programiz.com/python-programming/while-loop
43 |
--------------------------------------------------------------------------------
/flowcontrol/controlKeywords.md:
--------------------------------------------------------------------------------
1 | # Control Statements
2 |
3 | Loop control statements change execution from its normal sequence. When execution leaves a scope, all automatic objects that were created in that scope are destroyed. Python supports the following control statements.
4 |
5 | ## Continue Statement
6 |
7 | It returns the control to the beginning of the loop.
8 |
9 | ```python
10 | # Prints all letters except 'e' and 'd'
11 | for letter in 'helloworld':
12 | if letter == 'e' or letter == 'd':
13 | continue
14 | print 'Current Letter :', letter
15 | var = 10
16 | ```
17 |
18 | ## Break Statement
19 |
20 | It brings control out of the loop
21 |
22 | ```python
23 | for letter in 'helloworld':
24 |
25 | # break the loop as soon it sees 'e'
26 | # or 'd'
27 | if letter == 'e' or letter == 'd':
28 | break
29 |
30 | print 'Current Letter :', letter
31 | ```
32 |
33 | ## Pass Statement
34 |
35 | We use pass statement to write empty loops. Pass is also used for empty control statement, function and classes.
36 |
37 | ```python
38 | # An empty loop
39 | for letter in 'geeksforgeeks':
40 | pass
41 | print 'Last Letter :', letter
42 | ```
43 |
44 | For more information on loop control statements:
45 |
46 | https://www.geeksforgeeks.org/loops-and-loop-control-statements-continue-break-and-pass-in-python/
47 |
--------------------------------------------------------------------------------
/flowcontrol/examples/.gitignore:
--------------------------------------------------------------------------------
1 | *.pyc
2 | !.gitignore
3 |
--------------------------------------------------------------------------------
/flowcontrol/examples/filehandling/README.md:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/ACM-VIT/PyFlask_2k18/2103e54e3c284712767c319b8629e0f6ccd997ec/flowcontrol/examples/filehandling/README.md
--------------------------------------------------------------------------------
/flowcontrol/examples/for.py:
--------------------------------------------------------------------------------
1 | import sys
2 | # Some Examples of the for loop in python
3 | fruits = ["apple", "banana", "cherry"]
4 | for x in fruits:
5 | print(x)
6 | #The for loop does not require an indexing variable to set beforehand.
7 |
8 | ### Looping Through a String
9 | for x in "banana":
10 | print(x)
11 | #Even strings are iterable objects, they contain a sequence of characters
12 |
13 | ### _end_ argument is used
14 | for i in range(4):
15 | print(i)
16 | for i in range(4):
17 | print(i, end=" ")
18 | for i in range(4):
19 | print(i, end=" :-) ")
20 |
21 | ### The break Statement
22 | fruits = ["apple", "banana", "cherry"]
23 | for x in fruits:
24 | print(x)
25 | if x == "banana":
26 | break
27 | #With the break statement we can stop the loop before it has looped through all the items
28 |
29 | ### The continue Statement
30 | fruits = ["apple", "banana", "cherry"]
31 | for x in fruits:
32 | if x == "banana":
33 | continue
34 | print(x)
35 | #With the continue statement we can stop the current iteration of the loop, and continue with the next
36 |
37 | ### The range() Function
38 | for x in range(6):
39 | print(x)
40 | #To loop through a set of code a specified number of times, we can use the range() function
41 |
42 | ###Else in For Loop
43 | for x in range(6):
44 | print(x)
45 | else:
46 | print("Finally finished!")
47 | #The else keyword in a for loop specifies a block of code to be executed when the loop is finished
48 |
49 | ### Nested Loops
50 | adj = ["red", "big", "tasty"]
51 | fruits = ["apple", "banana", "cherry"]
52 |
53 | for x in adj:
54 | for y in fruits:
55 | print(x, y)
56 | #A nested loop is a loop inside a loop.
57 |
--------------------------------------------------------------------------------
/flowcontrol/examples/tryExcept.py:
--------------------------------------------------------------------------------
1 | def divide(a):
2 | try:
3 | result = a[0]//a[1]
4 | print("Yeah ! Your answer is :", result)
5 | except ArithmeticError:
6 | print("Sorry ! Arithmetic error occurred ")
7 | except ZeroDivisionError: #Already Handled by a Parent ArithmeticError exception. So it wont caught any error
8 | print("Sorry ! You are dividing by zero ")
9 | except TypeError:
10 | print("Sorry ! Only numbers are allowed ")
11 | except: # This will catch every error that is not caught by above exceptions
12 | print("Sorry ! Some Error occurred")
13 | else: # this will run if no error occurs
14 | print("Hurray ! No Error")
15 | finally: # This will run every time
16 | print("Program Ends...")
17 |
18 | divide([10,2])
19 | # Yeah ! Your answer is : 5
20 | # Hurray ! No Error
21 | # Program Ends...
22 |
23 | divide([10,0])
24 | # Sorry ! Arithmetic error occurred
25 | # Program Ends...
26 |
27 | divide([10,'a'])
28 | # Sorry ! Only numbers are allowed
29 | # Program Ends...
30 |
31 | divide([10])
32 | # Sorry ! Some Error occurred
33 | # Sorry ! Tried to use defined variable
34 | # Program Ends...
35 |
--------------------------------------------------------------------------------
/flowcontrol/for.md:
--------------------------------------------------------------------------------
1 | # For Loops
2 | ## What does for loop do:
3 | For loops are used for sequential traversal. For example: traversing a list or string or array etc. In Python, there is no C style for loop, i.e., for (i=0; iTry Except is used to handle exception
8 |
9 | The `try` block lets you test a block of code for errors.
10 | The `except` block lets you handle the error.
11 | The `finally` block lets you execute code, regardless of the result of the try- and except blocks.
12 |
13 | ## Need of Exception Handling
14 | When an error occurs, or exception as we call it, Python will normally stop and generate an error message. Since we can't let our application (supoose a web server) to crash, we use exception handling.
15 |
16 | Exception handling let us to have control on what will happen when our program will encounter an err instead of stoping the execution.
17 |
18 | ## Sequense of Try and Except execution
19 |
20 | * First `try` clause is executed i.e. the code between `try` and `except` clause.
21 | * If there is no exception, then only `try` clause will run, `except` clause is finished.
22 | * If any exception occured, `try` clause will be skipped and `except` clause will run.
23 | * If any exception occurs, but the `except` clause within the code doesn’t handle it, it is passed on to the outer `try` statements. If the exception left unhandled, then the execution stops.
24 | * A `try` statement can have more than one `except` clause
25 |
26 | ### Other Keywords
27 | * #### Else
28 | You can use the else keyword to define a block of code to be executed if no errors were raised
29 | ```python
30 | try:
31 | print("Hello")
32 | except:
33 | print("Something went wrong")
34 | else:
35 | print("Nothing went wrong")
36 | ```
37 | * #### Finally
38 | The finally block, if specified, will be executed regardless if the try block raises an error or not.
39 | ```python
40 | try:
41 | print(x)
42 | except:
43 | print("Something went wrong")
44 | finally:
45 | print("The 'try except' is finished")
46 | ```
47 |
48 | ## List of Exception Errors
49 | Here is a full Python exception class hierarchy view
50 | * BaseException
51 | * Exception
52 | * ArithmeticError
53 | * FloatingPointError
54 | * OverflowError
55 | * ZeroDivisionError
56 | * AssertionError
57 | * AttributeError
58 | * BufferError
59 | * EOFError
60 | * ImportError
61 | * ModuleNotFoundError
62 | * LookupError
63 | * IndexError
64 | * KeyError
65 | * MemoryError
66 | * NameError
67 | * UnboundLocalError
68 | * OSError
69 | * BlockingIOError
70 | * ChildProcessError
71 | * ConnectionError
72 | * BrokenPipeError
73 | * ConnectionAbortedError
74 | * ConnectionRefusedError
75 | * ConnectionResetError
76 | * FileExistsError
77 | * FileNotFoundError
78 | * InterruptedError
79 | * IsADirectoryError
80 | * NotADirectoryError
81 | * PermissionError
82 | * ProcessLookupError
83 | * TimeoutError
84 | * ReferenceError
85 | * RuntimeError
86 | * NotImplementedError
87 | * RecursionError
88 | * StopIteration
89 | * StopAsyncIteration
90 | * SyntaxError
91 | * IndentationError
92 | * TabError
93 | * SystemError
94 | * TypeError
95 | * ValueError
96 | * UnicodeError
97 | * UnicodeDecodeError
98 | * UnicodeEncodeError
99 | * UnicodeTranslateError
100 | * Warning
101 | * BytesWarning
102 | * DeprecationWarning
103 | * FutureWarning
104 | * ImportWarning
105 | * PendingDeprecationWarning
106 | * ResourceWarning
107 | * RuntimeWarning
108 | * SyntaxWarning
109 | * UnicodeWarning
110 | * UserWarning
111 | * GeneratorExit
112 | * KeyboardInterrupt
113 | * SystemExit
114 |
115 | ## Major Exception Types Overview
116 |
117 | Exception | Description
118 | ------------- | -------------
119 | ArithmeticError | The base class for the variety of arithmetic errors, such as when attempting to divide by zero, or when an arithmetic result would be too large for Python to accurately represent.
120 | AssertionError | This error is raised when a call to the [`assert`] statement fails.
121 | AttributeError | Python’s syntax includes something called `attribute references`, which is just the Python way of describing what you might know of as `dot notation`. In essence, any `primary token` in Python (like an identifier, literal, and so forth) can be written and followed by a period (.), which is then followed by an `identifier`. That syntax (i.e. primary.identifier) is called an attribute reference, and anytime the executing script encounters an error in such syntax an AttributeError is raised.
122 | BufferError | Python allows applications to access low level memory streams in the form of a `buffer`. For example, the bytes class can be used to directly work with `bytes` of information via a memory buffer. When something goes wrong within such a buffer operation a BufferError is raised.
123 | EOFError | Python’s EOFError is raised when using the `input()` function and reaching the end of a file without any data.
124 | ImportError | Modules are usually loaded in memory for Python scripts to use via the import statement (e.g. import car from vehicles). However, if an `import` attempt fails an `ImportError` will often be raised.
125 | LookupError | Like `ArithmeticError`, the LookupError is generally considered a base class from which other subclasses should inherit. All `LookupError` subclasses deal with improper calls to a collection are made by using invalid `key` or `index` values.
126 | MemoryError | In the event that your Python application is about to run out of memory a `MemoryError` will be raised. Since Python is smart enough to detect this potential issue slightly before all memory is used up, a `MemoryError` can be `rescued` and allow you to recover from the situation by performing garbage collection of some kind.
127 | NameError | Raised when trying to use an `identifier` with an invalid or unknown name.
128 | OSError | This error is raised when a system-level problem occurs, such as failing to find a local file on disk or running out of disk space entirely. `OSError` is a parent class to many subclasses explicitly used for certain issues related to operating system failure, so we’ll explore those in future publications.
129 | ReferenceError | Python includes the weakref module, which allows Python code to create a specific type of reference known as a `weak reference`. A weak reference is a reference that is not “strong” enough to keep the referenced object alive.
130 | RuntimeError | A RuntimeError is typically used as a `catchall` for when an error occurs that doesn’t really fit into any other specific error classification.
131 | StopIteration | If no `default` value is passed to the next() function when iterating over a collection, and that collection has no more iterated value to retrieve, a `StopIteration` exception is raised. Note that this is not classified as an `Error`, since it doesn’t mean that an error has occurred.
132 | StopAsyncIteration | As of version 3.5, Python now includes coroutines for `asynchronous transactions` using the `async and await` syntax. As part of this feature, collections can be `asynchronously` iterated using the __anext__() method. The __anext__() method requires that a StopAsyncIteration instance be raised in order to halt async iteration.
133 | SyntaxError | Just like most programming languages, a `SyntaxError` in Python indicates that there is some `improper syntax` somewhere in your script file. A SyntaxError can be raised directly from an executing script, or produced via functions like `eval()` and `exec()`.
134 | SystemError | A `generic error` that is raised when something goes wrong with the `Python interpreter` (not to be confused with the `OSError`, which handles operating system issues).
135 | TypeError | This error is raised when attempting to perform an `operation` on an `incorrect object type`.
136 | ValueError | Should be raised when a function or method receives an argument of the correct type, but with an actual value that is `invalid` for some reason.
137 | Warning | Another parent class to many subclasses, the Warning class is used to `alert` the user in non-dire situations.
138 |
--------------------------------------------------------------------------------
/flowcontrol/while.md:
--------------------------------------------------------------------------------
1 |
While loop
2 | A while loop is a control flow statement that allows code to be executed repeatedly based on a given Boolean condition. The while loop can be thought of as a repeating if statement.
3 |
4 |
while (boolean_condition)
5 | {
6 | // some statements here
7 | }
8 | Here, statement(s) may be a single statement or a block of statements. The boolean condition may be any expression, and true is any nonzero value. The loop iterates while the condition is true.
9 |
10 | When the condition becomes false, the program control passes to the line immediately following the loop.
11 |
46 | Step 1: The variable count is initialized with value 1 and then it has been tested for the condition.
47 | Step 2: If the condition returns true then the statements inside the body of while loop are executed else control comes out of the loop.
48 | Step 3: The value of count is incremented using ++ operator then it has been tested again for the loop condition.
49 |
Now, consider this loop:
50 | i = 1
51 | while(i < 6)
52 | {
53 | print(i)
54 | }
55 |
56 | This is what is known as an infinite loop, or never ending loop, meaning this loop never finishes running. This is because the value of i is not changing, it is always =1, so the condition that i<6 will always be true. Hence here 1 will be printed indefinitely.
57 |
58 |
59 |
While with else
60 | Same as that of for loop, we can have an optional else block with while loop as well.
61 | The else part is executed if the condition in the while loop evaluates to False.
62 | The while loop can be terminated with a break statement. In such a case, the else part is ignored. Hence, a while loop's else part runs if no break occurs and the condition is false.
63 |
72 | Inside loop
73 | Inside loop
74 | Inside loop
75 | Inside else
76 |
--------------------------------------------------------------------------------
/functions/README.md:
--------------------------------------------------------------------------------
1 | # Functions
2 |
3 | ## Need For Functions
4 |
5 | * Code reuse is a very important part of programming in any language.
6 | * Increasing code size makes it harder to maintain.
7 | * For a large programming project to be successful, it is essential to abide by the Don't Repeat Yourself,
8 | or DRY, principle.
9 |
10 | _**FACT** : Bad, repetitive code is said to abide by the WET principle, which stands for Write Everything Twice, or We Enjoy Typing._
11 |
12 |
13 |
14 | ## What is a Function?
15 |
16 | * A function is a block of code which only runs when it is called.
17 | * You can pass data, known as parameters, into a function.
18 | * A function can return data as a result.
19 | * Any statement that consists of a word followed by information in parentheses is a function call.
20 | Here are some examples that you've already seen:
21 | ```python
22 | print("Hello world!")
23 | range(2, 20)
24 | str(12)
25 | range(10, 20, 3)
26 | ```
27 | _**NOTE** : The words in front of the parentheses are function names, and the comma-separated values inside the parentheses are function arguments._
28 |
29 |
30 | ## Functions in Python
31 | * In addition to using pre-defined functions, you can create your own functions by using the def statement.
32 | * Here is an example of a function named my_func.
33 | It takes no arguments, and prints "spam" three times. It is defined, and then called.
34 | The statements in the function are executed only when the function is called.
35 | #### CODE
36 | ```python
37 | def my_func():
38 | print("spam")
39 | print("spam")
40 | print("spam")
41 |
42 | my_func()
43 | ```
44 | #### OUTPUT
45 | ```
46 | >>>
47 | spam
48 | spam
49 | spam
50 | >>>
51 | ```
52 |
53 | _**NOTE** : The code block within every function starts with a colon (:) and is indented._
54 |
55 | * You must define functions before they are called, in the same way that you must assign variables before using them.
56 | #### CODE
57 | ```python
58 | hello()
59 |
60 | def hello():
61 | print("Hello world!")
62 | ```
63 |
64 | #### OUTPUT
65 | ```
66 | >>>
67 | NameError: name 'hello' is not defined
68 | >>>
69 | ```
70 |
71 | ## Arguments
72 |
73 | * All the function definitions we've looked at so far have been functions of zero arguments, which are called with empty parentheses.
74 | * However, most functions take arguments.
75 | * The argument is defined inside the parentheses.
76 | * The example below defines a function that takes one argument:
77 | #### CODE
78 | ```python
79 | def print_with_exclamation(word):
80 | print(word + "!")
81 |
82 | print_with_exclamation("spam")
83 | print_with_exclamation("eggs")
84 | print_with_exclamation("python")
85 | ```
86 |
87 | #### OUTPUT
88 | ```
89 | >>>
90 | spam!
91 | eggs!
92 | python!
93 | >>>
94 | ```
95 |
96 | * You can also define functions with more than one argument; separate them with commas.
97 | #### CODE
98 | ```python
99 | def print_sum_twice(x, y):
100 | print(x + y)
101 | print(x + y)
102 |
103 | print_sum_twice(5, 8)
104 | ```
105 | #### OUTPUT
106 | ```
107 | >>>
108 | 13
109 | 13
110 | >>>
111 | ```
112 | * Function arguments can be used as variables inside the function definition.
113 | * However, they cannot be referenced outside of the function's definition.
114 | * This also applies to other variables created inside a function.
115 | #### CODE
116 | ```python
117 | def function(variable):
118 | variable += 1
119 | print(variable)
120 |
121 | function(7)
122 | print(variable)
123 | ```
124 | #### OUTPUT
125 | ```
126 | >>>
127 | 8
128 |
129 | NameError: name 'variable' is not defined
130 | >>>
131 | ```
132 | _**NOTE** : Technically, parameters are the variables in a function definition, and arguments are the values put into parameters when functions are called._
133 |
134 | ## Functions as Objects
135 | * Although they are created differently from normal variables, functions are just like any other kind of value.
136 | * They can be assigned and reassigned to variables, and later referenced by those names.
137 | #### CODE
138 | ```python
139 | def multiply(x, y):
140 | return x * y
141 |
142 | a = 4
143 | b = 7
144 | operation = multiply
145 | print(operation(a, b))
146 | ```
147 | #### OUTPUT
148 | ```
149 | >>>
150 | 28
151 | >>>
152 | ```
153 |
154 | * Functions can also be used as arguments of other functions.
155 | #### CODE
156 | ```python
157 | def add(x, y):
158 | return x + y
159 |
160 | def do_twice(func, x, y):
161 | return func(func(x, y), func(x, y))
162 |
163 | a = 5
164 | b = 10
165 |
166 | print(do_twice(add, a, b))
167 | ```
168 | #### OUTPUT
169 | ```
170 | >>>
171 | 30
172 | >>>
173 | ```
174 |
175 | _**HINT** : As you can see, the function do_twice takes a function as its argument and calls it in its body._
176 |
177 | ## Links and References
178 | https://www.w3schools.com/python/python_functions.asp
179 | https://www.tutorialspoint.com/python/python_functions.htm
180 | https://www.programiz.com/python-programming/function
181 |
--------------------------------------------------------------------------------
/functions/examples/.gitignore:
--------------------------------------------------------------------------------
1 | *.pyc
2 | !.gitignore
--------------------------------------------------------------------------------
/functions/examples/add_twice.py:
--------------------------------------------------------------------------------
1 | def print_sum_twice(x, y):
2 | print(x + y)
3 | print(x + y)
4 |
5 | print_sum_twice(5, 8)
6 |
--------------------------------------------------------------------------------
/functions/examples/exclaim.py:
--------------------------------------------------------------------------------
1 | def print_with_exclamation(word):
2 | print(word + "!")
3 |
4 | print_with_exclamation("spam")
5 | print_with_exclamation("eggs")
6 | print_with_exclamation("python")
7 |
--------------------------------------------------------------------------------
/functions/examples/function_as_argument.py:
--------------------------------------------------------------------------------
1 | def add(x, y):
2 | return x + y
3 |
4 | def do_twice(func, x, y):
5 | return func(func(x, y), func(x, y))
6 |
7 | a = 5
8 | b = 10
9 |
10 | print(do_twice(add, a, b))
11 |
--------------------------------------------------------------------------------
/functions/examples/function_scope.py:
--------------------------------------------------------------------------------
1 | def function(variable):
2 | variable += 1
3 | print(variable)
4 |
5 | function(7)
6 | print(variable)
7 |
--------------------------------------------------------------------------------
/functions/examples/functions_objects.py:
--------------------------------------------------------------------------------
1 | def multiply(x, y):
2 | return x * y
3 |
4 | a = 4
5 | b = 7
6 | operation = multiply
7 | print(operation(a, b))
8 |
--------------------------------------------------------------------------------
/operators/README.md:
--------------------------------------------------------------------------------
1 | # Python Operators
2 |
3 | Operators are used to perform operations on variables and values.
4 |
5 | Python divides the operators in the following groups:
6 |
7 | - Arithmetic operators
8 | - Assignment operators
9 | - Comparison operators
10 | - Logical operators
11 | - Identity operators
12 | - Membership operators
13 | - Bitwise operators
14 |
15 |
16 | ## Python Arithmetic Operators
17 |
18 | Arithmetic operators are used with numeric values to perform common mathematical operations:
19 |
20 | | Operator | Name | Example |
21 | | --- | --- | --- |
22 | | + | Addition | x + y |
23 | | - | Subtraction | x - y |
24 | | \* | Multiplication | x \* y |
25 | | / | Division | x / y |
26 | | % | Modulus | x % y |
27 | | \*\* | Exponentiation | x \*\* y |
28 | | // | Division | x // y |
29 |
30 |
31 | ## Python Assignment Operators
32 |
33 | Assignment operators are used to assign values to variables:
34 |
35 | | Operator | Example | Same As |
36 | | --- | --- | --- |
37 | | = | x = 5 | x = 5 |
38 | | += | x += 3 | x = x + 3 |
39 | | -= | x -= 3 | x = x - 3 |
40 | | \*= | x \*= 3 | x = x \* 3 |
41 | | /= | x /= 3 | x = x / 3 |
42 | | %= | x %= 3 | x = x % 3 |
43 | | //= | x //= 3 | x = x // 3 |
44 | | \*\*= | x \*\*= 3 | x = x \*\* 3 |
45 | | &= | x &= 3 | x &= 3 |
46 | | \|= | x \|= 3 | x = x \| 3 |
47 | | ^= | x ^= 3 | x = x ^ 3 |
48 | | >>= | x >>= 3 | x = x >> 3 |
49 | | <<= | x <<= 3 | x = x << 3 |
50 |
51 |
52 | ## Python Comparison Operators
53 |
54 | Comparison operators are used to compare two values:
55 |
56 | | Operator | Name | Example |
57 | | --- | --- | --- |
58 | | == | Equal | x == y |
59 | | != | Not equal | x != y |
60 | | > | Greater than | x > y |
61 | | < | Less than | x < y |
62 | | >= | Greater than or equal to | x >= y |
63 | | <= | Less than or equal to | x <= y |
64 |
65 |
66 | ## Python Logical Operators
67 |
68 | Logical operators are used to combine conditional statements:
69 |
70 | | Operator | Description | Example |
71 | | --- | --- | --- |
72 | | and | Returns True if both statements are true | x < 5 and x < 10 |
73 | | or | Returns True if one of the statements is true | x < 5 or x < 4 |
74 | | not | Reverse the result, returns False if the result is true | not(x < 5 and x < 10) |
75 |
76 |
77 | ## Python Identity Operators
78 |
79 | Identity operators are used to compare the objects, not if they are equal, but if they are actually the same object, with the same memory location:
80 |
81 | | Operator | Description | Example |
82 | | --- | --- | --- |
83 | | is | Returns true if both variables are the same object | x is y |
84 | | is not | Returns true if both variables are not the same object | x is not y |
85 |
86 |
87 | ## Python Membership Operators
88 |
89 | Membership operators are used to test if a sequence is presented in an object:
90 |
91 | | Operator | Description | Example |
92 | | --- | --- | --- |
93 | | in | Returns True if a sequence with the specified value is present in the object | x in y |
94 | | not in | Returns True if a sequence with the specified value is not present in the object | x not in y |
95 |
96 |
97 | ## Python Bitwise Operators
98 |
99 | Logical operators are used to combine conditional statements:
100 |
101 | | Operator | Name | Description |
102 | | --- | --- | --- |
103 | | & | AND | Sets each bit to 1 if both bits are 1 |
104 | | \| | OR | Sets each bit to 1 if one of two bits is 1 |
105 | | ^ | XOR | Sets each bit to 1 if only one of two bits is 1 |
106 | | ~ | NOT | Inverts all the bits |
107 | | << | Zero fill left shift | Shift left by pushing zeros in from the right and let the leftmost bits fall off |
108 | | >> | Signed right shift | Shift right by pushing copies of the leftmost bit in from the left, and let the rightmost bits fall off |
109 |
110 | You can check out more [examples](./examples) here.
111 |
112 | ### For more information on Operators:
113 | - https://www.w3schools.com/python/python_operators.asp
114 | - https://realpython.com/python-operators-expressions/
115 | - https://www.youtube.com/watch?v=v5MR5JnKcZI
116 |
--------------------------------------------------------------------------------
/operators/examples/.gitignore:
--------------------------------------------------------------------------------
1 | *.pyc
2 | !.gitignore
3 |
--------------------------------------------------------------------------------
/operators/examples/ArithmeticOperators.py:
--------------------------------------------------------------------------------
1 | # Arithmetic operators in Python
2 |
3 | x = 15
4 | y = 4
5 |
6 | # Output: x + y = 19
7 | print('x + y =',x+y)
8 |
9 | # Output: x - y = 11
10 | print('x - y =',x-y)
11 |
12 | # Output: x * y = 60
13 | print('x * y =',x*y)
14 |
15 | # Output: x / y = 3.75
16 | print('x / y =',x/y)
17 |
18 | # Output: x % y = 3
19 | print('x % y = ',x%y)
20 |
21 | # Output: x // y = 3
22 | print('x // y =',x//y)
23 |
24 | # Output: x ** y = 50625
25 | print('x ** y =',x**y)
26 |
--------------------------------------------------------------------------------
/operators/examples/BitwiseOperators.py:
--------------------------------------------------------------------------------
1 | # Bitwise Operators in Python
2 |
3 | x = 10
4 | y = 4
5 |
6 | # Output: x & y = 0
7 | print('x & y = ', x & y)
8 |
9 | # Output: x | y = 14
10 | print('x | y = ', x | y)
11 |
12 | # Output: ~x = -11
13 | print('~x = ', ~x)
14 |
15 | # Output: x ^ y = 14
16 | print('x ^ y = ', x ^ y)
17 |
18 | # Output: x >> 2 = 2
19 | print('x >> 2 = ', x >> 2)
20 |
21 | # Output: x << 2 = 40
22 | print('x << 2 = ', x << 2)
--------------------------------------------------------------------------------
/operators/examples/ComparisonOperators.py:
--------------------------------------------------------------------------------
1 | # Comparison operators in Python
2 |
3 | x = 10
4 | y = 12
5 |
6 | # Output: x > y is False
7 | print('x > y is',x>y)
8 |
9 | # Output: x < y is True
10 | print('x < y is',x= y is False
19 | print('x >= y is',x>=y)
20 |
21 | # Output: x <= y is True
22 | print('x <= y is',x<=y)
--------------------------------------------------------------------------------
/operators/examples/IdentityOperators.py:
--------------------------------------------------------------------------------
1 | # Identity operators in Python
2 |
3 | x1 = 5
4 | y1 = 5
5 | x2 = 'Hello'
6 | y2 = 'Hello'
7 | x3 = [1,2,3]
8 | y3 = [1,2,3]
9 |
10 | # Output: False
11 | print(x1 is not y1)
12 |
13 | # Output: True
14 | print(x2 is y2)
15 |
16 | # Output: False
17 | print(x3 is y3)
--------------------------------------------------------------------------------
/operators/examples/LogicalOperators.py:
--------------------------------------------------------------------------------
1 | # Logical Operators in Python
2 |
3 | x = True
4 | y = False
5 |
6 | # Output: x and y is False
7 | print('x and y is',x and y)
8 |
9 | # Output: x or y is True
10 | print('x or y is',x or y)
11 |
12 | # Output: not x is False
13 | print('not x is',not x)
--------------------------------------------------------------------------------
/operators/examples/MembershipOperators.py:
--------------------------------------------------------------------------------
1 | # Membership operators in Python
2 |
3 | x = 'Hello world'
4 | y = {1:'a',2:'b'}
5 |
6 | # Output: True
7 | print('H' in x)
8 |
9 | # Output: True
10 | print('hello' not in x)
11 |
12 | # Output: True
13 | print(1 in y)
14 |
15 | # Output: False
16 | print('a' in y)
--------------------------------------------------------------------------------