0% found this document useful (0 votes)
12 views

This Comprehensive Python Cheat Sheet Covers Everything You Need To Know To Get Started With Python

python

Uploaded by

godgiven.ug
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
12 views

This Comprehensive Python Cheat Sheet Covers Everything You Need To Know To Get Started With Python

python

Uploaded by

godgiven.ug
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 185

This comprehensive Python cheat sheet covers everything you need to know to get

started with Python, from basic syntax to advanced concepts like object-oriented
programming and data structures. It's also a great resource for experienced Python
users who want to brush up on their skills or learn something new.

What is Python?

Python is a High-Level Programming Language, with high-level inbuilt data


structures and dynamic binding. It is interpreted and an object-oriented programming
language. Python distinguishes itself from other programming languages in its easy
to write and understand syntax, which makes it charming to both beginners and
experienced folks alike. The extensive applicability and library support
of Python allow highly versatile and scalable software and products to be built on
top of it in the real world.

📙 20 Best Python Books for Beginners and Experienced Coders

1. Python Arithmetic Operators

The Arithmetic Operators in the below table are in Lowest to Highest precedence.

Operators Operation Explanation Examples

+ Addition Returns sum of 2 numbers 1+3=4

- Subtraction Returns the difference of 2 numbers 1 - 3 = -2

* Multiplication Returns the product of 2 numbers 1*3=3

/ Division Returns the value of a divided by b as a decimal value 1 / 3 = 0.33

// Floored Division Returns the floor of a divided by b 1 // 3 = 0

% Remainder Returns the remainder when a is divided by b 1%3=1

Some examples are shown below:

#Example for Addition

>>> 1 + 3

#Example for Subtraction

>>> 1 - 3

-2
#Example for Multiplication

>>> 6 * 6

36

#Example for Floored Division

>>> 4 // 2

#Example for Division

>>> 3 / 2

1.5000

#Example for Modulo

>>> 3 % 2

2. Python Data Types

The table below lists the different data types in Python along with some examples
of them:

DataTypes Examples

Integers 0, 2, -1, 5

Strings “a”, “hello”, “1234”, “12 Hello.”

Boolean True, False

Floating Point Numbers 16.0, -11.0, 2021.5

3. Python Variables

Variables are names given to data items that may take on one or more values during
a program’s runtime.
Following are the variable naming conventions in python:
 It cannot begin with a number.
 It must be a single word.
 It must consist of letters and _ symbols only.
 Variables in Python which start with _ (underscore) are considered as
“Unuseful”.

Some examples are shown below:

>>> variable_name = "Hello"

>>> variable_name

'Hello'

>>> variableName = 123

>>> variableName

123

4. Python Comments

Comments are lines of text/code in the program, which are ignored by the compiler
during program execution.

There are multiple types of comments in python:

 Inline Comment -

We can write an Inline Comment by typing # followed by the comment.

# Inline Comment to calculate sum of 2 numbers

def fun(a, b):

return a + b

 Multiline Comment -

We can write a Multiline Comment by typing # followed by the comment in each of


the lines.

# Multiline
# Comment

# Function to calculate

# sum of 2 numbers

def fun(a, b):

return a + b

 Docstring Comment -
Docstring comments are achieved by Typing the comment within triple quotes. ( '''
comment ''' )

'''

This is a function

to find sum

of 2 numbers.

This is an example of

docstring comment.

'''

def fun(a, b):

return a + b

5. Standard Python Functions

 print() function in Python

The print() function prints some specified message to the screen or some standard
output device. We can print strings, numbers, or any other object using this function.
We can print multiple tokens, and also specify to print the data separated by different
delimiters using the print() function.

>>> print("Hello World")


Hello World

>>> var = "Interviewbit"

>>> print("My name is ", var)

('My name is ', 'Interviewbit')

>>> print("My name is " + var)

My name is Interviewbit

>>> print(123)

123

>>> a = [1, 2, 3, 4]

>>> print(a)

[1, 2, 3, 4]

 input() function in Python

The input() function in Python is used to take any form of inputs from the
user/standard input device, which can later be processed accordingly in the program.
It is complementary to the print() function.

>>> print('Enter your name.')

>>> myName = input()

>>> print('Hello, {}'.format(myName))

Enter your name.

Interviewbit

Hello, Interviewbit

 len() function in Python


The len() function is used find the length(number of elements) of any python
container like string, list, dictionary, tuple, etc.

# For List

a = [1, 2, 3]

print(len(a))

# For string

a = "hello"

print(len(a))

# For tuple

a = ('1', '2', '3')

print(len(a))

 ord() function in Python

The ord() function in Python will return an integer that represents the Unicode
Character passed into it. It takes a single character as a parameter.

Example:

# Print unicode of 'A'

print(ord('A'))

# Print unicode of '5'

print(ord('5'))

# Print unicode of '$'

print(ord('$'))
Output:

65

53

36

6. Python Type Casting

Type casting is basically a conversion of variables of a particular datatype into some


other datatype, such that the conversion is valid.

Type casting can be of two types:

 Implicit Type Casting: In implicit type casting, the python compiler internally
typecasts one variable into another type without the external action of the
user.
Example:
int_num = 100

float_num = 1.01

ans = int_num + float_num

print(type(int_num))

print(type(float_num))

# ans is implicitly typecasted to float type for greater precision

print(type(ans))

 Explicit Type Casting: In explicit type casting, the user explicitly forces the
compiler to convert a variable from one type to another. The different ways of
explicit typecasting are given below:
1. Integer to String or Float:

To typecast an integer into a string type, we use the str() method. Similarly, to
typecast it into a float type, we use the float() method.

For example:
>>> var = 123

>>> str(var)

'123'

>>> var = 123

>>> float(var)

123.0

2. Float to Integer:

To typecast a float datatype into an integer datatype, we use the int() method.

For example:

>>> var = 7.8

>>> print(int(var))

7. Program Flow Control in Python

Relational Operators in Python

The Table gives a list of relational operators available in Python along with their
functions:

Operator What it does

== Is equal to

>= Is Greater than or Equal to

<= Is Less than or Equal to

> Is Greater than

< Is Less than

!= Not Equal to

Some examples are given below:


# Equality Operator

>>> 10 == 10

True # 10 is equal to 10, so true

>>> 10 == "10"

False # The first string is of type int, 2nd of type string, so false.

# Greater than

>>> 10 > 20

False # 10 is lesser than 20, so above expression is false.

# Inequality

>>> 10 != 20

True # 10 is not equal to 20, so the expression is true

# Greater than or equal to

>>> (2 + 3) >= (4 + 1)

True # (2 + 3) = 5 and (4 + 1) = 5, so the expression is true.

Note: Never use relational operators to compare boolean operations. Use is or is not
operators for it.
>>> True is False

False

>>> True is not False

True

8. Boolean Operators in Python

The Table gives a list of boolean operators available in Python along with their
functions:
Operator What it does

and Returns True if both operands are True, else False

or Returns True if both operands are True, else False

not Returns value opposite to the Truth value of the expression

Examples:

# and operator

print(True and False)

False

# or operator

print(True or False)

True

# not operator

print(not False)

True

9. Conditional Statements in Python

 If Statements: If statement is a condition statement that will perform some


operation, if the expression given in it evaluates to true as shown below:

>>> var = "Good"

>>> if var == "Good":

... print("Same")

...

Same
 Elif Statements: This statement is used in conjunction with the if statement
to add some other condition which is evaluated if the condition in if statement
fails.
>>> var = "Good"

>>> if var == "Good":

... print("Same")

... elif var != "Good":

... print("Not Same")

...

Same

 Else Statements: This statement is used to perform some operation, if all


the if and elif statements evaluates to be false.
>>> var = "Good"

>>> if var != "Good":

... print("Not Same")

... else:

... print("Same")

...

Same

The final if-elif-else ladder looks like shown below:

10. Loop Statements in Python

Loops in Python are statements that allow us to perform a certain operation multiple
times unless some condition is met.
For Loops: For loop is used to iterate iterables like string, tuple, list, etc and perform
some operation as shown in the flowchart below:

 For with range:


This loop format will iterate overall numbers from 0 to Limit - 1.
The below example prints numbers from 0 to 4.
for i in range(5):

print(i)

Output:

 For with range(start, stop, step):


This will run the loop from start to stop - 1, with step size = step in each iteration.
In the below example, the start is 2, end point is 10 and the step size is 2. Hence it
prints 2,4,6,8

for i in range(2, 10, 2):

print(i)

Output:

8
 For with in:
This is used to iterate over all the elements in a python container like list,
tuple, dictionary, etc.
a = [1, 3, 5, 7]

for ele in a:

print(ele)

Output:

 While Loops:
This is used for executing set of statements within its block as long as the
associated loop condition is evaluated to True as shown in the image below:

>>> count = 5

>>> while count > 0:

... print(count)

... count -= 1

...

2
1

11. Jump Statements in Python

 break: break statements are used to break out of the current loop, and allow
execution of the next statement after it as shown in the flowchart below:

>>> for i in range(5):

... print(i)

... if i == 3:

... break

...

 continue: continue statement allows us to send the control back to the


starting of the loop, skipping all the lines of code below it in the loop. This is
explained in the flowchart below:

>>> for i in range(5):

... if i == 3:

... continue

... print(i)

...
0

 pass: The pass statement is basically a null statement, which is generally


used as a placeholder. It is used to prevent any code from executing in its
scope.
for i in range(5):

if i % 2 == 0:

pass

else:

print(i)

Output:

 return: return statement allows us to send the control of the program outside
the function we are currently in. A function can have multiple return
statements, but can encounter only one of them during the course of its
execution.
def func(x):

if x == 'Hello':

return True

else:

return False
12. Functions in Python

Functions are used to well-organized our code and enhance code readability and
reusability. In Python, a function is defined using the def keyword. A function can
return some value, or not depending upon its use case. If it has to return a value, the
return statement (which has been discussed) is used. The syntax of a python
function is shown in the image below:

Example of a function:

# Function to return sum of two numbers

def getSum(a, b):

return a + b

# Function to print sum of 2 numbers

def printSum(a, b):

print(a + b)

print(getSum(5, 6))

printSum(5, 6)

13. Python Variable Scope Resolution

Scope of a variable is the part of the code, where it can be accessed freely and used
by the program.

The scopes in the above image are explained as follows:

 Built-in: These are reserved names for Python built-in modules.


 Global: These variables are defined at the highest level.
 Enclosed: These variables are defined inside some enclosing functions.
 Local: These variables are defined inside the functions or class and are local
to them.

The rules used in Python to resolve scope for local and global variables are as
follows:

 Code in the global scope cannot use any local variables.


 Code in a function’s local scope cannot use variables in any other local scope.
 However, a local scope can access global variables.
 We can use the same name for different variables if they are in different
scopes.

14. Global Statement

To modify a global variable from inside a function, we use the global statement:

def func():

global value

value = "Local"

value = "Global"

func()

print(value)

Output:

Local

We set the value of “value” as Global. To change its value from inside the function,
we use the global keyword along with “value” to change its value to local, and then
print it.

15. Importing Modules in Python

Python has various external libraries of code with useful utilities and functions. To
use these modules, we need to import them into our code, using the import keyword.

For example, if we want to use the functionalities of the math module, then we can
import it in our python code by using import math as shown in the example below.
import math

print(math.pi)

Output:

3.141592653589793

If we want to perform any string manipulations, we can use the string module as
import string in python. More of this is covered in the String Manipulation section
below.

16. Exception Handling in Python

Exception Handling is used to handle situations in our program flow, which can
inevitably crash our program and hamper its normal working. It is done in Python
using try-except-finally keywords.

 try: The code in try section is the part of the code where the code is to be
tested for exceptions.
 except: Here, the cases in the original code, which can break the code, are
written, and what to do in that scenario by the program.
 finally: The code in the finally block will execute whether or not an exception
has been encountered by the program.

The same has been illustrated in the image below:

Example:

# divide(4, 2) will return 2 and print Division Complete

# divide(4, 0) will print error and Division Complete

# Finally block will be executed in all cases

def divide(a, denominator):

try:

return a / denominator

except ZeroDivisionError as e:
print('Divide By Zero!! Terminate!!')

finally:

print('Division Complete.')

17. Lists in Python

Lists are used to store multiple items in a single variable. Their usage and some
functions are shown below with examples:

example = ["Sunday", "Monday", "Tuesday", "Wednesday"];

print(example)

Output:

['Sunday', 'Monday', 'Tuesday', 'Wednesday']

 Accessing elements in a List:


Accessing elements in a list basically means getting the value of an element
at some arbitrary index in the list.
Indexes are assigned on 0 based basis in python. We can also access
elements in python with negative indexes. Negative indexes represent
elements, counted from the back (end) of the list.
example = ["Sunday", "Monday", "Tuesday", "Wednesday"];

# Positive Indexing

print(example[0], example[1])

# Negative Indexing

print(example[-1])

Output:

Sunday Monday

Wednesday
 Slicing a List:
Slicing is the process of accessing a part or subset of a given list. The slicing
is explained in the image below:

example = ["Sunday", "Monday", "Tuesday", "Wednesday"];

# Positive Slicing

print(example[0:2])

# Negative Slicing

print(example[-3:-1])

Output:

['Sunday', 'Monday']

['Monday', 'Tuesday']

 Changing Values in a List:


We can change values at some particular index in a list by accessing the
element with [] and then setting it to some other value.
example = ["Sunday", "Monday", "Tuesday", "Wednesday"];

print(example)

example[0] = "Saturday"

print(example)

Output:

['Sunday', 'Monday', 'Tuesday', 'Wednesday']

['Saturday', 'Monday', 'Tuesday', 'Wednesday']

 List Concatenation and Replication:

When we merge the contents of 2 lists into one list, it is called list concatenation.
example = ["Sunday", "Monday", "Tuesday", "Wednesday"];

example1 = ["Weekdays", "Weekends"]

# Concatenation

example = example + example1

print(example)

Output:

['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Weekdays', 'Weekends']

Copying the contents of a list, some finite number of times into the same or some list
is called list replication.

example = ["Sunday", "Monday", "Tuesday", "Wednesday"];

example1 = ["Weekdays", "Weekends"]

# Replication

example1 = example1 * 3

print(example1)

Output:

['Weekdays', 'Weekends', 'Weekdays', 'Weekends', 'Weekdays', 'Weekends']

 Delete values from Lists:


We can delete a particular element from a list by using the del keyword.
example = ["Sunday", "Monday", "Tuesday", "Wednesday"];

print(example)

del example[2]

print(example)
Output:

['Sunday', 'Monday', 'Tuesday', 'Wednesday']

['Sunday', 'Monday', 'Wednesday']

 Looping through Lists:


The below example shows how we can iterate over all the elements present in
a list.
example = ["Sunday", "Monday", "Tuesday", "Wednesday"];

for ex in example:

print(ex)

Output:

Sunday

Monday

Tuesday

Wednesday

in and not in keywords:


With the in keyword, we can check if some particular element is present in the given
python variable.
Similar to the not in keyword, we can check if some particular element is not present
in the given python variable.

example = ["Sunday", "Monday", "Tuesday", "Wednesday"];

print("Sunday" in example)

print("Hello" not in example)

Output:
True

True

 Adding Values in Lists:


insert(): This function inserts an element into a particular index of a list.

example = ["Sunday", "Monday", "Tuesday", "Wednesday"];

print(example)

example.insert(1, 'Days')

print(example)

Output:

['Sunday', 'Monday', 'Tuesday', 'Wednesday']

['Sunday', 'Days', 'Monday', 'Tuesday', 'Wednesday']

append(): This function appends an element at the back of a list.

example = ["Sunday", "Monday", "Tuesday", "Wednesday"];

print(example)

example.append('Days')

print(example)

Output:

['Sunday', 'Monday', 'Tuesday', 'Wednesday']

['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Days']

 Sorting a List:
Sorting a list means arranging the elements of the list in some particular
order. We sort a list by using the sort() function.
# Sorts in lexicographical order

example = ["Sunday", "Monday", "Tuesday", "Wednesday"];

print(example)

# Sort in ascending order

example.sort()

print(example)

# Sort in descending order

example.sort(reverse = True)

print(example)

example = [1, 5, 3, 7, 2]

# Sort in ascending order

example.sort()

print(example)

# Sort in descending order

example.sort(reverse = True)

print(example)

Output:

['Sunday', 'Monday', 'Tuesday', 'Wednesday']

['Monday', 'Sunday', 'Tuesday', 'Wednesday']

['Wednesday', 'Tuesday', 'Sunday', 'Monday']


[1, 2, 3, 5, 7]

[7, 5, 3, 2, 1]

18. Tuples in Python

Tuples are entities in Python that work almost similar to that of lists, but differ in the
main feature from lists, is in that they are inmutable.

They are initialized by writing the elements of the tuple with (), separated by
commas.

# Defining and Initializing a tuple called example

example = ("First", "Second", "Third", "Fourth")

print(example)

print(example[1:3])

Output:

('First', 'Second', 'Third', 'Fourth')

('Second', 'Third')

Type Converting between Tuples, Lists, and Strings:

# Convert list to a tuple

tuple(['first', 'second', 'third'])

# Convert tuple to a list

list(('first', 'second', 'third'))

# Convert string to a list

list("Scaler")

19. Python Dictionaries

Dictionaries in Python are equivalent to Maps in C++/JAVA. They are used to store
data in key-value pairs.
Printing key and values in dictionaries:

To print the keys of the dictionary, use the .keys() method and to print the values,
use .values() method.

dict = {'first' : 'sunday', 'second' : 'monday', 'third' : 'tuesday'}

# dict.keys() method will print only the keys of the dictionary

for key in dict.keys():

print(key)

# dict.values() method will print only the values of the corressponding keys of the
dictionary

for value in dict.values():

print(value)

Output:

first

second

third

sunday

monday

tuesday

Update key value in dictionary:

 Update key value which is not present in dictionary:


We can update a key value in a dictionary by accessing the key withing [] and
setting it to a value.
dict = {'first' : 'sunday', 'second' : 'monday', 'third' : 'tuesday'}

for item in dict.items():


print(item)

dict['fourth'] = 'wednesday'

for item in dict.items():

print(item)

Output:

('first', 'sunday')

('second', 'monday')

('third', 'tuesday')

('first', 'sunday')

('second', 'monday')

('third', 'tuesday')

('fourth', 'wednesday')

 Update key value which is present in the dictionary:


We can update a key value in a dictionary, when the key is present in the
exact same way as we update a key, when the key is not present in the
dictionary.
dict = {'first' : 'sunday', 'second' : 'monday', 'third' : 'tuesday'}

for item in dict.items():

print(item)

dict['third'] = 'wednesday'

for item in dict.items():

print(item)
Output:

('first', 'sunday')

('second', 'monday')

('third', 'tuesday')

('first', 'sunday')

('second', 'monday')

('third', 'wednesday')

 Delete key-value pair from dictionary:


We can delete a key-value pair from a dictionary using the del keyword
followed by the key value to be deleted enclosed in [].
dict = {'first' : 'sunday', 'second' : 'monday', 'third' : 'tuesday'}

for item in dict.items():

print(item)

del dict['third']

for item in dict.items():

print(item)

Output:

('first', 'sunday')

('second', 'monday')

('third', 'tuesday')

('first', 'sunday')

('second', 'monday')
Merging 2 dictionaries

We can merge 2 dictionaries into 1 by using the update() method.

dict1 = {'first' : 'sunday', 'second' : 'monday', 'third' : 'tuesday'}

dict2 = {1: 3, 2: 4, 3: 5}

dict1.update(dict2)

print(dict1)

Output:

{'first': 'sunday', 'second': 'monday', 'third': 'tuesday', 1: 3, 2: 4, 3: 5}

20. Sets in Python

Initializing Sets:

Sets are initialized using curly braces {} or set() in python.

A python set is basically an unordered collection of unique values, i.e. it will


automatically remove duplicate values from the set.

s = {1, 2, 3}

print(s)

s = set([1, 2, 3])

print(s)

s = {1, 2, 3, 3, 2, 4, 5, 5}

print(s)

Output:

{1, 2, 3}

{1, 2, 3}

{1, 2, 3, 4, 5}
Inserting elements in set:

We can insert a single element into a set using the add function of sets.

s = {1, 2, 3, 3, 2, 4, 5, 5}

print(s)

# Insert single element

s.add(6)

print(s)

Output:

{1, 2, 3, 4, 5}

{1, 2, 3, 4, 5, 6}

To insert multiple elements into a set, we use the update function and pass a list of
elements to be inserted as parameters.

s = {1, 2, 3, 3, 2, 4, 5, 5}

# Insert multiple elements

s.update([6, 7, 8])

print(s)

Output:

{1, 2, 3, 4, 5, 6, 7, 8}

Deleting elements from the set:

We can delete elements from a set using either the remove() or the discard()
function.

s = {1, 2, 3, 3, 2, 4, 5, 5}

print(s)
# Remove will raise an error if the element is not in the set

s.remove(4)

print(s)

# Discard doesn't raise any errors

s.discard(1)

print(s)

Output:

{1, 2, 3, 4, 5}

{1, 2, 3, 5}

{2, 3, 5}

Operators in sets:

The below table shows the operators used for sets:

Operators What it does

| (Union) Returns all the unique elements in both the sets.

& (Intersection) Returns all the elements common to both the sets.

- (Difference) Returns the elements that are unique to the first set

^(Symmetric Difference) Returns all the elements not common to both the sets.

The set operators are represented in the Venn Diagram below:

Examples:

a = {1, 2, 3, 3, 2, 4, 5, 5}

b = {4, 6, 7, 9, 3}
# Performs the Intersection of 2 sets and prints them

print(a & b)

# Performs the Union of 2 sets and prints them

print(a | b)

# Performs the Difference of 2 sets and prints them

print(a - b)

# Performs the Symmetric Difference of 2 sets and prints them

print(a ^ b)

Output:

{3, 4}

{1, 2, 3, 4, 5, 6, 7, 9}

{1, 2, 5}

{1, 2, 5, 6, 7, 9}

21. Comprehensions in Python

 List Comprehensions:
It is a shorter syntax to create a new list using values of an existing list.
a = [0, 1, 2, 3]

# b will store values which are 1 greater than the values stored in a

b = [i + 1 for i in a]

print(b)

Output:

[1, 2, 3, 4]
 Set Comprehension:
It is a shorter syntax to create a new set using values of an existing set.
a = {0, 1, 2, 3}

# b will store squares of the elements of a

b = {i ** 2 for i in a}

print(b)

Output:

{0, 1, 4, 9}

 Dict Comprehension:
It is a shorter syntax to create a new dictionary using values of an existing
dictionary.
a = {'Hello':'World', 'First': 1}

# b stores elements of a in value-key pair format

b = {val: k for k , val in a.items()}

print(b)

Output:

{'World': 'Hello', 1: 'First'}

22. String Manipulation in Python

 Escape Sequences:

Escape Sequences are used to print certain characters to the output stream which
carry special meaning to the language compiler.

Examples:

Escape Sequence Results in

\t Tab Space

\n Newline
Escape Sequence Results in

\\ Backslash

\’ Single Quote

 Multiline Strings:
Multiline Strings are used in python through triple quotes '''

Example:

a = ''' Hello

World!

This is a

Multiline String.'''

print(a)

Output:

Hello

World!

This is a

Multiline String.

 Strings Indexing:

Strings in Python are indexed the same way as a list of characters, based on 0-
based indexing. We can access elements of a string at some index by using the []
operators.

Consider an example of the string value Python.

a = "Python"
print(a[0], a[2], a[4])

print(a[-1], a[-3], a[-5])

Output:

Pto

nhy

 Strings Slicing:

Slicing is also done the same way as in lists.

a = "Hello"

# Slices the string from 0 to 3 indexes

print(a[0:3])

# Slices the string from 3 to -1(same as 4) indexes

print(a[3:-1])

Output:

Hel

 Case Conversion Functions:

The upper() and lower() functions are used to convert a string of letters into
uppercase or lowercase respectively.

The isupper() and islower() functions are used to check if a string is in all uppercase
or lowercase respectively.

a = "Hello"

print(a)
# Converts string to uppercase

print(a.upper())

# Converts string to lowercase

print(a.lower())

# Checks if string is uppercase

print(a.isupper())

# Checks if string is lowercase

print(a.islower())

Output:

Hello

HELLO

hello

False

False

Other similar functions:

Function Explanation

isspace() Returns True if all characters in string are whitespaces

isalnum() Returns True if given string is alphanumeric

isalpha() Returns True if given character is alphabet

isTitle() Returns True if string starts with an uppercase letter and then rest of the characters are lowercase

 join() and split() Functions:

join() function merges elements of a list with some delimiter string, and returns the
result as a string.
list = ["One", "Two", "Three"]

# join function

s = ','.join(list)

print(s)

Output:

One,Two,Three

split() function splits the into tokens, based on some delimiters and returns the result
as a list.

# split function

newList = s.split(',')

print(newList)

Output:

['One', 'Two', 'Three']

In general, a string can be split to list using split() method and a list can be joined to
string using the join() method as shown in the image below:

 String Formatting:

String Formatting is done with the str.format() function.

first = "first"

second = "second"

s = "Sunday is the {} day of the week, whereas Monday is the {} day of the
week".format(first, second)

print(s)
Output:

Sunday is the first day of the week, whereas Monday is the second day of the week

 Template Strings:

It is recommended to be used when formatting strings generated by users. They


make the code less complex so are easier to understand. They can be used by
importing the Template class from the string module.

Example:

>>> from string import Template

>>> name = 'Scaler'

>>> t = Template('Hey $name!')

>>> t.substitute(name = name)

'Hey Scaler!'

23. Formatting Dates in Python

To handle date and time operations in Python, we use the datetime module.

 time class: We can represent time values using the time class.

Example:

import datetime

tm = datetime.time(1, 30, 11, 22)

print(tm)

Output:

01:30:11.000022

 date class: We can represent date values using the date class.

Example:
import datetime

date = datetime.date(2000, 11, 16)

print('Date date is ', date.day, ' day of ', date.month, ' month of the year ', date.year)

Output:

Date date is 16 day of 11 month of the year 2000

 Conversion from date to time: We can convert a date to its corresponding


time using the strptime() function.

Example:

from datetime import datetime

print(datetime.strptime('15/11/2000', '%d/%m/%Y'))

Output:

2000-11-15 00:00:00

 time.strftime() in Python: It converts a tuple or struct_time representing the


time into a string object.

For example:

from time import gmtime, strftime

s = strftime("%a, %d %b %Y %H:%M:%S + 1010", gmtime())

print(s)

Output:

Sun, 28 Nov 2021 18:51:24 + 1010

24. Python RegEx

 Regex Matching
The re module in python allows us to perform regex matching operations.
import re

landline = re.compile(r'\d\d\d\d-\d\d\d\d')

num = landline.search('LandLine Number is 2435-4153')

print('Landline Number is: {}'.format(num.group()))

Output:

Landline Number is: 2435-4153

The above example landline number from the string and stores it appropriately in the
num variable using regex matching.

 Parenthesis Grouping

A group is a part of a regex pattern enclosed in parenthesis (). We can put matches
into different groups using the parenthesis (). We can access the groups using
group() function.

import re

landline = re.compile(r'(\d\d\d\d)-(\d\d\d\d)')

num = landline.search('LandLine Number is 2435-4153')

# This will print the first group, which is the entire regex enclosed in the brackets

print(num.group(0))

# This will print the second group, which is the nested regex enclosed in the 1st set of
nested brackets

print(num.group(1))

# This will print the third group, which is the nested regex enclosed in the 2nd set of
nested brackets

print(num.group(2))

Output:
2435-4153

2435

4153

 Regex Symbols in Python

There are a lot of regex symbols that have different functionalities so they are
mentioned in the table below:

Symbol Matches

+ One or More of the preceding group

* Zero or More of preceding group

? Zero or One of preceding group

^name String must begin with the name

name$ String must end with the name

. Any character except \n

{n} Exactly n of preceding group

{n, } >= n of preceding group

{,n} [0, m] of preceding group

{n, m} [n, m] of preceding group

*? Non Greedy matching of the preceding group

[abc] Any character enclosed in the brackets

[^abc] Any character not enclosed in the brackets

\d, \w, \s Digit, word, or space respectively.

\D, \W, \S Anything except digit, word, or space respectively

Example:

Here we define a regex pattern,

address = "(\\d*)\\s?(.+),\\s(.+)\\s([A-Z]{2,3})\\s(\\d{4})"
From the above table, we can explain some of the symbols in this pattern:

 \s?: 0 or 1 whitespace.
 (\d*): 0 or more digit characters.
 (.+): Greater than or equal to 1 characters.
 \s: Single Whitespace
 ([A-Z]{2, 3}): 2 or 3 Uppercase alphabets
 (\d{4}): 4 digit characters

25. Debugging in Python

Raising Exceptions with raise statement:

The raise statement is used to raise exceptions and consists of 3 components:

 raise keyword
 Exception() function call
 Parameter of the Exception() function, which usually contains an error
message.

raise Exception("Error Occurred!!")

Traceback (most recent call last):

File "./prog.py", line 1, in <module>

Exception: Error Occurred!!

Traceback as String

There is a function in python called traceback.format_exc() which returns the


traceback displayed by Python when a raised Exception is not handled as a String
type. The Traceback Module is required to be imported for this purpose.

Example:

import traceback

try:

raise Exception('Error Message.')

except:
with open('error.txt', 'w') as error_file:

error_file.write(traceback.format_exc())

print('The traceback info was written to error.txt.')

Output:

The traceback info was written to error.txt.

Assert Statements in Python:

Assert Statements/Assertions are widely used for debugging programs and checking
if the code is performing some operation that is obviously wrong according to the
logic of the program. The special thing about assert is that when an assert fails, the
program immediately crashes, allowing us to narrow down our search space for the
bug.
Writing an assert statement has the following components as a part of it,

 assert keyword
 a condition that results in a boolean value
 a display message for when the assertion fails
 a comma separating the condition and the display message.

>>> sum = 4

>>> assert sum == 5, 'Addition Error'

Traceback (most recent call last):

File "<stdin>", line 1, in <module>

AssertionError: Addition Error

Assertions can be disabled by passing the -O option when running Python as shown
in the commands below.

$ python -Oc "assert False"

$ python -c "assert False"


Traceback (most recent call last):

File "<string>", line 1, in <module>

AssertionError

26. Logging in Python

Logging allows us to keep track of some events which occurs when some software
runs. It becomes highly important in Software Development, Debugging and Running
Softwares.

import logging

# Create and configues the logger

logging.basicConfig(filename="newfile.log", format='%(asctime)s %(message)s',


filemode='w')

# Creates logging object

logg = logging.getLogger()

# Sets the level of logging to DEBUG

logg.setLevel(logging.DEBUG)

# Messages

logg.debug("Debug Message")

logger.warning("Its a Warning")

logger.info("Just an information")

Levels of Logging:

Described in order of increasing importance

Level Function What it does

DEBUG logging.debug() Used for tracking any events that occur during program execution

INFO logging.info() Confirms the working of things at the end of the module in the program.
Level Function What it does

logging.warning( Used to flag some issues that might hinder the program from working in the
WARNING ) future, but allows it to work for now.

ERROR logging.error() Records errors that might have made the program fail at some point.

logging.critical
CRITICAL () Indicates or flags fatal errors in the program.

27. Lambda Function in Python

These are small anonymous functions in python, which can take any number of
arguments but returns only 1 expression.

Let us understand it with an example,

Consider the function which multiplies 2 numbers:

def mul(a, b):

return a * b

print(mul(3, 5))

Output:

15

The equivalent Lambda function for this function will be:

mul = lambda a, b: a * b

print(mul(3, 5))

Output:

15

The syntax for this will be as shown below:

Similarly, other functions can be written as Lambda functions too, resulting in shorter
codes for the same program logic.
28. Ternary Operator in Python

The ternary operator is used as an alternative to the if-else conditional statements


and provides a way to write a short crisp one-liner statement.

The syntax is as follows:

<expression 1> if <condition> else <expression 2>

f=2

s=2

# if the sum of f and s is greater than 0 the sum

# is printed, else 0 is printed

print(f + s if (f + s > 0) else 0)

Output:

29. *args and **kwargs in Python

We can pass a variable number of arguments to a function using special symbols


called *args and **kwargs.

The usage is as follows:

 *args: For non-keyword arguments.

Example:

# the function will take in a variable number of arguments

# and print all of their values

def tester(*argv):

for arg in argv:

print(arg)
tester('Sunday', 'Monday', 'Tuesday', 'Wednesday')

Output:

Sunday

Monday

Tuesday

Wednesday

 **kwargs: For keyword arguments.

Example:

# The function will take variable number of arguments

# and print them as key value pairs

def tester(**kwargs):

for key, value in kwargs.items():

print(key, value)

tester(Sunday = 1, Monday = 2, Tuesday = 3, Wednesday = 4)

Output:

Sunday 1

Monday 2

Tuesday 3

Wednesday 4

30. if __name__ == "__main__" in Python


__main__ is the name of the scope in which the top-level code executes. It can
check if it is running in its own scope by checking its own __name__.
Format of checking:

>>> if __name__ == "__main__":

... main()

31. Python Dataclasses

Python Classes used for storing data objects are called Dataclasses. They have
certain features like:

 Comparison with other objects of the same type is possible.


 Stores data, representing a particular data type.
Python 2.7:

The example shows the performing function of Dataclasses in older versions of


python when Dataclasses were not yet introduced.

class Self:

def __init__(self, x):

self.x = x

ob = Self("One")

print(ob.x)

Output:

One

Python 3.7:

The example shows using dataclasses in newer versions of python.

@dataclass #annotation indicates that it is a dataclass module

class Self:
x: string

ob = Self("One")

print(ob.x)

Output:

One

Note: It is compulsory to specify the datatype of each variable declared. If at any


point we don’t want to specify the type, set the type as typing.Any.

from dataclasses import dataclass

from typing import Any

@dataclass

class WithoutExplicitTypes:

name: Any

age: Any = 16

32. Python Virtual Environment

Virtual Environments are used to encapsulate certain Python Libraries of Python for
single project, which might not be used in other projects, rather than installing those
dependencies globally.

Installation Steps:

pip install virtualenv

pip install virtualenvwrapper-win

Usage Steps:

mkvirtualenv Test # Make virtual environment called Test

#setprojectdir .
deactivate # To move to something else in the command #line.

workon Test # Activate environment

33. Python Commands

Magic Commands are one of the new features added to the python shell. Basically,
they are enhancements over the normal python code, provided by the IPython
Kernel. The main syntax for these commands is that they are prefixed by as “%”
character. They prove useful in solving many common problems we encounter while
coding and also provide us some versatile shortcuts.
There are main kinds of commands:

 %prefix: The command will operate only on the given single line of code.
 %%prefix: The command will operate on the entire code block.

Some examples of these commands in Python are:

 %run: It is used for running an external file in Python.

def runner():

print("Hello World")

runner()

%run runner.py

Output:

Hello World

 %%time: This allows us to track the amount of time taken by our code for
execution.
%%time
for i in range(10000):

a = a + i**2

Output:

CPU Times: user: 3.72 ms, sys: 9us, , total: 3.73ms, Wall time: 3.75ms

 %%writefile: This command will copy content from our current code cell to
another external file.
%%writefile code.py

def func():

print("Hello")

func()

Output:

Overwriting code.py

 $pycat: This command is used to display the contents of an external file.


%pycat code.py

def func():

print("Hello")

func()

 %who: This command lists all the variables in the Python notebook.
a = "hello"

b=5

c=1
%who

Output:

abc

 %%html: This command will let us write and execute html code in the current
cell.
%%html

<html>

<body>

<table>

<tr>

<th>Name</th>

<th>Country</th>

<th>Age</th>

</tr>

<tr>

<td>Sid</td>

<td>India</td>

<td>22</td>

</tr>

<tr>

<td>Dave</td>
<td>UK</td>

<td>28</td>

</tr>

</table>

</body>

</html>

Output:

 %env: This command allows us to list all the environment variables, set a
value for such a variable, and get the value of such a variable.

 %pinfo: This command provides detailed information regarding the object


passed along with it. It works similar to that of the object? function.

Note: All the magic commands can be listed by using the %lsmagic command.
Some other useful tools for Python

 pipenv: It is a packaging tool for python aimed to solve common problems


which are associated with the typical program workflow.
 poetry: It is a dependency management and packaging tool in Python.

Conclusion

We can conclude that Python is a robust, high-level, interpreted programming


language. It is also an Object Oriented Programming Language that strongly follows
all OOPs principles. It has various inbuilt powerful modules that follow simple syntax
which makes it appealing to both beginners and experienced folks alike. A vast
collection of libraries and functions makes the development of any sort much easier
in Python. In this cheat sheet, we have covered the most common fundamentals of
python language that would help you kickstart your career in python.

#python

3 Likes22.45 GEEK
Iara Simões

6 months ago

Open options
JSON and PL/SQL: What's New in Oracle Database 23c

Explore the latest in JSON and PL/SQL! Learn how use JSON in the PL/SQL
programming language. Discover the enhancements and innovations in Oracle
Database 23c, unlocking powerful capabilities for developers.

Both JSON and PL/SQL are core Oracle Database features. In this session we give
an overview how one can use JSON in the PL/SQL programming language, for
example how PL/SQL constructs like records can be mapped to and from JSON. We
also focus on what's new in the latest 23c release.

#json #sql #oracle #database

YOUTUBE.COM
JSON and PL/SQL: What's New in
Oracle Database 23c?
Explore the latest in JSON and PL/SQL! Learn how use JSON in the PL/SQL
programming language. Discover the enhancements and innovations in Oracle
Database 23c, unlocking powerful capabilities for developers.

6.80 GEEK

Iara Simões

7 months ago

Open options

Build Real-World Web Apps with HTML,


CSS and JavaScript
Learn how to build real-world web apps with HTML, CSS, and JavaScript in this
comprehensive guide. You'll build 20 different web apps, including a blog, a portfolio,
an e-commerce store, and more.
Through a carefully curated curriculum, you'll have the opportunity to tackle a
remarkable collection of 20 projects, each designed to challenge and inspire you.
These projects are not mere exercises but real-world applications, carefully crafted
to simulate the types of challenges you'll face as a professional web developer.

As you progress through this course, you'll not only accumulate a diverse portfolio of
projects but also build a strong foundation in coding best practices. You'll learn how
to write clean, efficient, and maintainable JavaScript code, a crucial skill that
distinguishes a proficient developer from the rest. Moreover, you'll gain valuable
insights into responsive web design and user experience principles, ensuring that
your creations are both visually appealing and user-friendly.

What You'll Learn:

In this extensive course, you will:

1. Gain hands-on experience by building 20 real-world web applications from


scratch.

2. Dive into the world of web development with in-depth tutorials and practical
coding.

3. Harness the power of pure JavaScript, HTML5, and CSS3 to create responsive
and visually appealing projects.

4. Master the art of writing clean and maintainable JavaScript code, a valuable skill
for any developer.

5. Develop a strong foundation in web development, allowing you to confidently


pursue a career as a web developer or freelancer.

Projects Overview:

Throughout this course, you'll have the opportunity to work on a wide range of
projects, including:

1. Stopwatch Timer Application: Create a precise time-tracking tool.

2. Vowel Counter Application: Analyze and count vowels in a given text.

3. Poll System Application: Build a dynamic polling system for user engagement.

4. Random Password Generator Application: Generate secure and unique


passwords on the fly.

5. Cash Calculator Application: Perform financial calculations effortlessly.


6. Random HEX Card Color Generator Application: Explore color palettes for web
design.

7. Note-Taking Application: Create a user-friendly note-taking tool.

8. Dictionary Application: Develop a dictionary for quick word definitions.

9. Text Animation Project: Enhance web page visuals with captivating text
animations.

10. Mouse Wheel Zoom-In-Out Application: Implement Zoom functionality with ease.

11. Paragraph Generator Application: Generate random paragraphs for various use
cases.

12. Loan Calculator Application: Provide users with valuable financial insights.

13. Tip Calculator Application: Simplify the process of calculating tips.

14. Digital Clock Project: Display a sleek digital clock on your web page.

15. Expense Tracker Application: Manage and track expenses efficiently.

16. Fixed Deposit Calculator Application: Calculate returns on fixed deposits


effortlessly.

17. Simple To-Do List Application: Create a practical to-do list manager.

18. BMI Calculator Application: Calculate body mass index for health enthusiasts.

19. Date and Time Widget Application: Display current date and time elegantly.

20. Advanced Age Calculator Application: Calculate ages accurately with advanced
features.

Build Real-World Web Apps from Scratch with HTML, CSS and JavaScript (Part
1/3)

Build Real-World Web Apps from Scratch with HTML, CSS and JavaScript (Part
2/3)

Build Real-World Web Apps from Scratch with HTML, CSS and JavaScript (Part
3/3)

#html #css #javascript


8.25 GEEK

Iara Simões

7 months ago

Open options

Java Cheatsheet: The Essential


Reference for Every Java Developer
This Core Java Cheat Sheet has been designed by Java experts, based on the
experience of students who have recently undergone Java interviews. Whether you
are a beginner or an experienced Java developer, this Java Cheat Sheet is a
valuable resource for quickly accessing essential syntax, concepts, and best
practices related to Java Programming.

Learn Java Programming: Basics to Advanced Concepts

 Java Programming Terminologies


 Java Basics
 Java Program to Print “Hello World”
 Dataypes in Java
 Java Comments
 Java Variables
 Access Modifiers in Java
 Operators in Java
 Identifiers in Java
 Control Flow in Java
 Methods in Java
 Java Input-output (I/O operations)
 Java Polymorphism
 Java Inheritance
 Java Maths Class
 Typecasting In Java
 Arrays in Java
 Strings in Java
 Java Regex
 Java Exception Handling
 Java Commands
 Java Generics
 Java Multithreading
 Java Collections

1. Java Programming Terminologies

 JVM: executes the bytecode generated by the compiler.


 Bytecode: The Javac compiler of JDK compiles the Java source code into
bytecode so that it can be executed by JVM.
 JDK: It is a complete Java development kit that includes everything including
compiler, Java Runtime Environment (JRE), java debuggers, java docs, etc.
 JRE: allows the Java program to run, however, we cannot compile it.
 Garbage Collector: To delete or recollect that memory JVM has a program
called Garbage Collector.
 Finalize method: this function is triggered by the garbage collector just
before an object is deleted or destroyed.

2. Java Basics

Now, we will explore some of the fundamental concepts often utilized in the Java
programming language.

Object – An object refers to an entity that possesses both behavior and state, such
as a bike, chair, pen, marker, table, and car. These objects can be either tangible or
intangible, including the financial system as an example of an intangible object.

There are three characteristics of an object:

 State: The data (value) of an object is represented by its state.


 Behaviour: The functionality of an object, such as deposit, withdrawal, and so
on, is represented by the term behaviour.
 Identity: A unique ID is often used to represent an object&#x2019s
identification. The value of the ID is hidden from the outside user. The JVM
uses it internally to uniquely identify each object.
Class – A class is a collection of objects with similar attributes. It&#x2019s a
blueprint or template from which objects are made. It&#x2019s a logical thing. It
can&#x2019t be physical. In Java, a class definition can have the following
elements:
 Modifiers: A class can be private or public, or it can also have a default
access level
 class keyword: To construct a class, we use the class keyword.
 class name: The name of the class should usually start with a capital letter.
 Superclass (optional): If the class has any superclass, we use the extends
keyword and we mention the name of the superclass after the class name.
 Interface (optional): If the class implements an interface, we use the
implements keyword followed by the name of the interface after the class
name.
Constructors: In Java, a constructor is a block of code similar to a method.
Whenever a new class instance is created, the constructor is called. The memory
allocation for the object only happens when the constructor is invoked.

There are two types of constructors in Java. They are as follows:-

Default Constructor – A default constructor is a type of constructor that does not


require any parameters. When we do not declare a constructor for a class, the
compiler automatically generates a default constructor for the class with no
arguments.

Parameterised Constructor – A parameterized constructor is a type of constructor


that requires parameters. It is used to assign custom values to a class’s fields during
initialization.

Keyword – In Java, Reserved words are also known as keywords. These are
particular terms that hold specific meanings. Java has 61 Reserved Keywords that
are predefined and cannot be used as variable, object, or class names. Here’s a list
of the keywords used in Java:-

Keyword Use Case

abstract Used to declare an abstract class or abstract method

assert Used to check assertions during debugging

boolean Represents a boolean value (true or false)

break Exits from a loop or a switch statement

byte Represents a signed 8-bit integer

case Used in a switch statement to define a case

catch Catches exceptions thrown in a try block

char Represents a 16-bit Unicode character

class Declares a class

const* Not used in Java, reserved for future use


Keyword Use Case

continue Skips the rest of the loop and starts the next iteration

default Used in a switch statement as a default case

do Starts a do-while loop

double Represents a 64-bit double-precision floating-point number

else Used in an if-else statement

enum Declares an enumeration type

exports Used in module declarations to specify exported packages

extends Indicates a class is derived from another class

final Declares a variable, method, or class as final (unchangeable)

finally Defines a block of code to be executed after try-catch

float Represents a 32-bit single-precision floating-point number

for Starts a for loop

goto* Not used in Java, reserved for future use

if Used in an if statement

implements Indicates a class is implementing an interface

import Imports classes, packages, or individual members

instanceof Tests if an object is an instance of a specific class

int Represents a 32-bit integer

interface Declares an interface

long Represents a 64-bit integer

module* Defines a module, reserved for future use

native Indicates a method is implemented in platform-specific code

new Creates a new object

open Used in module declarations to specify open packages

opens Used in module declarations to specify opened packages

private Defines a private access modifier


Keyword Use Case

protected Defines a protected access modifier

provides Used in module declarations to specify service providers

public Defines a public access modifier

requires Used in module declarations to specify required modules

return Exits a method and returns a value

short Represents a 16-bit integer

static Declares a static variable or method

strictfp Ensures consistent floating-point calculations

super Refers to the parent class

switch Selects one of many code blocks to be executed

synchronized Defines a synchronized block or method

this Refers to the current instance of the class

throw Throws an exception

throws Declares exceptions that a method may throw

to Used in switch expressions to specify case values

transient Indicates a member variable should not be serialized

while Starts a while loop

transitive Used in module declarations to specify transitive dependencies

try Defines a block of code to be tested for exceptions

uses Used in module declarations to specify service uses

void Defines a method that does not return a value

volatile Indicates a variable may be modified by multiple threads

with Used in switch expressions to specify pattern matching

_ Reserved for future use

3. Java Program to Print “Hello World”


// Java Program to Print

// Hello World

class GFG {

public static void main (String[] args) {

System.out.println("Hello World!");

Output

Hello World!

Editing, Compiling, and Executing

4. Data Types in Java

Data Types in Java are the different values and sizes that can be stored in the
variable according to the requirements.

Java Datatype are further two types:-

1. Primitive Data Type in Java


In Java, primitive data types serve as the foundation for manipulating data. They are
the most basic types of data that the Java programming language uses. Java has
several primitive data types, including:

Type Size Example Literals Range of values

boolea 1 bit true, false true, false


n
Type Size Example Literals Range of values

8 -128 to 127
byte
bits (none)

characters representation of
ASCII values
char &#x2018a&#x2019, &#x2018\u0041&#x2019,
16 &#x2018\101&#x2019, &#x2018\\&#x2019, &#x2018\ 0 to 255
bits &#x2019, &#x2018\n&#x2019, &#x2018β&#x2019

16 -32,768 to 32,767
short
bits (none)

-2,147,483,648

to
int

32 2,147,483,647
bits -2,-1,0,1,2

-9,223,372,036,854,775,808

to
long

64 9,223,372,036,854,775,807
bits -2L,-1L,0L,1L,2L

32 upto 7 decimal digits


float
bits 1.23e100f , -1.23e-100f , .3f ,3.14F

upto 16 decimal digits


double 64
bits 1.23456e300d , -123456e-300d , 1e1d

2. Non-primitive Data Type


Non-primitive datatypes are created from primitive datatypes. Examples of non-
primitive datatypes include arrays, stacks, and queues.

5. Java Comments

There are three types of comments in Java

1. Single Line comment


To comment on a single line of code, you can use a double forward slash “//”
followed by your message. This syntax is commonly used for coding.

/*package whatever //do not write package name here */

import java.io.*;

class GFG {

public static void main(String[] args)

System.out.println("GFG!");

// System.out.println("Thi line is not executed");

Output

GFG!

2. Multi-line comment
If you need to comment on multiple lines of code, you can utilize the syntax of a
double forward slash “/*”. Simply enter your message between the two symbols, and
complete the comment with “*/”. This is a widely used syntax in coding.

/*package whatever //do not write package name here */

import java.io.*;
class GFG {

public static void main(String[] args)

System.out.println("GFG!");

/* System.out.println("This line is Ignored ny

comiler"); System.out.prinln("Including this");

*/

Output

GFG!

3. JavaDoc Type Comment


When working on a project or software package, it is often helpful to use this method
as it can assist in creating a documentation page for reference. This page can
provide information on available methods, their parameters, and more, making it a
useful tool for learning about the project.

Syntax:

/** Comment starts

*This is

*sample comment */

6. Java Variables

Variables are the containers that save the data values. Each variable is assigned
according to the data type it is assigned.

Syntax:
data_type var_name;

Types of Variables

There are 3 types of Data types in Java as mentioned below:

1. Local Variables
A variable defined within a block or method or constructor is called a local variable.

2. Instance Variables
Instance variables are non-static variables and are declared in a class outside of any
method, constructor, or block.

3. Static Variables
Static variables are also known as class variables. The static variables are declared
using the static keyword within a class outside of any method, constructor, or block.
Below is the Example of the above topic:

// Java Program to demonstrate

// Variables

import java.io.*;

class GFG {

// instance variable

public int revise;

// static variable

public static int count = 0;

public static void help(int i)

{
// here int i is local variable

// changes will not affect original value

GFG.count++;

System.out.println(i);

public static void main(String[] args)

// local variable

int i = 10;

System.out.println("Before Calling function count:"

+ GFG.count);

help(i);

System.out.println("After Calling function count:"

+ GFG.count);

GFG temp = new GFG();

temp.revise = i + count;
System.out.println("Instance variable value:"

+ temp.revise);

Output

Before Calling function count:0

10

After Calling function count:1

Instance variable value:11

7. Access Modifiers in Java

Access modifiers help to restrict the scope of a class, constructor, variable, method,
or data member. It provides security, accessibility, etc to the user depending upon
the access modifier used with the element

Types of Access Modifiers in Java

There are four types of access modifiers available in Java:

 Default &#x2013 No keyword required


 Private
 Protected
 Public
8. Operators in Java

Comparison Operators are the Operators which return a boolean value as the result
means the answer will be either true or false.
Operators Meaning True False

== Equal 1==1 1==2

!= Not Equal 1!=2 1!=1

< Less Than 1<2 2<1

<= Less Than Equal to 1<=1 2<=1

> Greater Than 3>2 2>3

>= Greater Than Equal to 3>=3 2>=3

Precedence and Associativity of Operator in Java

Here is the table representing the precedence order of Java operators from high to
low as we move from top to bottom.

Operators Associativity Type

++, &#x2013 Right to Left Unary postfix

++, –, +, -, ! Right to Left Unary prefix

/, *, % Left to Right Multiplicative

+, – Left to Right Additive

<, <=, >, >= Left to Right Relational

==, !== Left to Right Equality

& Left to Right Boolean Logical AND

^ Left to Right Boolean Logical Exclusive OR

| Left to Right Boolean Logical Inclusive OR

&& Left to Right Conditional AND

|| Left to Right Conditional OR

?: Right to Left Conditional

=, +=, -=, *=, /=, %= Right to Left Assignment

9. Identifiers in Java

The name that we give to the class, variable, and methods are formally called
identifiers in Java. and for defining Identifier there are some rules of it we need to
take care of that while defining Identifiers.
Rules of defining Java identifiers:-

 Valid Java Identifiers have strict guidelines to avoid compile-time errors.


Similar rules apply to C and C++
 Only letters (both upper and lowercase), numbers, dollar signs, and
underscores are allowed as identifiers in Java. Special characters like “@” are
not permitted.
 Numbers should not be used to begin identifiers ([0-9]).
&#x201c123geeks,&#x201d for example, is not a valid Java identifier.
 Case matters when it comes to Java Identifiers. For example
&#x2018bit&#x2019 and &#x2018BIT&#x2019 would be considered as
different identifiers in Java.
 The length of the identifier is not limited, however, it is recommended that it be
kept to a maximum of 4&#x201315 letters.
 Using reserved words as identifiers is not allowed in Java. This includes the
term “while,” as it is one of the 53 reserved terms.
 The length of the identifier is not limited, however, it is recommended that it be
kept to a maximum of 4&#x201315 letters.

10. Control Flow in Java

1. If, else-if, else

// Java Program to implement

// if - else if - else

import java.io.*;

// Driver Class

class GFG {

// main function

public static void main(String[] args)

int a = 1, b = 2;
if (a < b)

System.out.println(b);

else if (a > b)

System.out.println(a);

else

System.out.println(a + "==" + b);

Output

2. Nested if – else
A nested if is an if statement that is the target of another if or else. Nested if
statements mean an if statement inside an if statement.

// Java program to illustrate nested-if statement

import java.util.*;

class NestedIfDemo {

public static void main(String args[])

int i = 10;

if (i == 10 || i < 15) {
// First if statement

if (i < 15)

System.out.println("i is smaller than 15");

// Nested - if statement

// Will only be executed if statement above

// it is true

if (i < 12)

System.out.println(

"i is smaller than 12 too");

else {

System.out.println("i is greater than 15");

Output

i is smaller than 15

i is smaller than 12 too

2. Switch Statement

// Java program to Demonstrate Switch Case


// Driver class

public class GFG {

// main driver method

public static void main(String[] args)

int day = 5;

String dayString;

// Switch statement with int data type

switch (day) {

// Case

case 1:

dayString = "Monday";

break;

// Case

case 2:

dayString = "Tuesday";
break;

// Case

case 3:

dayString = "Wednesday";

break;

// Case

case 4:

dayString = "Thursday";

break;

// Case

case 5:

dayString = "Friday";

break;

// Case

case 6:

dayString = "Saturday";

break;
// Case

case 7:

dayString = "Sunday";

break;

// Default case

default:

dayString = "Invalid day";

System.out.println(dayString);

Output

Friday

Loops in Java

Loops are used for performing the same task multiple times. There are certain loops
available in Java as mentioned below:

1. For Loop
2. While Loop
3. do-while

// Java Program to implement


// For loop

import java.io.*;

// Driver Class

class GFG {

// Main function

public static void main(String[] args)

int n = 5;

for (int i = 1; i <= n; i++) {

System.out.println(i);

// Java Program to demonstrate

// the working of while loop

import java.io.*;

// Driver Class

class GFG {

// main function
public static void main(String[] args)

int i = 16;

// Working of while loop

while (i != 0) {

System.out.println(i);

if (i > 4)

i -= 4;

else

i -= 1;

// Java Program to demonstrate

// do-while loop

// Driver Class

class GFG {

// main function
public static void main(String[] args)

int i = 1;

do {

System.out.println(i);

i++;

} while (i <= 5);

Output

11. Methods in Java

Java Methods are collections of statements that perform some specific task and
return the result.

Syntax of Method

<access_modifier> <return_type> <method_name>( list_of_parameters)

//body
}

Below is the implementation of the above method:

// Java Program to demonstrate the

// Use of Methods

import java.io.*;

// Driver Class

class GFG {

public static int sum(int i, int j) { return i + j; }

// main method

public static void main(String[] args)

int n = 3, m = 3;

for (int i = 0; i < n; i++) {

for (int j = 0; j < m; j++) {

System.out.print(sum(i, j) + " ");

System.out.println();

}
}

Output

012

123

234

12. Java Input-output (I/O operations)

We can only print using System.out but can use different print varieties in it:

1. print

The cursor remains on the same line

System.out.print(" GFG " + x);

2. println

Cursor Moves to a new line

System.out.println(" GFG " + x);

3. printf

The cursor remains on the same line

System.out.printf(" GFG %d",x);

Formatted Print

System.out.printf("%7.5f", Math.PI);

Explanation of the above statement:

7 is the Field width and .5 is the precision fo the floating number printed . So,
answer will be 3.14159

Taking Input in Java

1. Parsing Command-line arguments


We can take input using the Command line simp

// Java Program to take Input

// from command line arguments

class GFG {

public static void main(String args[])

for (int i = 0; i < args.length; i++)

System.out.println(args[i]);

javac GFG.java

java GFG This is just to check 2

Output:

This

is

just

to

Check

2. Buffer Reader Class


InputStreamReader() is a function that converts the input stream of bytes into a
stream of characters so that it can be read as BufferedReader expects a stream of
characters.

Below is the implementation of the above method:

// Java Program for taking user

// input using BufferedReader Class

import java.io.*;

class GFG {

// Main Method

public static void main(String[] args)

throws IOException

// Creating BufferedReader Object

// InputStreamReader converts bytes to

// stream of character

BufferedReader bfn = new BufferedReader(

new InputStreamReader(System.in));

// String reading internally

String str = bfn.readLine();


// Integer reading internally

int it = Integer.parseInt(bfn.readLine());

// Printing String

System.out.println("Entered String : " + str);

// Printing Integer

System.out.println("Entered Integer : " + it);

Output:

ABC

11

Entered String : ABC

Entered Integer : 11

3. Scanner Class

Syntax:

Scanner scn = new Scanner(System.in);

Below is the implementation of the above method:

// Java Program to take input using

// Scanner Class in Java

import java.io.*;
import java.util.Scanner;

class GFG {

public static void main(String[] args)

// creating the instance of class Scanner

Scanner obj = new Scanner(System.in);

String name;

int rollno;

float marks;

// taking string input

System.out.println("Enter your name");

name = obj.nextLine();

// taking float input

System.out.println("Enter your marks");

marks = obj.nextFloat();

// printing the output

System.out.println("Name :" + name);


System.out.println("Marks :" + marks);

Output:

ABC

65

Name :ABC

Marks :65

13. Java Polymorphism

Polymorphism: It is the ability to differentiate between entities with the same name
efficiently.

Compile-time polymorphism: Static polymorphism, also called compile-time


polymorphism, is achieved through function overloading in Java. Static
polymorphism, also called compile-time polymorphism, is achieved through function
overloading in Java.

Method Overloading: If there are multiple functions that have the same name but
different parameters, it is known as overloading. Alterations in the number or type of
arguments can result in the overloading of functions.

Example:

// Java Program to demonstrate

// Polymorphism

import java.io.*;

// Class

class ABC {
// Sum Method with int returning value

public int sum(int x, int y) { return x + y; }

// Sum Method with float returning value

public double sum(double x, double y) { return x + y; }

// Driver Class

class GFG {

// main function

public static void main(String[] args)

ABC temp = new ABC();

System.out.println(temp.sum(1, 2));

System.out.println(temp.sum(3.14, 4.23));

Output

7.370000000000001
14. Java Inheritance

Inheritance: It is the mechanism in Java by which one class is allowed to inherit the
features (fields and methods) of another class.

// Java Program to demonstrate

// Inheritance (concise)

import java.io.*;

// Base or Super Class

class Employee {

int salary = 70000;

// Inherited or Sub Class

class Engineer extends Employee {

int benefits = 15000;

// Driver Class

class Gfg {

public static void main(String args[])

Engineer E1 = new Engineer();


System.out.println("Salary : " + E1.salary

+ "\nBenefits : " + E1.benefits);

Output

Salary : 70000

Benefits : 15000

15. Java Maths Class

In Java, there exists a Math Library that can simplify intricate calculations

Library:

import java.lang.Math;

Use:

Math.function_name <parameters>

Functions Returns or Calculates

min( int a,int b ) minimum of a and b

max( int a,int b ) maximum of a and b

sin( int θ ) sine of θ

cos( int θ ) cosine of θ

tan( int θ) tangent of θ

toRadians( int θ ) Convert angle in degrees(θ) to radians

toDegrees( int θ ) Convert angle int radians(θ) to degrees

exp( int a ) exponential value ea

log( int a ) natural log -> logea


Functions Returns or Calculates

pow( int a, int b ) power ab

round( double a ) round to the nearest integer

random() returns the random value in [0,1)

sqrt( int a ) the square root of a

E value of e (constant value)

PI Value of π(constant value)

Note: All the functions mentioned above can be used with either data-types not
bounded any single data-types.

16. Typecasting In Java

1. Type Casting in Java

Type Casting is a method in which we convert from one data type to another.

2. Type Conversion in Java

Type Conversion in Java is a technique where we can convert from double, int, and
float to double.

Below is the implementation of the above methods:

// Java Program to Implement

// Type Casting of the Datatype


import java.io.*;

// Main class

public class GFG {

// Main driver method

public static void main(String[] args)

int a = 3;

// Casting to Large datatype

double db = (double)a;

// Print and display the casted value

System.out.println(db);

// Java Program to illustrate

// Type Conversion

import java.io.*;

// Driver Class
class GFG {

// main function

public static void main(String[] args)

long a = 1;

byte b = 1;

double c = 1.0;

// Type Conversion

double final_datatype = (a + b + c);

// Printing the sum of all three initialized values

System.out.print(final_datatype);

Output

3.0

17. Arrays in Java

Arrays are the type of data structure that can store data of similar data types. Arrays
are allocated in contiguous memory allocation with a fixed size.

Syntax:

// Both Methods are correct

int arr[]=new int[20];


int[] arr=new int[20];

Below is the implementation of the above method:

// Java Program to implement

// arrays

class GFG {

public static void main(String[] args)

// declares an Array of integers.

int[] arr = new int[5];

// Allocating memory to the

// elements

arr[0] = 10;

arr[1] = 20;

arr[2] = 30;

arr[3] = 40;

arr[4] = 50;

// accessing the elements of the specified array

for (int i = 0; i < arr.length; i++)

System.out.println("arr[" + i + "] :" + arr[i]);


}

Output

arr[0] :10

arr[1] :20

arr[2] :30

arr[3] :40

arr[4] :50

Multidimensional Arrays in Java

Arrays are not bounded to be single-dimensional but can store elements in


multidimensional.

Syntax:

int[][] arr= new int[3][3];

int arr[][]=new int[3][3];

Below is the implementation of the above method:

// Java Program to implement

// 2-D dimensional array

// driver class

public class multiDimensional {

// main function

public static void main(String args[])


{

// declaring and initializing 2D array

int arr[][]

= { { 1, 2, 3 }, { 4, 5, 6 }, { 7, 8, 9 } };

// printing 2D array

for (int i = 0; i < 3; i++) {

for (int j = 0; j < 3; j++)

System.out.print(arr[i][j] + " ");

System.out.println();

Output

123

456

789

18. Strings in Java

Strings are the type of objects that can store the character of values. A string acts
the same as an array of characters in Java.

Syntax:
String abc=" ";

CharSequence Interface in Java

1. StringBuffer

StringBuffer s = new StringBuffer("GeeksforGeeks");

2. StringBuilder

StringBuilder str = new StringBuilder();

str.append("GFG");

3. String Tokenizer

public StringJoiner(CharSequence delimiter)

19. Java Regex

Regular Expressions, or Regex for short, is a Java API that allows users to define
String patterns for searching, manipulating, and modifying strings. It is commonly
used for setting limits on various areas of strings such as email validation and
passwords. The java.util.regex package contains regular expressions and consists of
three classes and one interface. The following table lists the three classes included
in the java.util.regex package:

Class Description

util.regex.Pattern It is used to define patterns.

util.regex.Matcher It is used to conduct match operations on text using patterns.

PatternSyntaxException In a regular expression pattern, it’s used to indicate a syntax problem.

Pattern class: This class does not have any public constructors. Instead, it consists
of a group of regular expressions that can be utilized to define different types of
patterns. To do this, simply execute the compile() method with a regular expression
as the first input. After execution, the method will return a pattern.

The table below provides a list of the methods in this class along with their
descriptions.

Method Description

compile(String regex) Compiles a regular expression into a pattern.

compile(String regex, int flags) Turns a regular expression into a pattern using the flags provided.
Method Description

flags() Gets the match flags for this pattern.

matcher(CharSequence input) Builds a matcher that compares the given input to the pattern.

matches(String regex,
CharSequence input) Matches a regular expression and tries to match it against the given input.

pattern() Gets the regular expression that was used to create this pattern.

quote(String s) Generates a literal pattern String from the given String.

split(CharSequence input) Splits the given input sequence around patterns that match this pattern.

split(CharSequence input, int Divides the given input sequence into sections based on matches to this pattern.
limit) The number of times the pattern is applied is controlled by the limit parameter.

toString() Returns the pattern’s string representation.

Matcher Class: To evaluate previously described patterns through match operations


on an input string in Java, the ‘object’ is utilized. No public constructors are defined
here. One can execute a matcher() on any pattern object to achieve this. The table
below displays the methods present in this class along with their descriptions:To
evaluate previously described patterns through match operations on an input string
in Java, the ‘object’ is utilized. No public constructors are defined here. One can
execute a matcher() on any pattern object to achieve this.

The table below displays the methods present in this class along with their
descriptions:

Method Description

find() find() is mostly used to look for multiple occurrences of regular expressions in a text.

find(int start) It is used to find occurrences of regular expressions in the text starting from the provided index.

start() start() is used to retrieve the start index of a match found with the find() method.

end() It’s used to acquire the end index of a match discovered with the find() method.

groupCount() groupCount() is a function that returns the total number of matched subsequences.

matches() It’s used to see if the pattern matches the regular expression.

20. Java Exception Handling

Exception:– An Exception is an unexpected error that occurs during the run-time of


a program.

Error vs Exception: What is the difference?


When a program encounters an error, it means there is a significant issue that a
well-designed program should not try to fix. On the other hand, an exception
indicates a particular situation that a well-designed program should try to handle.

Types of Exceptions:-

Checked Exception:- This mainly includes IO Exceptions and Compile time


Exceptions

Unchecked Exceptions:– This covers both Runtime Exceptions and Null Pointer
Exceptions.

Handle Exceptions
try block: The try block comprises a set of statements that may throw an exception.

Catch Block: When there is an uncertain condition in the try block, the catch block
comes in handy to handle it. It is mandatory to have a catch block right after the try
block to handle any exceptions that may be thrown by the try block.

Finally Block: When programming in Java, the finally block is a section of code that
will always run, regardless of whether or not an exception has been caught. If there
is a catch block following a try block, it will be executed before the finally block.
However, if there is no catch block, the finally block will be executed immediately
after the try block.

Example:-

try {

// block of code to monitor for errors


// the code you think can raise an exception

} catch (ExceptionType1 exOb) {

// exception handler for ExceptionType1

} catch (ExceptionType2 exOb) {

// exception handler for ExceptionType2

// optional

finally { // block of code to be executed after try block ends

final vs finally vs finalize


Below is a table that outlines the distinctions between the terms final, finally, and
finalize:

final

 A final keyword can be used with classes, methods, and variables.


 A final class cannot be inherited.
 A final method cannot be overridden.
 A final variable cannot be reassigned.
finally

 A finally block is always executed, regardless of whether an exception is


thrown or not.
 The finally block is executed after the try block and catch block, but before the
program control returns to the calling method.
 The finally block can be used to close resources, such as files and database
connections.
finalize
 The finalize() method is called by the garbage collector when an object is no
longer needed.
 The finalize() method can be used to perform cleanup operations, such as
releasing resources or writing data to a file.
 The finalize() method is not guaranteed to be called, so it should not be used
to perform critical operations.
throw keyword:- When using Java, the throw keyword is utilized to throw an
exception from a block of code or a method. It is possible to throw either a checked
or unchecked exception. The throw keyword is frequently used for throwing custom
exceptions.

throws keyword:- If a try/catch block is not present, the throws keyword can be
used to manage exceptions. This keyword specifies the specific exceptions that a
method should throw if an exception happens.

21. Java Commands

Here are the most commonly used Java commands:

 java -version : Displays the version of the Java Runtime Environment (JRE)
that is installed on your computer.
 java -help: Displays a list of all of the Java commands.
 java -cp: Specifies the classpath for the Java program that you are running.
 java -jar: Runs a Java Archive (JAR) file.
 java -D: Sets a system property.
 java -X: Specifies a non-standard option for the Java Virtual Machine (JVM).

Here are some other useful Java commands:

 javac: Compiles a Java source file into bytecode.


 javap: Disassembles a Java class file.
 jdb: A Java debugger.
 jconsole: A Java monitoring and management tool.
 jvisualvm: A Java profiling and diagnostic tool.

22. Java Generics

Generics means parameterized types. The idea is to allow type (Integer, String,
&#x2026 etc., and user-defined types) to be a parameter to methods, classes, and
interfaces. Using Generics, it is possible to create classes that work with different
data types. An entity such as class, interface, or method that operates on a
parameterized type is a generic entity.

Types of Java Generics

Generic Method: Generic Java method takes a parameter and returns some value
after performing a task. It is exactly like a normal function, however, a generic
method has type parameters that are cited by actual type. This allows the generic
method to be used in a more general way. The compiler takes care of the type of
safety which enables programmers to code easily since they do not have to perform
long, individual type castings.

// To create an instance of generic class

BaseType <Type> obj = new BaseType <Type>()

Generic Functions: We can also write generic functions that can be called with
different types of arguments based on the type of arguments passed to the generic
method. The compiler handles each method.

// Java program to show working of user defined

// Generic functions

class Test {

// A Generic method example

static<T> void genericDisplay(T element)

System.out.println(element.getClass().getName()

+ " = " + element);

// Driver method

public static void main(String[] args)

// Calling generic method with Integer argument

genericDisplay(11);
// Calling generic method with String argument

genericDisplay("GeeksForGeeks");

// Calling generic method with double argument

genericDisplay(1.0);

Output

java.lang.Integer = 11

java.lang.String = GeeksForGeeks

java.lang.Double = 1.0

23. Java Multithreading

Multithreading is a Java feature that allows concurrent execution of two or more


parts of a program for maximum utilization of CPU. Each part of such program is
called a thread. So, threads are light-weight processes within a process.

Threads can be created by using two mechanisms :

 Extending the Thread class


 Implementing the Runnable Interface
Example: – Thread creation by extending the Thread class

To create a new thread in Java, we can extend the java.lang.Thread class and
override its run() method. This is where the thread’s execution starts. Then, we can
create an instance of our class and call the start() method to begin the execution of
the thread. The start() method will then call the run() method of the Thread object.

class MultithreadingDemo extends Thread {


public void run()

try {

// Displaying the thread that is running

System.out.println(

"Thread " + Thread.currentThread().getId()

+ " is running");

catch (Exception e) {

// Throwing an exception

System.out.println("Exception is caught");

// Main Class

public class Multithread {

public static void main(String[] args)

int n = 8; // Number of threads

for (int i = 0; i < n; i++) {


MultithreadingDemo object

= new MultithreadingDemo();

object.start();

Output

Thread 15 is running

Thread 17 is running

Thread 14 is running

Thread 12 is running

Thread 13 is running

Thread 18 is running

Thread 11 is running

Thread 16 is running

24. Java Collections

The collection is a framework in Java that provides an architecture to store and


manipulate objects in Java. It contains the interface as mentioned below:

 List Interface
 Queue Interface
 Deque Interface
 Set Interface
 SortedSet Interface
 Map Interface
 Collection Interface
 Iterable Interface

Syntax of the Interfaces:

Interfaces Syntax

Iterable Interface Iterator iterator();

List <T> al = new ArrayList<> ();

List <T> ll = new LinkedList<> ();


List Interface
List <T> v = new Vector<> ();

Queue <T> pq = new PriorityQueue<> ();

Queue Interface
Queue <T> ad = new ArrayDeque<> ();

Deque Interface Deque<T> ad = new ArrayDeque<> ();

Set<T> hs = new HashSet<> ();

Set<T> lhs = new LinkedHashSet<> ();


Set Interface
Set<T> ts = new TreeSet<> ();

Sorted Set Interface SortedSet<T> ts = new TreeSet<> ();


Interfaces Syntax

Map<T> hm = new HashMap<> ();

Map Interface
Map<T> tm = new TreeMap<> ();

Why Use Java?


Java is simple for programmers to learn. Java is frequently chosen as the first
programming language to learn. Furthermore, the sector continues to benefit from
Java’s prominence. The majority of websites and apps in the government,
healthcare, defence, and educational sectors continue to use Java technology. Java
is thus worthwhile to learn and use. If you choose a career in Java, you can follow a
number of different career routes. Almost anything that Java can accomplish.

Why is Java so Popular?


Because Java includes a unique tool called the Java Virtual Machine that ensures
the code functions consistently everywhere, it is feasible for Java to execute without
any issues on many types of computers and machines. This makes Java a popular
programming language. A rule in Java also known as WORA states that code only
has to be written once and may execute anywhere. Java’s high level of security,
which shields the code from hackers, viruses, and other dangers, is another factor in
its popularity. Java also enables the creation of many jobs that may run concurrently
within a programme, making it quicker and more effective. Java provides a clever
method for generating code that primarily concentrates on.

Features of Java
 Java is an Object Oriented Programming language.
 Java is Platform Independent because it comes with its own platform to run
applications.
 Simple to learn programming language because doesn&#x2019t contain
Pointers and operator overloading.
 Java is secure because the Java program runs on Java virtual machine(JVM)
so, if there is any problem occurred in the program it will remain inside the
JVM only, it will not affect the operating system.
 Java is Architecture neutral because it is independent of the platform so we
do not have to design the program for different devices differently.
 Java is portable because, after the compilation of any Java program, it
generates a bytecode that can run on any machine which has JVM.
 Java is Robust means Java comes with automatic garbage collection
management and strong exception handling.
 Java supports multithreading, It is possible in Java that we can divide a
program into two or many subprograms and run these programs/threads at
the same time.
Applications of Java Programming language
 Mobile Applications
 Desktop GUI Applications
 Artificial intelligence
 Scientific Applications
 Cloud Applications
 Embedded Systems
 Gaming Applications

#java

5.10 GEEK

Iara Simões

7 months ago

Open options

10 Best Unity Books for Beginners and


Experienced Developers
Learn Unity game development from scratch or take your skills to the next level with
these 10 best Unity books.

Whether you're a beginner or an experienced developer, these 10 Unity books will


help you take your game development skills to the next level. Learn everything from
the basics of Unity to advanced topics such as scripting, 3D modeling, and AI. This
guide is perfect for anyone who wants to create their own video games using Unity.

📘 15 Best C# Books for Beginners and Experts


1. Unity in Action

Check Price

Key Information
Author: Joe Hocking Publisher: Manning

Pages: 416 Edition: 3rd

Publish Date: February 2022 Level: Beginner

Rating: 4.9/5 Formats: Paperback and Kindle

Why we chose this book

If you’re looking for the best book to learn Unity, this practical and hands-on
beginner's guide to Unity game development is designed for programmers who are
new to Unity but have previous experience with object-oriented programming.

Expect to learn about 2D, 3D, and AR/VR game creation using C# along with a wide
range of topics like character creation, 3D first-person shooters, 2D card games, and
online play. The third edition has also been updated to include augmented and
virtual reality toolkits.

Features

 Comprehensive overview of game development using Unity and C#


 Offers a variety of game projects for hands-on experience
 Covers 2D, 3D, and AR/VR game creation

2. Introduction to Game Design, Prototyping, and Development

Check Price

Key Information

Author: Jeremy Gibson Bond Publisher: Addison-Wesley Professional

Pages: 1296 Edition: 3rd


Publish Date: September 2022 Level: Intermediate

Rating: 5/5 Formats: Paperback and Kindle

Why we chose this book

A comprehensive guide for aspiring game developers who are interested in learning
the ins and outs of game design theory, prototyping, and programming using Unity
2020.3 LTS (Long Term Support).

The book covers topics like game mechanics, narrative design, user experience, and
rapid iterative prototyping — a crucial aspect of game development. It also features a
chapter on Data-Oriented Tech Stack (DOTS) and coding challenges to help readers
apply their knowledge. By the end of this book, you’ll be well on your way to
mastering Unity 2D game and 3D prototypes.

Features

 Covers game design theory, rapid iterative prototyping, and practical


programming
 Built-in game tutorials and coding challenges
 Includes a chapter on Unity's high-performance Data-Oriented Tech Stack
(DOTS)

3. Unity Game Development Cookbook

Check Price

Key Information

Author: Paris Buttfield-Addison, Jon Manning, and Tim Nugent Publisher: O'Reilly Media

Pages: 408 Edition: 1st

Publish Date: April 2019 Level: Intermediate

Rating: 4.6/5 Formats: Paperback and Kindle

Why we chose this book


A valuable resource for intermediate game developers who want to take their Unity
skills to the next level. It’s best suited for those who have some knowledge of C#
programming and want to learn how to use Unity to its full potential.

The book is a collection of recipes that provide practical solutions to common


gameplay scenarios while teaching specific features of the Unity game engine. It
covers a wide range of topics, including gameplay mechanics, character behavior,
and animation. The recipes also cover advanced topics such as artificial intelligence,
multiplayer networking, and virtual reality.

Features

 Collection of recipes that teach specific features of the Unity game engine
 Solutions to common gameplay scenarios, such as keeping score
 Coverage of 2D and 3D graphics, animation, behavior, sound, and scripting

4. Learning C# by Developing Games With Unity

Check Price

Key Information

Author: Harrison Ferrone Publisher: Packt Publishing

Pages: 458 Edition: 7th

Publish Date: November 2022 Level: Beginner

Rating: 4.6/5 Formats: Paperback and Kindle

Why we chose this book

This is an engaging introduction to Unity game development using C# programming.


It's designed to help readers create a playable game prototype from scratch and is
suitable for anyone who wants to learn Unity.
The book covers a wide range of Unity fundamentals, including game objects,
components, and scripting. It also delves into more advanced topics such as
character movement, shooting mechanics, and AI. By the end of the book, readers
will have the knowledge and skills to create their own first-person shooter game
prototype using Unity.

Features

 Covers the fundamentals of game programming concepts, including collision


detection
 Has readers build a working first-person shooter game prototype
 Contains an invitation to join the online Unity Game Development community

5. Unity Game Development in 24 Hours

Check Price

Key Information

Author: Mike Geig Publisher: Sams Publishing

Pages: 464 Edition: 4th

Publish Date: November 2021 Level: Beginner

Rating: 4.8/5 Formats: Paperback and Kindle

Why we chose this book

This is a straightforward and easy-to-follow approach to learning the Unity game


engine. It consists of 24 lessons of one hour or less, covering everything from the
basics to advanced topics. It’s designed for complete beginners who want to learn
Unity game development.

The book includes tutorials on creating 2D games, using graphical asset pipelines,
and leveraging mobile device accelerometers for gameplay. By the end, readers will
have a solid understanding of Unity’s features and be able to create their own
games.
Features

 Step-by-step instructions to walk you through common Unity game


development tasks
 Four sample game projects to illustrate the concepts covered in the book
 Quickly create game objects with prefabs

6. C#: 3 Books in 1

Check Price

Key Information

Author: Mark Reed Publisher: Independently published

Pages: 344 Edition: 1st

Publish Date: September 2022 Level: Beginner to Advanced

Rating: 4.5/5 Formats: Paperback and Kindle

Why we chose this book

An interactive guide to learning C# programming that is broken down into three


books, making it easy to follow along regardless of your level of expertise. It's
designed for developers of all levels who want to improve their programming skills
and learn C# in a practical, hands-on way.

If you want to develop games with Unity, this book covers everything from the basics
of C# to more advanced concepts and strategies such as asynchronous
programming and type reflection. So while it’s focused on C# programming, it's a
great resource for learning C# fundamentals for Unity game development.

Features

 Contains three books, covering beginner, intermediate, and advanced C#


programming
 Offers practical experience using essential tools and strategies
7. Unity From Zero to Proficiency (Foundations)

Check Price

Key Information

Author: Patrick Felicia Publisher: Independently published

Pages: 240 Edition: 1st

Publish Date: February 2019 Level: Beginner

Rating: 4.5/5 Formats: Paperback, Kindle, and Audiobook

Why we chose this book

An easy-to-follow introduction to game development in C# using Unity, perfect for


those who have no prior knowledge of programming. It's designed for parents or
teachers who want to introduce young learners to game development and hobbyists
just getting started with Unity.

The book teaches readers the best practices for creating realistic 2D and 3D
environments, starting with the basics of Unity and working up to more advanced
techniques. It contains lessons on creating a 3D maze, designing various
landscapes, and exporting games to the web.

Features

 Designed for beginners who want to learn skills over time


 Motivates readers by providing challenges at the end of each chapter
 Provides detailed explanations and instructions on each concept

8. Hands-On Unity 2022 Game Development


Check Price

Key Information

Author: Nicolas Alejandro Borromeo Publisher: Packt Publishing

Pages: 712 Edition: 3rd

Publish Date: October 2022 Level: Beginner

Rating: 4.6/5 Formats: Paperback and kindle

Why we chose this book

This is a comprehensive guide to multiplatform game development with Unity for


those who are interested in building commercial-quality games. It’s designed for
developers who want to migrate or start building 3D games in Unity.

The book covers all aspects of game development, from the fundamentals of the
Unity editor to creating visual effects, improving game graphics, and using Unity’s
AR tools. It includes hands-on tutorials and projects, which allow readers to build a
game prototype while learning the basics of Unity.

Features

 Covers Unity’s AR tools for 3D apps and games


 Hands-on tutorials and projects on C# and visual scripting
 Learn to create both mobile and console games

9. Game Development With Unity for .NET Developers

Check Price

Key Information
Author: Jiadong Chen Publisher: Packt Publishing

Pages: 584 Edition: 1st

Publish Date: May 2022 Level: Advanced

Rating: 4.8/5 Formats: Paperback and kindle

Why we chose this book

An intermediate-level guide to using Unity's built-in modules to create impressive


games. It’s designed for developers who want to learn game development with Unity
and have some prior experience with the engine.

The book covers topics ranging from the basics of using the editor and C# coding
concepts to more advanced topics, like computer graphics math and developing a
custom render pipeline using the Scriptable Render Pipeline. It also features lessons
on integrating various services into Unity games, such as Unity Ads, Unity Analytics,
and Unity IAP.

Features

 Contains solutions to common problems faced by .NET developers


 Covers advanced Unity coding techniques
 Introduces the integration of Microsoft Game Dev, Azure Cloud, and PlayFab

10. Unity Certified Programmer: Exam Guide

Check Price

Key Information

Author: Philip Walker Publisher: Packt Publishing

Pages: 762 Edition: 1st

Publish Date: June 2020 Level: Advanced


Rating: 4.6/5 Formats: Paperback and kindle

Why we chose this book

This is designed to prepare readers for the Unity Certified Programmer exam by
providing a comprehensive guide to game scripting. It's an ideal resource for aspiring
game developers who want to obtain the Unity certification and demonstrate their
expertise to potential employers.

The guide covers the basics of C# programming and Unity, as well as more
advanced topics such as writing maintainable Unity applications, animation, and
debugging. It includes a full Unity programmer mock exam to help readers prepare
for the official certification exam.

Features

 Contains mock tests, exam tips, and self-assessment questions to help


readers pass the Unity certification
 Covers the essentials of game scripting with Unity and C#

Conclusion
If you're looking to start your game development journey, a great Unity book can be
a valuable resource for learning the fundamentals and gaining hands-on experience.
From our handpicked list of the top Unity books to our tips on choosing the right book
for you, we hope this article has provided you with valuable insights and resources.

Remember, the key to success in game development is practice and perseverance,


so don't be discouraged if you encounter obstacles along the way. With the right
Unity book and a passion for game development, you can bring your ideas to life and
create your own amazing games.

#unity #gamedevelopment #gamedev #book #csharp

3.15 GEEK

Iara Simões

8 months ago

Open options
10 Best Dart Books for Beginners and
Experienced Developers
Looking for the best Dart books to learn or improve your skills? Check out this list of
the top 10 Dart books for beginners and experienced developers, covering a wide
range of topics from the basics to advanced concepts.

Learn Dart from scratch or brush up on your skills with these top-rated Dart books.
Whether you're a beginner or an experienced developer, you'll find something to help
you on your journey to mastering Dart.

📒 25 Best Flutter Books for Beginners and Experienced Developers

1. Dart Apprentice
Dart Apprentice is one of the best Dart books this year.
↘️Ideal for: programming newbies, experienced developers
↘️Topics covered: Dart fundamentals, building applications

Dart Apprentice is for both new and experienced developers looking to learn Dart
programming. You’ll start by learning the basics of Dart such as:

 expressions, variables and constants


 types and operations
 control flow, functions and classes

And much, much more.

Dart Apprentice is the book you want to learn Dart.

I repeat: Dart Apprentice is the book you want to learn Dart.

It’s got 5-star reviews across the board, and it’s one of the most modern resources
you’ll find on Dart programming.

Don’t waste your time on outdated or weak material. Stick with the best and stay
ahead of the pack. 🐺

PICK UP YOUR COPY OF DART APPRENTICE

📙 20 Best Python Books for Beginners and Experienced Coders


2. Dart: Up and Running
Dart: Up and Running is one of the best Dart books with the most
bang for your buck.
↘️Ideal for: experienced developers, Dart newbies
↘️Topics covered: building web apps, Dart APIs, language features

Note: Dart: Up & Running is an older book that covers Dart 1.0. But it is still one
of the best Dart introductions out there.

So if you want to learn the fundamentals of Dart for a good price, this book is the
way to go.

With this hands-on guide, you’ll learn about Dart libraries and tools while building
simple scripts and complex applications. You’ll also look at:

 language features
 Dart APIs
 debugging web and command line apps

And beyond.

GRAB YOUR COPY OF DART: UP & RUNNING

📘 15+ Best JavaScript Books for Beginners and Experienced Coders

3. Dart in Action
Dart in Action is one of the best Dart books for intermediate Dart developers.
↘️Ideal for: experienced HTML developers and intermediate Dart developers
↘️Topics covered: Dart fundamentals
Dart in Action starts with a quick overview of the Dart programming language. Then
you’ll learn how to use Dart in browser-based, desktop and mobile applications.

With hands-on exercises, code samples and diagrams you’ll also discover how to
create single web applications.

➡️Dart in Action is for intermediate developers who want to dive deep into Dart
concepts and start building apps right away.

Dart ecosystem diagram in Dart in Action

PICK UP DART IN ACTION

📙 10 Best SQL Books for Beginners and Advanced

4. Dart Essentials
Dart Essentials is one of the best Dart books for experienced
JavaScript developers.
↘️Ideal for: JavaScript programmers
↘️Topics covered: Dart, JavaScript

With Dart Essentials, you’ll learn how to develop sophisticated applications using
Dart 1.9. In this tutorial-based guide, you’ll explore:

 Dart syntax and libraries


 using JavaScript libraries in Dart
 using HTML5 features in Dart
 developing web apps using AngularDart
 testing apps with unit tests

And much more.

➡️Dart Essentials teaches experienced JavaScript developers how to build


web and CLI applications.

GRAB YOUR COPY OF DART ESSENTIALS

📕 Top 15 Data Structures and Algorithms Books for Every Developer

5. Mastering Dart
Mastering Dart is one of the best Dart books for experienced Dart
developers.
↘️Ideal for: experienced Dart developers
↘️Topics covered: Dart, HTML5 features

Mastering Dart will take your existing Dart programming expertise to the next level
while you:

 discover asynchronous programming


 use collections to store and manipulate objects
 build web applications using Dart and JavaScript
 use HTML5 features to deliver cross-platform content

And beyond.

➡️Mastering Dart is for experienced Dart developers who want to build high-
performance applications.

PICK UP MASTERING DART

6. Learning Dart
Learning Dart is one of the best Dart books for developers
experienced with HTML.
↘️Ideal for: Dart newbies
↘️Topics covered: Dart fundamentals, HTML5 forms

Learning Dart shows you how to develop modern web applications using Dart and
HTML5. You’ll dive deep into Dart concepts such as:

 functions, classes and generics


 using browsers to process and store data
 developing games
 using audio and video in the browser
 building HTML5 forms
You’ll also discover how to store the data from your application
in MySQL and MongoDB using Dart.

➡️Learning Dart teaches Dart newbies how to develop high-performance


applications using Dart 1.12. Some experience with HTML will be helpful.
Dart web model in Learning Dart

GRAB YOUR COPY OF LEARNING DART

7. Dart for Absolute Beginners


↘️Ideal for: programming newbies
↘️Topics covered: Dart fundamentals

Dart for Absolute Beginners is for readers with no prior programming experience.
With digestible chapters, you’ll learn Dart fundamentals alongside technologies
behind the web.

➡️Dart for Absolute Beginners is an older book so some of the material is


outdated. However, you’ll still learn plenty of Dart fundamentals.

PICK UP DART FOR ABSOLUTE BEGINNERS


8. The Dart Programming Language
↘️Ideal for: experienced programmers, Dart newbies
↘️Topics covered: Dart fundamentals

The Dart Programming Language shares valuable insights into the fundamentals
of Dart. You’ll look at how Dart:

 programs are organized into libraries


 functions are structured
 handles expressions and statements
 features support concurrency and distribution

And more.

➡️The Dart Programming Language is written by Gilad Bracha, a software


engineer at Google who uses Dart.

GRAB YOUR COPY OF THE DART PROGRAMMING LANGUAGE

9. Quick Start Guide to Dart Programming


↘️Ideal for: Dart and programming newbies
↘️Topics covered: Dart basics

Quick Start Guide to Dart Programming you’ll learn the basics of Dart. First you’ll
become familiar with components of Dart such as:

 types
 variables
 arrays
 collections

Then you’ll explore control, looping, functions and objects. Finally, you’ll discover
Dart packages and libraries used to create a backend server.
➡️With the Quick Start Guide to Dart Programming, you’ll learn how to create
high-performance apps for both web and mobile.

Dart language features in Quick Start Guide to Dart Programming

PICK UP QUICK START GUIDE TO DART PROGRAMMING

10. Dart for Hipsters


Dart for Hipsters is one of the best Dart books for covering Dart 1.1.

↘️Ideal for: Dart newbies


↘️Topics covered: Dart fundamentals

Dart for Hipsters is a project-based, hip book containing real-world examples and
exercises. While working on projects, you’ll learn how to maintain Dart and
JavaScript side-by-side. Then you’ll:

 write an Ajax-powered application


 use Dart with HTML5
 build easily maintained libraries

And more.
➡️Dart for Hipsters is another older Dart book covering Dart 1.1, so some
concepts will be outdated. But you will still find valuable insights into Dart
programming.

PICK UP YOUR COPY OF DART FOR HIPSTERS

#dart #flutter #mobileapp #book

1 Likes3.00 GEEK

Iara Simões

8 months ago

Open options

Python Functions Explained with Code


Examples
Learn Python functions, one of the most important concepts in Python, with this
comprehensive tutorial. With code examples for every concept, you'll be mastering
Python functions in no time! In this tutorial, we shall learn about user-defined
functions in Python.
In any programming language, functions facilitate code reusability. In simple terms,
when you want to do something repeatedly, you can define that something as a
function and call that function whenever you need to.

When you started coding in Python, you'd have used the built-in print() function in
your Hello World! program 😀 and the input() function to read in input from the
user.

So long as you know how to use these functions, you don't have to worry about how
they've been implemented.

In programming, this is called abstraction. It lets you use functions by calling the
function with required arguments, without having to worry about how they actually
work.

There's a whole wealth of built-in functions in Python. In this post, we shall see how
we can define and use our own functions. Let's get started!

📙 20 Best Python Books for Beginners and Experienced Coders


Python Function Syntax

The following snippet shows the general syntax to define a function in Python:

def function_name(parameters):

# What the function does goes here

return result

 You need to use the def keyword, give your function a name, followed by a
pair of parentheses, and end the line with a colon (:).
 If your function takes arguments, the names of the arguments (parameters)
are mentioned inside the opening and closing parentheses.
 Please note that in function definition, the arguments that your function
consumes are referred to as parameters.
 When you call the function with specific values for these parameters, they're
called arguments or actual parameters. This is because the arguments in
the function call are the values used for the function's parameters.
 Then, you begin an indented block. This is the body of the function that
describes what your function does.
 There's a return statement that returns the result of the operation on the
arguments. The return statement returns control to the point where the
function was originally called.
Note that the arguments and the return statement are optional. This means that
you could have a function that takes in no arguments, and returns nothing. 😀

Let's now try to understand the above statements using simple examples.

How to Create a Simple Function in Python

Let's now create a simple function in Python that greets the user, as shown below:

def my_func():

print("Hello! Hope you're doing well")

As you can see, the function my_func():

 takes no arguments,
 returns nothing, and
 prints out "Hello! Hope you're doing well" whenever it's called.
Note that the above function definition is inert until the function is triggered or called.
Let's go ahead and call the function my_func() and check the output.

my_func()

# Output

Hello! Hope you're doing well

How to Create a Function with Arguments in Python

Now, we shall modify the function my_func() to include the name and place of the
user.

def my_func(name,place):

print(f"Hello {name}! Are you from {place}?")

We can now call my_func() by passing in two strings for the name and place of the
user, as shown below.

my_func("Jane","Paris")

# Output

Hello Jane! Are you from Paris?

What happens if you specify the place first and then the name? Let's find out.

my_func("Hawaii","Robert")

# Output

Hello Hawaii! Are you from Robert?

We get Hello Hawaii! Are you from Robert? – and this doesn't make sense. 🙂
What's causing this problem?
The arguments in the function call are positional arguments. This means that the first
argument in the function call is used as the value of the first parameter ( name) and
the second argument in the function call is used as the value of the second
parameter ( place )

See the code snippet below. Instead of specifying only the arguments, we've
mentioned the parameters and the values they take.

my_func(place="Hawaii",name="Robert")

# Output

Hello Robert! Are you from Hawaii?

These are called keyword arguments. The order of arguments in the function call
does not matter so long as the names of the parameters are correct.

📘 15+ Best JavaScript Books for Beginners and Experienced Coders

How to Create a Function with Default Arguments in Python

What if we had certain parameters that take a specific value most of the time during
the function calls?

Can we not do better than calling the function with the same value for a particular
parameter?

Yes we can do better, and that's what default arguments are for! 😀

Let's create a function total_calc() that helps us calculate and print out the total
amount to be paid at a restaurant. Given a bill_amount and the percentage of
the bill_amount you choose to pay as tip (tip_perc ), this function calculates the
total amount that you should pay.

Note how the function definition includes the default value of the
parameter tip_perc to be used when the user doesn't specify a tip percentage.

Run the code snippet below.👇🏽 You now have your function ready!

def total_calc(bill_amount,tip_perc=10):

total = bill_amount*(1 + 0.01*tip_perc)

total = round(total,2)
print(f"Please pay ${total}")

Let's now call the function in a few different ways. The code snippet below shows the
following:

 When you call the function total_calc with only the bill_amount, by default
the tip percentage of 10 is used.
 When you explicitly specify the percentage tip, the tip percentage mentioned
in the function call is used.

# specify only bill_amount

# default value of tip percentage is used

total_calc(150)

# Output

Please pay $165.0

# specify both bill_amount and a custom tip percentage

# the tip percentage specified in the function call is used

total_calc(200,15)

# Output

Please pay $230.0

total_calc(167,7.5)

# Output
Please pay $179.53

How to Create a Function that Returns a Value in Python

So far, we've only created functions that may or may not take arguments and do not
return anything. Now, let's create a simple function that returns the volume of a
cuboid given the length, the width, and the height.

def volume_of_cuboid(length,breadth,height):

return length*breadth*height

Recall that the return keyword returns control to the point where the function was
called. The function call is replaced with the return value from the function.

Let's call the function volume_of_cuboid() with the necessary dimension


arguments, as shown in the code snippet below. Note how we use the
variable volume to capture the value returned from the function.

volume = volume_of_cuboid(5.5,20,6)

print(f"Volume of the cuboid is {volume} cubic units")

# Output

Volume of the cuboid is 660.0 cubic units

How to Create a Function that Returns Multiple Values in Python

In our earlier example, the function volume_of_cuboid() returned only one value,
namely, the volume of a cuboid given its dimensions. Let's see how we can return
multiple values from a function.

 To return multiple values from a function, just specify the values to be


returned, separated by a comma.
 By default, the function returns the values as a tuple. If there are N return
values, we get an N-tuple.
Let's create a simple function cube() that returns the volume and total surface area
of a cube, given the length of its side.

def cube(side):

volume = side **3

surface_area = 6 * (side**2)

return volume, surface_area

To verify that a tuple is returned, let's collect it in a variable returned_values, as


shown below:

returned_values = cube(8)

print(returned_values)

# Output

(512, 384)

Now, we shall unpack the tuple and store the values in two different variables.

volume, area = cube(6.5)

print(f"Volume of the cube is {volume} cubic units and the total surface area is {area}
sq. units")

# Outputs

Volume of the cube is 274.625 cubic units and the total surface area is 253.5 sq. units

How to Create a Function that Takes a Variable Number of Arguments in


Python

Let's start by asking a few questions:

 What if we do not know the exact number of arguments beforehand?


 Can we create functions that work with a variable number of arguments?
The answer is yes! And we'll create such a function right away.

Let's create a simple function my_var_sum() that returns the sum of all numbers
passed in as the argument. However, the number of arguments could be potentially
different each time we call the function.

Notice how the function definition now has *args instead of just the name of the
parameter. In the body of the function, we loop through args until we've used all the
arguments. The function my_var_sum returns the sum of all numbers passed in as
arguments.

def my_var_sum(*args):

sum = 0

for arg in args:

sum += arg

return sum

Let's now call the function my_var_sum() with a different number of arguments each
time and quickly check if the returned answers are correct! 🙂

# Example 1 with 4 numbers

sum = my_var_sum(99,10,54,23)

print(f"The numbers that you have add up to {sum}")

# Output

The numbers that you have add up to 186

# Example 2 with 3 numbers

sum = my_var_sum(9,87,45)

print(f"The numbers that you have add up to {sum}")

# Output
The numbers that you have add up to 141

# Example 3 with 6 numbers

sum = my_var_sum(5,21,36,79,45,65)

print(f"The numbers that you have add up to {sum}")

# Output

The numbers that you have add up to 251

⌛ A Quick Recap

Let's quickly summarize what we've covered. In this tutorial, we've learned:

 how to define functions,


 how to pass in arguments to a function,
 how to create functions with default and variable number of arguments, and
 how to create a function with return value(s).

Hope you all enjoyed reading this article. Thank you for reading. As always, until
next time! 😀

Source: https://www.freecodecamp.org

#python

4.55 GEEK

Iara Simões

8 months ago

Open options
Top 10 Angular Books for Beginners to
Advanced Developers
Master Angular with these top 10 books for beginners to advanced developers!
Learn Angular from the ground up with these top-rated books for beginners and
advanced developers. Master the Angular framework and build powerful web
applications with these essential resources.

📙 Best JavaScript Books: https://bit.ly/3RLdPUJ

From foundational concepts to advanced techniques, these angular books offer a


range of insights, tips, and strategies that will help you take your Angular skills to the
next level. Whether you need to learn how to build dynamic web applications using
Angular or the best practices for structuring and testing your code, our list has got
you covered. Let’s dive in and discover the best Angular books you should take
advantage of adding to your reading list!

Key Highlights

 Offers insights and information about the contents of each book, including its
strengths and weaknesses, to help make informed choices.
 Compares and contrasts different books and highlights their unique features
to quickly choose the one that best suits the needs and learning style.
 Assist beginners, intermediate and advanced developers in their learning
journey by providing reliable resources to enhance their knowledge and skills
in Angular.

10 Most Recommended Angular Books

Sr.no Publish Rating


Book Author Date

Amazon: 4.4

Goodreads:
3.93
1 Angular Development with TypeScript Yakov Fain and Anton Moiseev 2018

2 Angular in Action Jeremy Wilken 2018 Amazon: 3.9


Goodreads: 4

Amazon: 4

Goodreads:
ng-book: The Complete Guide to Nathan Murray, Felipe Coury, 3.75
3 Angular Ari Lerner, and Carlos Taborda 2019

Amazon: 3.1

Goodreads:
Learning Angular: A Hands-On Guide 3.60
4 to Angular 2 and Angular 4 Brad Dayley 2017

Amazon: 2.1

Goodreads:
4.25
5 Mastering Angular 2 Components Gion Kunz 2016

Amazon: 4.1

Goodreads:
4.20
6 Angular 2 Cookbook Matt Frisbie 2017

Amazon: 4.1

Goodreads:
AngularJS: Up and Running: Enhanced 3.96
7 Productivity with Structured Web Apps Shyam Seshadri and Brad Green 2014

8 Angular 2 By Example Chandermani Arora 2016 Amazon: 3.6

Goodreads:
4.20

Amazon: 3.2

Goodreads:
3.91
9 AngularJS: Novice to Ninja Sandeep Panda 2014

Amazon: 2.2

Goodreads:
4.10
10 Angular Test-Driven Development Md. Ziaul Haq 2017

Let us look at the Angular Books and see which one best suits your needs:-

Book #1: Angular Development with TypeScript

Author: Yakov Fain and Anton Moiseev

Get this book here

Review

“Angular Development with TypeScript” is an essential guide for developers who


want to learn Angular and TypeScript. The book offers a detailed overview of the
Angular framework, including its architecture, components, directives, and services.
The authors also explain using TypeScript to build more robust and scalable
applications. With a comprehensive approach, this book is perfect for developers of
all levels interested in learning Angular and TypeScript.

Key Takeaways

 Guides using the Angular framework with TypeScript to write more scalable
and maintainable code.
 Offers practical advice on best practices for working with Angular, including
components, forms, and authentication.
 It covers advanced topics such as testing and deploying Angular applications.
 Offers helpful tips and tricks for solving common Angular development
challenges.
Book #2: Angular in Action

Author: Jeremy Wilken

Get this book here

Review

“Angular in Action” is an excellent guide for developers who want to learn Angular.
The book covers the basics of Angular and dives into more advanced topics, such as
building custom directives and services. The author provides a comprehensive
overview of the Angular framework, including its features and functionalities. This
book is an outstanding resource for developers looking to create top-notch Angular
applications. It provides clear explanations and practical examples to help them
achieve their goals.

Key Takeaways

 Provides a practical guide to building responsive, mobile-first web applications


with Angular.
 Offers guidance on how to use Angular components, templates, data binding,
and routing to build scalable and maintainable applications.
 It covers topics such as debugging, testing Angular applications, and
integrating with third-party libraries.
 Provides real-world examples of how to build applications with Angular.
Book #3: ng-book: The Complete Guide to Angular

Author: Nathan Murray, Felipe Coury, Ari Lerner, and Carlos Taborda

Get this book here

Review

“ng-book” is an excellent resource for developers who want to learn Angular. The
book covers all aspects of Angular, from basic concepts to advanced topics. The
authors provide clear explanations and practical examples to help readers
understand the framework. With a comprehensive approach, this book is an ideal
resource for developers who want to master Angular.

Key Takeaways

 Offers comprehensive guidance on building web applications with Angular,


including a detailed introduction to the framework.
 Covers all the major features of Angular, including components, services,
directives, and pipes.
 Provides practical advice on how to build scalable and maintainable
applications with Angular.
 Includes real-world examples and exercises to help reinforce learning.
Book #4: Learning Angular: A Hands-On Guide to Angular 2 and Angular 4

Author: Brad Dayley, Brendan Dayley, Caleb Dayley

Get this book here

Review

“Learning Angular” is a practical guide for developers who want to learn Angular. The
book covers the basics of Angular, including its architecture, components, and
services. The author also provides hands-on examples and exercises to help
readers understand the framework. With a clear and concise approach, this book is
perfect for developers who want to start with Angular.

Key Takeaways

 Covers the fundamentals of Angular, including modules, components,


services, directives, forms, and more.
 Provides practical examples, step-by-step instructions, and real-world
scenarios to help readers understand how to use Angular effectively.
 Gives a solid understanding of Angular and the ability to build dynamic and
responsive web applications.
Book #5: Mastering Angular 2 Components

Author: Gion Kunz

Get this book here

Review

If you’re a developer looking to create custom components using Angular, then


“Mastering Angular 2 Components” would be an excellent guide to help you achieve
that goal. The book covers all aspects of Angular components, including how to
create them, how to use them, and how to test them. With practical examples and
clear explanations, this book is perfect for developers who want to take their Angular
skills to the next level.

Key Takeaways
 It focuses specifically on building and using components in Angular.
 Offers practical guidance on how to create reusable and maintainable
components with Angular.
 Covers topics such as component architecture, data binding, templates, and
lifecycle hooks.
Book #6: Angular 2 Cookbook

Author: Matt Frisbie

Get this book here

Review

“Angular 2 Cookbook” is an essential resource for developers aspiring to learn how


to build real-world applications in Angular. The book provides practical recipes for
creating various types of applications, including CRUD apps, authentication systems,
and chat apps. With a clear and concise approach, this book is perfect for
developers wanting to start with Angular quickly.

Key Takeaways

 Provides a collection of practical recipes for solving everyday challenges


when building web applications with Angular.
 Covers topics such as component architecture, templates, data binding,
forms, and observables.
 Offers guidance on how to test and debug Angular applications.
 Provides practical advice on best practices for building scalable and
maintainable applications with Angular.
Book #7: AngularJS: Up and Running: Enhanced Productivity with Structured Web
Apps

Author: Shyam Seshadri and Brad Green

Get this book here

Review

“AngularJS: Up and Running” is a comprehensive guide for developers who want to


learn AngularJS. The book covers all aspects of AngularJS, including its features,
components, and services. The authors provide practical examples and clear
explanations to help readers understand the framework. With a comprehensive
approach, this book is perfect for developers who want to master AngularJS.
Key Takeaways

 Provides an introduction to the AngularJS framework and how to use it to


build structured and maintainable web applications.
 Covers topics such as controllers, templates, data binding, and directives.
 Offers practical advice on how to use AngularJS to create more scalable and
maintainable applications.
Book #8: Angular 2 By Example

Author: Chandermani Arora, Kevin Hennessy

Get this book here

Review

If you’re a developer looking to build practical applications using Angular, “Angular 2


By Example” is an outstanding guide. The book provides practical examples of
creating various applications, including a weather app, a task management app, and
a music app. With a clear and concise approach, this book is perfect for developers
who want to learn Angular by doing.

Key Takeaways

 Offers a practical guide to building web applications with Angular.


 Covers the basics of Angular, including components, templates, and data
binding.
 Progresses to more advanced topics like routing, forms, and observables.
Book #9: AngularJS: Novice to Ninja

Author: Sandeep Panda

Get this book here

Review

It is an extensive guide for those who want to learn AngularJS from scratch. This
book covers all the essential topics of AngularJS in a step-by-step manner, making it
easy for beginners to understand the concepts. The book starts with the basics of
AngularJS and gradually progresses toward more advanced topics. The author has
done a fantastic job explaining complex ideas in simple, easy-to-understand
language. Also, the author has provided some tips and tricks to help readers become
more proficient in AngularJS.
Key Takeaways

 Serves as a guide to learning AngularJS, a powerful and popular front-end


development framework.
 Explains in a step-by-step approach, starting with the basics of AngularJS and
gradually building up to more advanced topics.
 Shows how to create a complete web app from scratch, including creating
controllers, services, directives, and filters.
 It covers essential topics such as data binding, routing, animations, and
testing, making it a comprehensive resource for anyone looking to learn
AngularJS.
Book #10: Angular Test-Driven Development

Author: Md. Ziaul Haq

Get this book here

Review

Angular Test-Driven Development by Md. Ziaul Haq is an excellent book for anyone
who wants to learn test-driven development with Angular. The author has done a
fantastic job explaining test-driven development concepts in simple, easy-to-
understand language. The book contains numerous practical examples and code
snippets that facilitate readers’ comprehension of the concepts. The book covers all
the essential topics of Angular and test-driven development, making it ideal for
beginners and advanced developers.

Key Takeaways

 Offers a practical guide to using test-driven development with Angular.


 Covers topics like Jasmine, Karma, Protractor, and testing Angular
components, services, and directives.
 Includes practical examples to reinforce learning.
 It offers the benefits of test-driven development and provides practical
examples of implementing it in an Angular project.

#angular

1 Likes4.80 GEEK
Iara Simões

8 months ago

Open options

11+ Best JavaScript Project Ideas for


Beginners (With Source Code!)
Learn JavaScript by building 11+ fun and engaging projects, with source code
included for all projects. Master the basics of JavaScript and build your coding skills
with these beginner-friendly projects.

📙 Best JavaScript Books: https://bit.ly/3RLdPUJ


1. JavaScript Calculator

The calculator is one of the easy JavaScript projects on our list. We will use simple
HTML and CSS, and create all functional components using basic JavaScript
functions. We’ll continue using HTML to display buttons and improve the
presentation with CSS. Finally, we’ll need to ensure buttons perform the right
functions using JavaScript.

The main function is eval(), a global JS function that solves JS code. The display()
function will display the selected number on the calculator screen. Note that the
program will work only for mouse events. Here is the complete code, split into HTML,
CSS and JS sections:

HTML:

<div class="calculator">

<input type="text" class="calculator-screen" value="" disabled />

<div class="calculator-keys">
<button type="button" class="operator" value="+">+</button>

<button type="button" class="operator" value="-">-</button>

<button type="button" class="operator" value="*">&times;</button>

<button type="button" class="operator" value="/">&divide;</button>

<button type="button" value="7">7</button>

<button type="button" value="8">8</button>

<button type="button" value="9">9</button>

<button type="button" value="4">4</button>

<button type="button" value="5">5</button>

<button type="button" value="6">6</button>

<button type="button" value="1">1</button>

<button type="button" value="2">2</button>

<button type="button" value="3">3</button>

<button type="button" value="0">0</button>


<button type="button" class="decimal" value=".">.</button>

<button type="button" class="all-clear" value="all-clear">AC</button>

<button type="button" class="equal-sign operator" value="=">=</button>

</div>

</div>

CSS:

html {

font-size: 62.5%;

box-sizing: border-box;

*, *::before, *::after {

margin: 0;

padding: 0;

box-sizing: inherit;

.calculator {

border: 1px solid #ccc;


border-radius: 5px;

position: absolute;

top: 50%;

left: 50%;

transform: translate(-50%, -50%);

width: 400px;

.calculator-screen {

width: 100%;

font-size: 5rem;

height: 80px;

border: none;

background-color: #252525;

color: #fff;

text-align: right;

padding-right: 20px;

padding-left: 10px;

button {
height: 60px;

background-color: #fff;

border-radius: 3px;

border: 1px solid #c4c4c4;

background-color: transparent;

font-size: 2rem;

color: #333;

background-image: linear-gradient(to bottom,transparent,transparent


50%,rgba(0,0,0,.04));

box-shadow: inset 0 0 0 1px rgba(255,255,255,.05), inset 0 1px 0 0


rgba(255,255,255,.45), inset 0 -1px 0 0 rgba(255,255,255,.15), 0 1px 0 0
rgba(255,255,255,.15);

text-shadow: 0 1px rgba(255,255,255,.4);

button:hover {

background-color: #eaeaea;

.operator {

color: #337cac;

}
.all-clear {

background-color: #f0595f;

border-color: #b0353a;

color: #fff;

.all-clear:hover {

background-color: #f17377;

.equal-sign {

background-color: #2e86c0;

border-color: #337cac;

color: #fff;

height: 100%;

grid-area: 2 / 4 / 6 / 5;

.equal-sign:hover {

background-color: #4e9ed4;

}
.calculator-keys {

display: grid;

grid-template-columns: repeat(4, 1fr);

grid-gap: 20px;

padding: 20px;

JavaScript:

const calculator = {

displayValue: '0',

firstOperand: null,

waitingForSecondOperand: false,

operator: null,

};

function inputDigit(digit) {

const { displayValue, waitingForSecondOperand } = calculator;

if (waitingForSecondOperand === true) {

calculator.displayValue = digit;

calculator.waitingForSecondOperand = false;
} else {

calculator.displayValue = displayValue === '0' ? digit : displayValue + digit;

function inputDecimal(dot) {

if (calculator.waitingForSecondOperand === true) {

calculator.displayValue = "0."

calculator.waitingForSecondOperand = false;

return

if (!calculator.displayValue.includes(dot)) {

calculator.displayValue += dot;

function handleOperator(nextOperator) {

const { firstOperand, displayValue, operator } = calculator

const inputValue = parseFloat(displayValue);


if (operator && calculator.waitingForSecondOperand) {

calculator.operator = nextOperator;

return;

if (firstOperand == null && !isNaN(inputValue)) {

calculator.firstOperand = inputValue;

} else if (operator) {

const result = calculate(firstOperand, inputValue, operator);

calculator.displayValue = `${parseFloat(result.toFixed(7))}`;

calculator.firstOperand = result;

calculator.waitingForSecondOperand = true;

calculator.operator = nextOperator;

function calculate(firstOperand, secondOperand, operator) {

if (operator === '+') {


return firstOperand + secondOperand;

} else if (operator === '-') {

return firstOperand - secondOperand;

} else if (operator === '*') {

return firstOperand * secondOperand;

} else if (operator === '/') {

return firstOperand / secondOperand;

return secondOperand;

function resetCalculator() {

calculator.displayValue = '0';

calculator.firstOperand = null;

calculator.waitingForSecondOperand = false;

calculator.operator = null;

function updateDisplay() {

const display = document.querySelector('.calculator-screen');


display.value = calculator.displayValue;

updateDisplay();

const keys = document.querySelector('.calculator-keys');

keys.addEventListener('click', event => {

const { target } = event;

const { value } = target;

if (!target.matches('button')) {

return;

switch (value) {

case '+':

case '-':

case '*':

case '/':

case '=':

handleOperator(value);

break;
case '.':

inputDecimal(value);

break;

case 'all-clear':

resetCalculator();

break;

default:

if (Number.isInteger(parseFloat(value))) {

inputDigit(value);

updateDisplay();

});

2. Hangman Game

Hangman is a well-known game, and one of our simple JS projects. You can develop
it in a jiffy using JavaScript, HTML, and CSS. Note that the main functionality is
defined using JS. HTML is for display, and CSS does the job of beautifying the
contents.

Many methods are defined in the JS code, so it may seem a bit complicated, but you
will realize it is simple once you read the code thoroughly. You can also run the code
and see the execution line by line.

Check the code and execution here.


3. JavaScript Weather App

Weather apps are also popular JavaScript projects. Once you change the location
name in this project, the weather display changes immediately without a page
refresh. The UI is also quite sleek.

Note that most weather apps use an API that gets the weather data. We will use the
popular and most common API, OpenWeatherMap.

Check out this Youtube video that explains the weather app code and functionality in
detail. There are three files, as usual: index.html, main.js, and main.css. Although
you can put all the code in a single file (HTML), it is more convenient to maintain
separate files.

Recommended JavaScript Course

The Complete JavaScript Course 2023: From Zero to Expert!

4. JavaScript Music Events

Here, we’ll introduce you to event listeners that will act on keyboard events. For
example, an event will take place if the ‘S’ key is pressed. Each one will have a
different code and action.

Apart from event listeners, we will also learn how to add and play audio files. Note
that we have added very basic CSS, as the focus here is on JavaScript. You will
have to import your own sounds and background image for the program to work fully.

<html>

<head>

<meta charset="UTF-8">

<meta name="viewport" content="width=device-width, initial-scale=1">

<title>KeyBoard Music</title>

</head>

<body>
<div class="keys">

<div data-key="65" class="key">

<kbd>A</kbd>

</div>

<div data-key="83" class="key">

<kbd>S</kbd>

</div>

<div data-key="68" class="key">

<kbd>D</kbd>

</div>

<div data-key="70" class="key">

<kbd>F</kbd>

</div>

<div data-key="71" class="key">

<kbd>G</kbd>

</div>

<div data-key="72" class="key">

<kbd>H</kbd>

</div>

<div data-key="74" class="key">

<kbd>J</kbd>
</div>

<div data-key="75" class="key">

<kbd>K</kbd>

</div>

<div data-key="76" class="key">

<kbd>L</kbd>

</div>

</div>

<audio data-key="65" src="sounds/clap.wav"></audio>

<audio data-key="83" src="sounds/chord.wav"></audio>

<audio data-key="68" src="sounds/ride.wav"></audio>

<audio data-key="70" src="sounds/openhat.wav"></audio>

<audio data-key="71" src="sounds/tink.wav"></audio>

<audio data-key="72" src="sounds/kick.wav"></audio>

<audio data-key="74" src="sounds/swipe.wav"></audio>

<audio data-key="75" src="sounds/tom.wav"></audio>

<audio data-key="76" src="sounds/boom.wav"></audio>

</body>

<script>

function removeTransition(event) {

if (event.propertyName !== 'transform') return


event.target.classList.remove('playing')

function playSound(event) {

const audio = document.querySelector(`audio[data-key="${event.keyCode}"]`)

const key = document.querySelector(`div[data-key="${event.keyCode}"]`)

if (!audio) return

key.classList.add('playing')

audio.currentTime = 0

audio.play()

const keys = Array.from(document.querySelectorAll('.key'))

keys.forEach((key) => key.addEventListener('transitionend', removeTransition))

window.addEventListener('keydown', playSound)

</script>

<style>

html {

font-size: 12px;

background: url('drums.jpg') top center;

background-size: 80%;

.keys {
display: flex;

flex: 1;

align-items: top;

justify-content: center;

.key {

border: 0.4rem solid blue;

border-radius: 0.5rem;

margin: 1rem;

font-size: 2rem;

padding: 1rem 0.5rem;

transition: all 0.01s ease;

width: 5rem;

text-align: center;

color: black;

text-shadow: 0 0 0.5rem yellow;

</style>

</html>

5. JavaScript Form Validation


Form validation is a useful aspect and used by many websites for client-side
validation of user information, such as card and address details. For example, if
there is a mandatory input field name, the user may type a number, leave the field
blank, or type just one letter. JS can validate this information.

The project below involves simple form validation. Of course, the project will need
HTML elements as well. We have not carried out any extensive styling, only
including basic elements in the HTML itself.

Here is the complete code of a simple form with basic validations:

<html>

<head>

<title>Form Validation</title>

<script type = "text/javascript">

function validate() {

var text;

if( document.myForm.name.value == "" ) {

text = "Name cannot be empty";

document.getElementById("demo").innerHTML = text;

document.myForm.name.focus() ;

return false;

if( document.myForm.email.value == "" ) {

text = "E-mail cannot be empty";

document.getElementById("demo").innerHTML = text;
document.myForm.email.focus() ;

return false;

var emailID = document.myForm.email.value;

atposn = emailID.indexOf("@");

dotposn = emailID.lastIndexOf(".");

if (atposn < 1 || ( dotposn - atposn < 2 )) {

text = "Please enter valid email ID";

document.getElementById("demo").innerHTML = text;

document.myForm.email.focus() ;

return false;

if( document.myForm.phone.value == "" || isNaN( document.myForm.phone.value


) ||

document.myForm.phone.value.length != 10 ) {

text = "Please enter a valid 10-digit phone number";

document.getElementById("demo").innerHTML = text;

document.myForm.phone.focus() ;

return false;

if( document.myForm.subject.value == "0" ) {


text = "Please provide your area of expertise";

document.getElementById("demo").innerHTML = text;

return false;

return( true );

</script>

</head>

<body>

<form action = "" name = "myForm" onsubmit = "return(validate());">

<h1 align="center">USER REGISTRATION</H1>

<table align="center" cellspacing = "3" cellpadding = "3" border = "3">

<tr>

<td align = "right">Name</td>

<td><input type = "text" name = "name" /></td>

</tr>

<tr>

<td align = "right">E-mail</td>

<td><input type = "text" name = "email" /></td>

</tr>

<tr>
<td align = "right">Phone Number</td>

<td><input type = "text" name = "phone" /></td>

</tr>

<tr>

<td align = "right">Subject</td>

<td>

<select name = "subject">

<option value = "0" selected>Select</option>

<option value = "1">HTML</option>

<option value = "2">JavaScript</option>

<option value = "3">CSS</option>

<option value = "4">JSP</option>

</select>

</td>

</tr>

</table>

<p id="demo" style="color:red; text-align:center"></p>

<div style="text-align:center"><input type = "submit" value = "Submit" /></div>

</form>

</body>

</html>
6. JavaScript Photo Details Display

Here, we will display some images on a web page. Once the user hovers over the
images, more details will appear. You can download images from anywhere or use
the ones you already have.

Again, we have used basic HTML and CSS along with JS. The latter carries out most
of the work. You will learn how mouse hover (over and out) events work through this
project.

<!DOCTYPE html>

<html>

<head>

<title>My Sun Sign Infos</title>

</head>

<script>

function display(element){

document.getElementById('image').innerHTML = element.alt;

function revert(){

document.getElementById('image').innerHTML = "Hover over a sunsign image to


display details.";

</script>

<style>

#image{
width: 650px;

height: 70px;

border:5px solid pink;

background-color: black;

background-repeat: no-repeat;

color:white;

background-size: 100%;

font-family: Didot;

font-size: 150%;

line-height: 60px;

text-align: center;

img{

width: 200px;

height: 200px;

border-radius: 50%;

</style>

<body>

<div>

<p id = "image">Hover over a sunsign image to display details.<p>


<img alt = "Sagittarius are beautiful, loyal and passionate." src = "saggi.jpg"
onmouseover = "display(this)" onmouseout = "revert()">

<img alt = "Pisces are dreamy, helpful and love everyone!" src = "pisces.jpg"
onmouseover = "display(this)" onmouseout = "revert()">

<img alt = "Leo are strong and fearless. They aim for and achieve a lot!" src =
"leo.jpg" onmouseover = "display(this)" onmouseout = "revert()">

<img alt = "Scorpions are friends for life. They are trustworthy and truthful." src =
"scorpio.jpg" onmouseover = "display(this)" onmouseout = "revert()">

</div>

</body>

</html>

To make this project more complex, try this slideshow project from W3Schools. You
can change the onClick events to onmousehover and onmouseout events, in which
case, the images will change once the user hovers over the images.

7. Build an Interactive Landing Page

This project involves building a dynamic landing page that stores your name and text
written in local storage, and shows you an appropriate image and greeting message
based on the day's time. This YouTube video will help you learn about this project’s
JS components.

Intermediate JavaScript Projects


8. Single Page Application

Here, the page won’t reload upon navigating the side links, but the content will
change. Again, we will use eventListeners to change the view from one link to
another. Check out the code and explanation on this YouTube video.

9. JavaScript Browser Code Editor


While you already have an ample choice of JS code editors, it’s always nice to be
able to create your own. JS allows you to create an in-browser code editor, which is
what this project is about. It makes use of some useful JS methods - and even
features syntax highlighting!

The source code for this project is available here.

10. Real-time Chat Application

Chat applications are comparatively simple to make and you can create one yourself
using JavaScript. This project makes use of both React and Node.js, so it might be a
little intimidating. However, it’s a good way to get your hands dirty and learn how to
work with these invaluable tools.

You can view the source code on GitHub.

11. 2D Platforming Game

Games are an excellent and fun way to learn JS. It’s why you’ll see so many projects
revolving around games. This project teaches you how to create a 2D platformer
game — all using JS, HTML, and CSS.

12. Photo-sharing App

Everyone knows Instagram. It has a lot of features, but fundamentally, it’s a photo-
sharing application. You can create a similar but smaller-scale version of it using JS.
This is a hefty project and you’ll find yourself using React, Node.js, and Postgres,
among other things.

Take a look at the source code here.

13. File Sharing App


Learning how to share files is another useful skill to have. You’ll be using the Virgil
Crypto Library in JavaScript to create this app. It’s secure, and you’ll be able to
download, decrypt, and view encrypted media files.

Take a look at the source code here.

#javascript #js

2.80 GEEK

Iara Simões

8 months ago

Open options

BASH CheatSheet: Learn the Most


Common BASH Commands
Master BASH with this comprehensive cheatsheet for beginners! Learn the most
common BASH commands. This comprehensive BASH cheatsheet for beginners is
the perfect resource for anyone who wants to learn the most common BASH
commands quickly and easily. Covering a wide range of topics, from basic file
management to advanced scripting, this cheatsheet has everything you need to start
using BASH effectively.

Whether you're a complete beginner or you have some basic BASH knowledge, this
cheatsheet is a must-have for anyone who wants to learn the most common BASH
commands.

Commands

tr command

Remove whitespace:
$ echo 'foo - bar' | tr -d '[:space:]'

foo-bar

Convert to uppercase:
$ echo 'HeLLo' | tr '[:lower:]' '[:upper:]'
HELLO

One Liners

Block Bad IPs

Use iptables to block all bad ip addresses:


$ cat /var/log/maillog | grep 'lost connection after AUTH from unknown' | tail -n 5

May 10 11:19:49 srv4 postfix/smtpd[1486]: lost connection after AUTH from


unknown[185.36.81.145]

May 10 11:21:41 srv4 postfix/smtpd[1762]: lost connection after AUTH from


unknown[185.36.81.164]

May 10 11:21:56 srv4 postfix/smtpd[1762]: lost connection after AUTH from


unknown[175.139.231.129]

May 10 11:23:51 srv4 postfix/smtpd[1838]: lost connection after AUTH from


unknown[185.211.245.170]

May 10 11:24:02 srv4 postfix/smtpd[1838]: lost connection after AUTH from


unknown[185.211.245.170]

Get the data to show only IPs:


cat /var/log/maillog | grep 'lost connection after AUTH from unknown' | cut -d'[' -f3 | cut -
d ']' -f1 | tail -n5

185.36.81.164

175.139.231.129

185.211.245.170

185.211.245.170

185.36.81.173

Get the uniqe IP addresses:


$ cat /var/log/maillog | grep 'lost connection after AUTH from unknown' | cut -d'[' -f3 | cut
-d ']' -f1 | sort | uniq
103.194.70.16

112.196.77.202

113.172.210.19

113.173.182.119

139.59.224.234

Redirect the output to iptables:


$ for ip in $(cat /var/log/maillog | grep 'lost connection after AUTH from unknown' | cut -
d'[' -f3 | cut -d ']' -f1 | sort | uniq); do iptables -I INPUT -s ${ip} -p tcp --dport 25 -j DROP;
done

If Statements

Check if args are passed

if [[ $# -eq 0 ]] ; then

echo 'need to pass args'

exit 0

fi

Check if required variables exist

if [ $1 == "one" ] || [ $1 == "two" ]

then

echo "argument 1 has the value one or two"

exit 0

else
echo "I require argument 1 to be one or two"

exit 1

fi

OR

NAME=${1}

if [ -z ${NAME} ]

then

echo NAME is undefined

exit 1

else

echo "Hi ${NAME}"

fi

Check if environment variables exists

if [ -z ${OWNER} ] || [ -z ${NAME} ]

then

echo "does not meet requirements of both environment variables"

exit 1

else

echo "required environment variables exists"

fi

While Loops
Run process for 5 Seconds

set -ex

count=0

echo "boot"

ping localhost &

while [ $count -le 5 ]

do

sleep 1

count=$((count + 1))

echo $count

done

ps aux | grep ping

echo "tear down"

kill $!

sleep 2

Run until state changes within ttl

UPDATE_COMPLETE=false

UPDATE_STATUS=running

COUNT=0

while [ ${UPDATE_COMPLETE} == false ]

do
if [ $count -gt 10 ]

then

echo "timed out"

exit 1

fi

if [ ${UPDATE_STATUS} == running ]

then

echo "still running"

sleep 1

COUNT=$((COUNT+1))

if [ $count == 7 ]

then

UPDATE_COMPLETE=true

fi

elif [ ${UPDATE_STATUS} == successful ]

then

UPDATE_COMPLETE=successful

else

echo "unexpected update response"

exit 1

fi
done

echo "complete"

for Loops

Upload all docker image

for i in $(ls | grep .tar): do

docker load -i $i;

done

Functions

message(){

NAME=${1}

echo "Hi ${NAME}"

OR pass all args:

message(){

echo "Hi $@"

Redirecting Outputs

Stdout, Stderr

Redirect stderr to /dev/null:


grep -irl faker . 2>/dev/null
Redirect stdout to one file and stderr to another file:
grep -irl faker . > out 2>error

Redirect stderr to stdout (&1), and then redirect stdout to a file:


grep -irl faker . >out 2>&1

Redirect both to a file:


grep -irl faker . &> file.log

Manipulating Text

Remove first 3 characters

$ STRING="abcdefghij"

$ echo ${STRING:3}

defghij

Only show last 3 characters

With tail to only show the last 3 characters:


$ STRING="abcdefghij"

$ echo ${STRING} | tail -c 4

hij

#bash #linux

2.65 GEEK

Iara Simões

8 months ago

Open options
Cómo optimizar el rendimiento de
compilación de su aplicación Next.js
Aprenda cómo mejorar el rendimiento de compilación de su aplicación Next.js
utilizando una variedad de técnicas, incluida la optimización de imágenes, la división
de código y el almacenamiento en caché.

A medida que las aplicaciones web modernas crecen, resulta cada vez más difícil
mantener su rendimiento. Por eso es esencial optimizar el rendimiento de la
aplicación desde el principio.

Con la llegada de marcos como Next.js, un marco popular de React, puedes crear
una aplicación web completamente funcional en solo unos minutos. Next.js ofrece
muchas funciones integradas, incluida la representación del lado del servidor, la
generación de sitios estáticos y el enrutamiento basado en archivos. También
proporciona muchas optimizaciones incorporadas para mejorar el rendimiento de la
aplicación.

En este artículo, veremos varios enfoques para optimizar el rendimiento de


compilación de su aplicación Next.js.

¿Qué es el rendimiento de construcción?


El rendimiento de compilación es el tiempo que lleva compilar su aplicación: es
decir, compilar y generar los archivos estáticos. Un rendimiento de compilación
rápido le permite iterar más rápido y entregar su aplicación a sus usuarios más
rápidamente.

Muchos factores pueden afectar el rendimiento de compilación de su aplicación,


incluido su tamaño y la cantidad de dependencias, páginas y componentes. Si el
rendimiento de compilación de su aplicación es lento, el rendimiento general de su
aplicación se verá afectado, lo que afectará la experiencia del usuario.

De forma predeterminada, Next.js proporciona muchas optimizaciones para mejorar


el rendimiento de la creación de aplicaciones. Además, existen muchos otros
enfoques que puede adoptar para mejorar aún más el rendimiento de compilación
de su aplicación. Vamos a ver.

Usando la última versión estable de Next.js


La forma más sencilla de mejorar el rendimiento de compilación de su aplicación
Next.js es utilizar la última versión estable de Next.js. El equipo detrás de Next.js
trabaja constantemente para mejorar aún más el marco y agregar nuevas funciones
y optimizaciones. Por lo tanto, es importante utilizar la última versión estable.
Al momento de escribir este artículo, la última versión estable de Next.js es v13.4.
Puede consultar la última versión estable de Next.js aquí y puede actualizar su
aplicación a la última versión estable de Next.js ejecutando el siguiente comando:

npm install next@latest

Aprovechando las optimizaciones incorporadas de


Next.js
Next.js proporciona varias optimizaciones incorporadas que puede utilizar para
mejorar el rendimiento de compilación de su aplicación, como optimización estática
automática, división de código, optimización de imágenes, optimización de fuentes y
captación previa, así como optimización de scripts de terceros.

Optimización estática automática


Si no hay rutas dinámicas en su aplicación, Next.js automáticamente representará
su aplicación como HTML estático de forma predeterminada. Si
ni getServerSidePropsni getInitialPropsestán definidos, Next.js no necesitará
volver a representar la página en cada solicitud, ya que las páginas se crearán una
vez y se entregarán a todos los usuarios.

Esta optimización mejora el rendimiento de la aplicación al reducir el tiempo que


lleva generar el HTML estático para la aplicación. La optimización estática es
perfecta para aplicaciones web sin rutas dinámicas y páginas que sólo cambian
ocasionalmente.

Para páginas que tienen rutas dinámicas o que obtienen datos de una API externa,
el uso de Next.js getServerSidePropso getInitialPropsfunciones le permite
prerenderizar la página en el servidor y recuperar los datos necesarios antes de
enviar el HTML al cliente. Esto ayuda a mejorar el tiempo de carga inicial y el
rendimiento general de la página.

División automática de código


La división de código es el proceso de dividir su código en fragmentos más
pequeños. Cada fragmento contiene el código requerido para una página en
particular.

De forma predeterminada, Next.js dividirá automáticamente su código en


fragmentos más pequeños para reducir el tiempo que lleva cargar el código de su
aplicación. Esto significa que Next.js solo cargará el código necesario para esa
página en particular en la carga inicial de la página.

Para aprovechar aún más los beneficios de la división de código, puede utilizar
importaciones dinámicas para cargar el código de una página en particular solo
cuando sea necesario. La división de código es útil para páginas que se visitan con
poca frecuencia.
Optimización automática de imágenes
Puede utilizar el next/imagecomponente, que es el <img>elemento incorporado de
Next.js, para optimizar automáticamente sus imágenes con carga diferida y
cambiando el tamaño o comprimiendo automáticamente las imágenes según el
tamaño del dispositivo.

La carga diferida es el proceso de cargar imágenes sólo cuando son necesarias: es


decir, cuando están visibles en la pantalla. La optimización automática de imágenes
reduce el tiempo que lleva cargar las imágenes en su aplicación, mejorando así el
rendimiento.

También puede especificar que algunas imágenes se carguen inicialmente


configurando el priorityaccesorio del next/imagecomponente en true. Next.js
priorizará la carga de las imágenes esenciales que desea cargar primero.

Optimización automática de fuentes


Next.js usa el next/fontcomponente para optimizar la fuente. Este componente
incluye alojamiento automático incorporado para Google Fonts. Puede utilizar
Google Fonts en su aplicación sin tener que preocuparse por el cambio de diseño o
el destello de texto invisible (FOIT).

Next.js descargará automáticamente las fuentes y las entregará desde su


aplicación. Las fuentes estarán disponibles para sus usuarios, incluso sin conexión.
Esto reduce el tiempo que lleva cargar las fuentes en su aplicación, mejorando así el
rendimiento de la aplicación.

Precarga automática
La captación previa se refiere a cargar el código de una página en particular antes
de que el usuario navegue a la página. De forma predeterminada, cuando utiliza
el Linkcomponente de next/link, Next.js buscará automáticamente el código de la
página que el usuario probablemente visitará a continuación.

Cuando se carga la página inicial, los enlaces visibles en la pantalla se recuperan


previamente. Esto es útil para páginas que se visitan con frecuencia.

Para las páginas que se visitan con menos frecuencia, puede usar
el prefetchaccesorio en el Linkcomponente y configurarlo falsepara deshabilitar la
captación previa para esa página. Con este enfoque, el código de la página solo se
buscará previamente cuando el usuario pase el cursor sobre el enlace.

Dependiendo del caso de uso, puede mejorar el rendimiento de su aplicación


con prefetch, reduciendo el tiempo que lleva cargar el código para la página
siguiente.

Optimización de scripts de terceros


Next.js proporciona un next/scriptcomponente para cargar scripts de terceros. De
forma predeterminada, este componente le permite cargar scripts temprano, pero
después de que se haya cargado algún contenido crítico para evitar bloquear la
carga de la página.

Next.js también garantiza que un script solo se cargue una vez, lo que resulta
beneficioso para los scripts utilizados en varias páginas de su aplicación. Incluso
cuando el usuario navega a una página que no usa el script, el script no se cargará
nuevamente cuando el usuario navega a una página que lo usa.

Optimización de la ruta de renderizado crítica


La ruta de renderizado crítica (CRP) se refiere a los pasos que sigue un navegador
para convertir HTML, CSS y JavaScript en una página web renderizada. Optimizar
CRP es esencial para mejorar el tiempo de carga inicial y el rendimiento percibido
de una aplicación web.

La optimización de CRP implica optimizar la entrega y la representación del


contenido más crítico para el usuario lo más rápido posible. Al minimizar el tiempo
que tarda el navegador en mostrar la página, puede mejorar el rendimiento percibido
y brindar una mejor experiencia de usuario. Echemos un vistazo más de cerca a
algunas técnicas para optimizar la representación de rutas críticas.

Gran optimización de pintura con contenido.


Large contentful paint (LCP) es una métrica de Core Web Vitals que mide el tiempo
que tarda el elemento de contenido más grande en la ventana gráfica en volverse
visible. LCP es crucial porque mide la velocidad de carga percibida de su aplicación.

Herramientas como Lighthouse y PageSpeed Insights pueden ayudar a identificar


oportunidades para mejorar el LCP de su aplicación. Algunas de las formas de
mejorar el LCP de una aplicación incluyen:

 Minimizar los recursos que bloquean el procesamiento : los recursos que


bloquean el procesamiento, como archivos CSS y JavaScript, impiden que el
navegador represente la página. Minimizar la cantidad de recursos que
bloquean el procesamiento puede mejorar el LCP de su aplicación
 Minimizar el trabajo del hilo principal : el hilo principal de una aplicación
analiza HTML, ejecuta JavaScript y representa la página. Minimizar la
cantidad de trabajo realizado en el hilo principal puede mejorar el LCP de una
aplicación.
 Reduzca el tiempo de ejecución de JavaScript : JavaScript es un lenguaje
de subproceso único, lo que significa que solo se ejecuta una tarea a la vez.
Reducir la cantidad de JavaScript ejecutado en el hilo principal puede mejorar
el LCP de su aplicación
 Uso asyncynext/script component to load scripts : Permitir que el
navegador descargue el script de forma asincrónica sin bloquear la
representación de la página también puede ayudar a mejorar el LCP de su
aplicación.
Usando la API de Intersection Observer
La API Intersection Observer es una API del navegador que nos permite observar
cambios en la intersección de un elemento de destino con su elemento ancestro o la
ventana gráfica de un documento de nivel superior. Esta API es útil para cargar
imágenes de forma diferida y otro contenido que no es visible en la pantalla. Puede
utilizar la API de Intersection Observer para mejorar el LCP de su aplicación
cargando contenido solo cuando esté visible en la pantalla.

Optimización y minificación de CSS y JS


La optimización y minificación de CSS y JavaScript eliminan caracteres innecesarios
de sus archivos CSS y JavaScript sin cambiar su funcionalidad. Evite el uso de
preprocesadores de CSS que agreguen caracteres innecesarios a sus archivos
CSS.

También puedes utilizar herramientas como PurgeCSS para eliminar CSS no


utilizado de tu aplicación. Esto reducirá el tamaño de sus archivos CSS, mejorando
el LCP de su aplicación. De manera similar, evite el uso de caracteres innecesarios
en sus archivos JavaScript. Herramientas como Terser también te ayudarán a
minimizar tus archivos JavaScript, reduciendo su tamaño y mejorando el LCP de tu
aplicación.

Mejorar el rendimiento de la red


Mejorar el rendimiento de la red es otra forma de reducir el rendimiento de
compilación de su aplicación Next.js. El rendimiento de la red es el tiempo que tarda
el navegador en descargar los recursos necesarios para su aplicación. Echemos un
vistazo a un par de estrategias para mejorar el rendimiento de la red de su
aplicación.

Almacenamiento en caché
El almacenamiento en caché almacena los recursos de su aplicación en el
navegador. La implementación de estrategias de almacenamiento en caché,
como encabezados de control de caché y trabajadores de servicios , puede ayudar
a mejorar el rendimiento de la red de su aplicación.

Los encabezados Cache-Control le permiten especificar políticas de


almacenamiento en caché del navegador, como cuánto tiempo almacenar en caché
un recurso y cuándo revalidar el recurso. Next.js le permite configurar los
encabezados de Cache-Control para su aplicación utilizando la headerspropiedad
en el next.config.jsarchivo.

Los trabajadores del servicio le permiten almacenar en caché recursos en el


navegador y servirlos desde el caché cuando el usuario está desconectado. Esto
reduce el tiempo que lleva cargar los recursos en su aplicación, mejorando así el
rendimiento de la red de su aplicación.
Integración CDN
Una red de entrega de contenido (CDN) es una red de servidores distribuidos
globalmente. Almacena sus activos estáticos en estos servidores, que se entregan a
los usuarios según su ubicación.

Puede almacenar en caché los activos estáticos y servirlos desde ubicaciones


perimetrales mediante una CDN para una entrega global más rápida. Next.js
también proporciona soporte incorporado para Vercel Edge Network . Si utiliza
Vercel para la implementación, Vercel Edge Network será una CDN
automáticamente.

Usando el análisis de paquetes


El análisis de paquetes es un enfoque para analizar su aplicación para identificar
oportunidades para reducir su tamaño. Con una herramienta de análisis de
paquetes, puede ver qué módulos de su paquete de aplicaciones ocupan mucho
espacio, identificar archivos innecesarios y encontrar formas de reducir el tamaño de
dichos archivos o eliminar los no utilizados.

Algunas herramientas para analizar el tamaño de su aplicación Next.js incluyen


next/bundle-analyzer, webpack-bundle-analyzer y next-bundle-analyzer.

Aprovechar la gestión de la dependencia


Administrar las dependencias en su aplicación es otra forma de mejorar el
rendimiento de su compilación. Al eliminar las dependencias no utilizadas y
optimizar las que se están utilizando, puede mejorar el rendimiento de su
compilación.

Eliminar dependencias no utilizadas


Las herramientas de gestión de dependencias, como depcheck , pueden ayudar a
identificar dependencias no utilizadas. Luego puede desinstalar las dependencias no
utilizadas, reduciendo el tamaño de su aplicación y mejorando su rendimiento de
compilación.

Sacudiendo el arbol
La agitación de árboles es el proceso de eliminar el código inactivo o no utilizado del
paquete final de su aplicación. use módulos ES6 en lugar de CommonJS para
aprovechar el soporte incorporado de Next.js para sacudir árboles. Por ejemplo,
utilice declaraciones importy exporten lugar de
declaraciones requirey module.exports.

Importaciones específicas
Al importar un módulo, solo debe importar las piezas que necesita. Es útil tener en
cuenta este enfoque para módulos que tienen muchas exportaciones.

Por ejemplo, en lugar de importar el módulo completo de esta manera:

import { Button, Card, Input } from "react-bootstrap";

Puede importar solo las partes del módulo que necesita, así:

import Button from "react-bootstrap/Button";

import Card from "react-bootstrap/Card";

import Input from "react-bootstrap/Input";

Excluir carpetas o archivos innecesarios


Otra forma de optimizar el rendimiento de compilación de su aplicación Next.js es
excluir carpetas o archivos innecesarios del proceso de compilación. Puede reducir
el tiempo de compilación y mejorar el rendimiento general excluyendo directorios o
archivos específicos que no son necesarios para representar su aplicación.

Puede utilizar la excludeopción en el next.config.jsarchivo para configurar el


proceso de compilación para excluir directorios o archivos específicos. Esto le
permite especificar patrones o rutas que deben ignorarse durante la compilación.

Por ejemplo, puede excluir carpetas que contengan archivos multimedia de gran
tamaño, documentación o activos específicos del desarrollo que no sean necesarios
para la compilación de producción:

module.exports = {

exclude: ["**/media/**", "**/docs/**", "**/dev/**"],

};

Al excluir recursos innecesarios de la compilación, reducirá la cantidad de datos que


deben procesarse y agruparse, lo que resulta en tiempos de compilación más
rápidos y una utilización de recursos más eficiente. Esta técnica de optimización es
ventajosa cuando se trata de proyectos grandes o cuando tiene carpetas o archivos
específicos que no contribuyen al renderizado.

Ejemplo de optimización del rendimiento de Next.js


Para demostrar el impacto significativo que algunos de los enfoques anteriores
pueden tener en el rendimiento de la compilación, creé una aplicación web Next.js
simple. Puedes encontrar la aplicación de ejemplo en GitHub . La aplicación tiene
cuatro páginas: home, form, accordiony carousel.

Optimicé completamente la mainrama de la aplicación web. Luego, construí otras


ramas, como unused-dependenciesy unnecessary-imports, para compararlas
con la mainrama.

Ejecutaremos yarn buildla terminal en la mainsucursal para construir la aplicación.


A continuación, puede ver el tamaño de compilación de cada página:

Ejemplo de aplicación Next.js,main branch build.

A continuación, instalé algunas dependencias innecesarias en la unused-


dependenciesrama:

 react-icons: El proyecto solo necesita un ícono y es mejor usar un SVG


 react-accessible-accordion: Construir un acordeón personalizado es fácil y
de menor tamaño
 react-hook-form: Para una forma simple, este paquete es excesivo
Ahora, ejecutemos yarn builden la terminal de esta rama. A continuación, puede
ver el tamaño de construcción de las páginas:

Ejemplo de aplicación Next.js, unused-dependenciescompilación de rama.

Si compara ambas compilaciones, notará una gran diferencia en el tamaño de la


página. La formpágina aumentó de 844Bhasta 8.416kBy la accordionpágina
aumentó de 1.39kBhasta 5.004kB. Comprender cuándo utilizar un paquete o una
dependencia puede ser vital para desarrollar el rendimiento.

Ahora, comparemos la unnecessary-importsrama con la mainrama. En esta nueva


rama, importé algunos archivos CSS accordiony luego ejecuté yarn build. El
tamaño de la página en forma de acordeón aumentó de 1.39kBa 5.26kB.

Ejemplo de aplicación Next.js, compilación de rama de importaciones innecesarias.

El rendimiento de la compilación sería aún más significativo si estos enfoques de


optimización se aplicaran a una base de código más compleja.

Conclusión
Optimizar el rendimiento de compilación de su aplicación Next.js es crucial para una
experiencia de usuario rápida y receptiva. Aproveche las optimizaciones
incorporadas de Next.js y otras técnicas, como optimizar las rutas de renderizado
críticas, mejorar el rendimiento de la red y aprovechar la gestión de dependencias
para mejorar el rendimiento de compilación de su aplicación. El monitoreo y las
pruebas continuas de su aplicación ayudarán a identificar áreas de mejora y
garantizarán mejoras continuas en el rendimiento.

Fuente: https://blog.logrocket.com

#nextjs
2.20 GEEK



Who to follow

Dylan Iqbal
1190 Posts

Follow

John David
633 Posts

Follow

Zara Bryant
814 Posts

Follow


Aamir Latif
3 Posts

Follow

Robert E. Hilton
262 Posts

Follow

Recommended

MySQL Cheat Sheet for Beginners and Advanced Users

SQL Cheat Sheet for Beginners and Advanced Users

Kubernetes Cheat Sheet for Beginners and Advanced Users


NumPy Cheat Sheet for Beginners and Advanced Users

CSS Cheat Sheet for Beginners and Advanced Users

Regex Cheat Sheet for Beginners and Advanced Users

This site uses Google AdSense ad intent links. AdSense autom

You might also like