This Comprehensive Python Cheat Sheet Covers Everything You Need To Know To Get Started With Python
This Comprehensive Python Cheat Sheet Covers Everything You Need To Know To Get Started With Python
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?
The Arithmetic Operators in the below table are in Lowest to Highest precedence.
>>> 1 + 3
>>> 1 - 3
-2
#Example for Multiplication
>>> 6 * 6
36
>>> 4 // 2
>>> 3 / 2
1.5000
>>> 3 % 2
The table below lists the different data types in Python along with some examples
of them:
DataTypes Examples
Integers 0, 2, -1, 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”.
>>> variable_name
'Hello'
>>> variableName
123
4. Python Comments
Comments are lines of text/code in the program, which are ignored by the compiler
during program execution.
Inline Comment -
return a + b
Multiline Comment -
# Multiline
# Comment
# Function to calculate
# sum of 2 numbers
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.
'''
return a + b
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.
My name is Interviewbit
>>> print(123)
123
>>> a = [1, 2, 3, 4]
>>> print(a)
[1, 2, 3, 4]
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.
Interviewbit
Hello, Interviewbit
# For List
a = [1, 2, 3]
print(len(a))
# For string
a = "hello"
print(len(a))
# For tuple
print(len(a))
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(ord('A'))
print(ord('5'))
print(ord('$'))
Output:
65
53
36
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
print(type(int_num))
print(type(float_num))
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'
>>> float(var)
123.0
2. Float to Integer:
To typecast a float datatype into an integer datatype, we use the int() method.
For example:
>>> print(int(var))
The Table gives a list of relational operators available in Python along with their
functions:
== Is equal to
!= Not Equal to
>>> 10 == 10
>>> 10 == "10"
False # The first string is of type int, 2nd of type string, so false.
# Greater than
>>> 10 > 20
# Inequality
>>> 10 != 20
>>> (2 + 3) >= (4 + 1)
Note: Never use relational operators to compare boolean operations. Use is or is not
operators for it.
>>> True is False
False
True
The Table gives a list of boolean operators available in Python along with their
functions:
Operator What it does
Examples:
# and operator
False
# or operator
print(True or False)
True
# not operator
print(not False)
True
... 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"
... print("Same")
...
Same
... else:
... print("Same")
...
Same
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:
print(i)
Output:
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
... print(count)
... count -= 1
...
2
1
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:
... print(i)
... if i == 3:
... break
...
... if i == 3:
... continue
... print(i)
...
0
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:
return a + b
print(a + b)
print(getSum(5, 6))
printSum(5, 6)
Scope of a variable is the part of the code, where it can be accessed freely and used
by the program.
The rules used in Python to resolve scope for local and global variables are as
follows:
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.
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.
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.
Example:
try:
return a / denominator
except ZeroDivisionError as e:
print('Divide By Zero!! Terminate!!')
finally:
print('Division Complete.')
Lists are used to store multiple items in a single variable. Their usage and some
functions are shown below with examples:
print(example)
Output:
# 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:
# Positive Slicing
print(example[0:2])
# Negative Slicing
print(example[-3:-1])
Output:
['Sunday', 'Monday']
['Monday', 'Tuesday']
print(example)
example[0] = "Saturday"
print(example)
Output:
When we merge the contents of 2 lists into one list, it is called list concatenation.
example = ["Sunday", "Monday", "Tuesday", "Wednesday"];
# Concatenation
print(example)
Output:
Copying the contents of a list, some finite number of times into the same or some list
is called list replication.
# Replication
example1 = example1 * 3
print(example1)
Output:
print(example)
del example[2]
print(example)
Output:
for ex in example:
print(ex)
Output:
Sunday
Monday
Tuesday
Wednesday
print("Sunday" in example)
Output:
True
True
print(example)
example.insert(1, 'Days')
print(example)
Output:
print(example)
example.append('Days')
print(example)
Output:
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
print(example)
example.sort()
print(example)
example.sort(reverse = True)
print(example)
example = [1, 5, 3, 7, 2]
example.sort()
print(example)
example.sort(reverse = True)
print(example)
Output:
[7, 5, 3, 2, 1]
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.
print(example)
print(example[1:3])
Output:
('Second', 'Third')
list("Scaler")
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.
print(key)
# dict.values() method will print only the values of the corressponding keys of the
dictionary
print(value)
Output:
first
second
third
sunday
monday
tuesday
dict['fourth'] = 'wednesday'
print(item)
Output:
('first', 'sunday')
('second', 'monday')
('third', 'tuesday')
('first', 'sunday')
('second', 'monday')
('third', 'tuesday')
('fourth', 'wednesday')
print(item)
dict['third'] = 'wednesday'
print(item)
Output:
('first', 'sunday')
('second', 'monday')
('third', 'tuesday')
('first', 'sunday')
('second', 'monday')
('third', 'wednesday')
print(item)
del dict['third']
print(item)
Output:
('first', 'sunday')
('second', 'monday')
('third', 'tuesday')
('first', 'sunday')
('second', 'monday')
Merging 2 dictionaries
dict2 = {1: 3, 2: 4, 3: 5}
dict1.update(dict2)
print(dict1)
Output:
Initializing Sets:
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)
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}
s.update([6, 7, 8])
print(s)
Output:
{1, 2, 3, 4, 5, 6, 7, 8}
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)
s.discard(1)
print(s)
Output:
{1, 2, 3, 4, 5}
{1, 2, 3, 5}
{2, 3, 5}
Operators in 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.
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)
print(a | b)
print(a - b)
print(a ^ b)
Output:
{3, 4}
{1, 2, 3, 4, 5, 6, 7, 9}
{1, 2, 5}
{1, 2, 5, 6, 7, 9}
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 = {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}
print(b)
Output:
Escape Sequences:
Escape Sequences are used to print certain characters to the output stream which
carry special meaning to the language compiler.
Examples:
\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.
a = "Python"
print(a[0], a[2], a[4])
Output:
Pto
nhy
Strings Slicing:
a = "Hello"
print(a[0:3])
print(a[3:-1])
Output:
Hel
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())
print(a.lower())
print(a.isupper())
print(a.islower())
Output:
Hello
HELLO
hello
False
False
Function Explanation
isTitle() Returns True if string starts with an uppercase letter and then rest of the characters are lowercase
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:
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:
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:
Example:
'Hey Scaler!'
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
print(tm)
Output:
01:30:11.000022
date class: We can represent date values using the date class.
Example:
import datetime
print('Date date is ', date.day, ' day of ', date.month, ' month of the year ', date.year)
Output:
Example:
print(datetime.strptime('15/11/2000', '%d/%m/%Y'))
Output:
2000-11-15 00:00:00
For example:
print(s)
Output:
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')
Output:
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)')
# 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
There are a lot of regex symbols that have different functionalities so they are
mentioned in the table below:
Symbol Matches
Example:
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
raise keyword
Exception() function call
Parameter of the Exception() function, which usually contains an error
message.
Traceback as String
Example:
import traceback
try:
except:
with open('error.txt', 'w') as error_file:
error_file.write(traceback.format_exc())
Output:
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
Assertions can be disabled by passing the -O option when running Python as shown
in the commands below.
AssertionError
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
logg = logging.getLogger()
logg.setLevel(logging.DEBUG)
# Messages
logg.debug("Debug Message")
logger.warning("Its a Warning")
logger.info("Just an information")
Levels of Logging:
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.
These are small anonymous functions in python, which can take any number of
arguments but returns only 1 expression.
return a * b
print(mul(3, 5))
Output:
15
mul = lambda a, b: a * b
print(mul(3, 5))
Output:
15
Similarly, other functions can be written as Lambda functions too, resulting in shorter
codes for the same program logic.
28. Ternary Operator in Python
f=2
s=2
Output:
Example:
def tester(*argv):
print(arg)
tester('Sunday', 'Monday', 'Tuesday', 'Wednesday')
Output:
Sunday
Monday
Tuesday
Wednesday
Example:
def tester(**kwargs):
print(key, value)
Output:
Sunday 1
Monday 2
Tuesday 3
Wednesday 4
... main()
Python Classes used for storing data objects are called Dataclasses. They have
certain features like:
class Self:
self.x = x
ob = Self("One")
print(ob.x)
Output:
One
Python 3.7:
class Self:
x: string
ob = Self("One")
print(ob.x)
Output:
One
@dataclass
class WithoutExplicitTypes:
name: Any
age: Any = 16
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:
Usage Steps:
#setprojectdir .
deactivate # To move to something else in the command #line.
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.
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
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.
Note: All the magic commands can be listed by using the %lsmagic command.
Some other useful tools for Python
Conclusion
#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.
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
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.
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.
Projects Overview:
Throughout this course, you'll have the opportunity to work on a wide range of
projects, including:
3. Poll System Application: Build a dynamic polling system for user engagement.
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.
14. Digital Clock Project: Display a sleek digital clock on your web page.
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)
Iara Simões
7 months ago
Open options
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.
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:-
continue Skips the rest of the loop and starts the next iteration
if Used in an if statement
// Hello World
class GFG {
System.out.println("Hello World!");
Output
Hello World!
Data Types in Java are the different values and sizes that can be stored in the
variable according to the requirements.
8 -128 to 127
byte
bits (none)
characters representation of
ASCII values
char 𠆊’, ‘\u0041’,
16 ‘\101’, ‘\\’, ‘\ 0 to 255
bits ’, ‘\n’, ‘β’
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
5. Java Comments
import java.io.*;
class GFG {
System.out.println("GFG!");
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.
import java.io.*;
class GFG {
System.out.println("GFG!");
*/
Output
GFG!
Syntax:
*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
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:
// Variables
import java.io.*;
class GFG {
// instance variable
// static variable
{
// here int i is local variable
GFG.count++;
System.out.println(i);
// local variable
int i = 10;
+ GFG.count);
help(i);
+ GFG.count);
temp.revise = i + count;
System.out.println("Instance variable value:"
+ temp.revise);
Output
10
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
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
Here is the table representing the precedence order of Java operators from high to
low as we move from top to bottom.
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:-
// if - else if - else
import java.io.*;
// Driver Class
class GFG {
// main function
int a = 1, b = 2;
if (a < b)
System.out.println(b);
else if (a > b)
System.out.println(a);
else
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.
import java.util.*;
class NestedIfDemo {
int i = 10;
if (i == 10 || i < 15) {
// First if statement
if (i < 15)
// Nested - if statement
// it is true
if (i < 12)
System.out.println(
else {
Output
i is smaller than 15
2. Switch Statement
int day = 5;
String dayString;
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:
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
import java.io.*;
// Driver Class
class GFG {
// Main function
int n = 5;
System.out.println(i);
import java.io.*;
// Driver Class
class GFG {
// main function
public static void main(String[] args)
int i = 16;
while (i != 0) {
System.out.println(i);
if (i > 4)
i -= 4;
else
i -= 1;
// do-while loop
// Driver Class
class GFG {
// main function
public static void main(String[] args)
int i = 1;
do {
System.out.println(i);
i++;
Output
Java Methods are collections of statements that perform some specific task and
return the result.
Syntax of Method
//body
}
// Use of Methods
import java.io.*;
// Driver Class
class GFG {
// main method
int n = 3, m = 3;
System.out.println();
}
}
Output
012
123
234
We can only print using System.out but can use different print varieties in it:
1. print
2. println
3. printf
Formatted Print
System.out.printf("%7.5f", Math.PI);
7 is the Field width and .5 is the precision fo the floating number printed . So,
answer will be 3.14159
class GFG {
System.out.println(args[i]);
javac GFG.java
Output:
This
is
just
to
Check
import java.io.*;
class GFG {
// Main Method
throws IOException
// stream of character
new InputStreamReader(System.in));
int it = Integer.parseInt(bfn.readLine());
// Printing String
// Printing Integer
Output:
ABC
11
Entered Integer : 11
3. Scanner Class
Syntax:
import java.io.*;
import java.util.Scanner;
class GFG {
String name;
int rollno;
float marks;
name = obj.nextLine();
marks = obj.nextFloat();
Output:
ABC
65
Name :ABC
Marks :65
Polymorphism: It is the ability to differentiate between entities with the same name
efficiently.
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:
// Polymorphism
import java.io.*;
// Class
class ABC {
// Sum Method with int returning value
// Driver Class
class GFG {
// main function
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.
// Inheritance (concise)
import java.io.*;
class Employee {
// Driver Class
class Gfg {
Output
Salary : 70000
Benefits : 15000
In Java, there exists a Math Library that can simplify intricate calculations
Library:
import java.lang.Math;
Use:
Math.function_name <parameters>
Note: All the functions mentioned above can be used with either data-types not
bounded any single data-types.
Type Casting is a method in which we convert from one data type to another.
Type Conversion in Java is a technique where we can convert from double, int, and
float to double.
// Main class
int a = 3;
double db = (double)a;
System.out.println(db);
// Type Conversion
import java.io.*;
// Driver Class
class GFG {
// main function
long a = 1;
byte b = 1;
double c = 1.0;
// Type Conversion
System.out.print(final_datatype);
Output
3.0
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:
// arrays
class GFG {
// elements
arr[0] = 10;
arr[1] = 20;
arr[2] = 30;
arr[3] = 40;
arr[4] = 50;
Output
arr[0] :10
arr[1] :20
arr[2] :30
arr[3] :40
arr[4] :50
Syntax:
// driver class
// main function
int arr[][]
= { { 1, 2, 3 }, { 4, 5, 6 }, { 7, 8, 9 } };
// printing 2D array
System.out.println();
Output
123
456
789
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=" ";
1. StringBuffer
2. StringBuilder
str.append("GFG");
3. String Tokenizer
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
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, int flags) Turns a regular expression into a pattern using the flags provided.
Method Description
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.
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.
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.
Types of 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 {
// optional
final
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.
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).
Generics means parameterized types. The idea is to allow type (Integer, String,
… 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.
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.
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.
// Generic functions
class Test {
System.out.println(element.getClass().getName()
// Driver method
genericDisplay(11);
// Calling generic method with String argument
genericDisplay("GeeksForGeeks");
genericDisplay(1.0);
Output
java.lang.Integer = 11
java.lang.String = GeeksForGeeks
java.lang.Double = 1.0
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.
try {
System.out.println(
+ " is running");
catch (Exception e) {
// Throwing an exception
System.out.println("Exception is caught");
// Main Class
= 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
List Interface
Queue Interface
Deque Interface
Set Interface
SortedSet Interface
Map Interface
Collection Interface
Iterable Interface
Interfaces Syntax
Queue Interface
Queue <T> ad = new ArrayDeque<> ();
Map Interface
Map<T> tm = new TreeMap<> ();
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’t 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
Check Price
Key Information
Author: Joe Hocking Publisher: Manning
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
Check Price
Key Information
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
Check Price
Key Information
Author: Paris Buttfield-Addison, Jon Manning, and Tim Nugent Publisher: O'Reilly Media
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
Check Price
Key Information
Features
Check Price
Key Information
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
6. C#: 3 Books in 1
Check Price
Key Information
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
Check Price
Key Information
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
Key Information
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
Check Price
Key Information
Author: Jiadong Chen Publisher: Packt Publishing
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
Check Price
Key Information
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
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.
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.
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:
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. 🐺
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.
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.
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:
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:
And beyond.
➡️Mastering Dart is for experienced Dart developers who want to build high-
performance applications.
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:
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.
The Dart Programming Language shares valuable insights into the fundamentals
of Dart. You’ll look at how Dart:
And more.
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 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:
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.
1 Likes3.00 GEEK
Iara Simões
8 months ago
Open options
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!
The following snippet shows the general syntax to define a function in Python:
def function_name(parameters):
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.
Let's now create a simple function in Python that greets the user, as shown below:
def 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
Now, we shall modify the function my_func() to include the name and place of the
user.
def my_func(name,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
What happens if you specify the place first and then the name? Let's find out.
my_func("Hawaii","Robert")
# Output
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
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.
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 = 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.
total_calc(150)
# Output
total_calc(200,15)
# Output
total_calc(167,7.5)
# Output
Please pay $179.53
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.
volume = volume_of_cuboid(5.5,20,6)
# Output
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.
def cube(side):
surface_area = 6 * (side**2)
returned_values = cube(8)
print(returned_values)
# Output
(512, 384)
Now, we shall unpack the tuple and store the values in two different variables.
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
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
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! 🙂
sum = my_var_sum(99,10,54,23)
# Output
sum = my_var_sum(9,87,45)
# Output
The numbers that you have add up to 141
sum = my_var_sum(5,21,36,79,45,65)
# Output
⌛ A Quick Recap
Let's quickly summarize what we've covered. In this tutorial, we've learned:
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.
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.
Amazon: 4.4
Goodreads:
3.93
1 Angular Development with TypeScript Yakov Fain and Anton Moiseev 2018
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
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:-
Review
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
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
Author: Nathan Murray, Felipe Coury, Ari Lerner, and Carlos Taborda
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
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
Review
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
Review
Key Takeaways
Review
Review
Key Takeaways
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
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
#angular
1 Likes4.80 GEEK
Iara Simões
8 months ago
Open options
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">
<div class="calculator-keys">
<button type="button" class="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 {
position: absolute;
top: 50%;
left: 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;
background-color: transparent;
font-size: 2rem;
color: #333;
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-gap: 20px;
padding: 20px;
JavaScript:
const calculator = {
displayValue: '0',
firstOperand: null,
waitingForSecondOperand: false,
operator: null,
};
function inputDigit(digit) {
calculator.displayValue = digit;
calculator.waitingForSecondOperand = false;
} else {
function inputDecimal(dot) {
calculator.displayValue = "0."
calculator.waitingForSecondOperand = false;
return
if (!calculator.displayValue.includes(dot)) {
calculator.displayValue += dot;
function handleOperator(nextOperator) {
calculator.operator = nextOperator;
return;
calculator.firstOperand = inputValue;
} else if (operator) {
calculator.displayValue = `${parseFloat(result.toFixed(7))}`;
calculator.firstOperand = result;
calculator.waitingForSecondOperand = true;
calculator.operator = nextOperator;
return secondOperand;
function resetCalculator() {
calculator.displayValue = '0';
calculator.firstOperand = null;
calculator.waitingForSecondOperand = false;
calculator.operator = null;
function updateDisplay() {
updateDisplay();
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.
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.
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">
<title>KeyBoard Music</title>
</head>
<body>
<div class="keys">
<kbd>A</kbd>
</div>
<kbd>S</kbd>
</div>
<kbd>D</kbd>
</div>
<kbd>F</kbd>
</div>
<kbd>G</kbd>
</div>
<kbd>H</kbd>
</div>
<kbd>J</kbd>
</div>
<kbd>K</kbd>
</div>
<kbd>L</kbd>
</div>
</div>
</body>
<script>
function removeTransition(event) {
function playSound(event) {
if (!audio) return
key.classList.add('playing')
audio.currentTime = 0
audio.play()
window.addEventListener('keydown', playSound)
</script>
<style>
html {
font-size: 12px;
background-size: 80%;
.keys {
display: flex;
flex: 1;
align-items: top;
justify-content: center;
.key {
border-radius: 0.5rem;
margin: 1rem;
font-size: 2rem;
width: 5rem;
text-align: center;
color: black;
</style>
</html>
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.
<html>
<head>
<title>Form Validation</title>
function validate() {
var text;
document.getElementById("demo").innerHTML = text;
document.myForm.name.focus() ;
return false;
document.getElementById("demo").innerHTML = text;
document.myForm.email.focus() ;
return false;
atposn = emailID.indexOf("@");
dotposn = emailID.lastIndexOf(".");
document.getElementById("demo").innerHTML = text;
document.myForm.email.focus() ;
return false;
document.myForm.phone.value.length != 10 ) {
document.getElementById("demo").innerHTML = text;
document.myForm.phone.focus() ;
return false;
document.getElementById("demo").innerHTML = text;
return false;
return( true );
</script>
</head>
<body>
<tr>
</tr>
<tr>
</tr>
<tr>
<td align = "right">Phone Number</td>
</tr>
<tr>
<td>
</select>
</td>
</tr>
</table>
</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>
</head>
<script>
function display(element){
document.getElementById('image').innerHTML = element.alt;
function revert(){
</script>
<style>
#image{
width: 650px;
height: 70px;
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>
<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.
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.
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.
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.
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.
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.
#javascript #js
2.80 GEEK
Iara Simões
8 months ago
Open options
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
185.36.81.164
175.139.231.129
185.211.245.170
185.211.245.170
185.36.81.173
112.196.77.202
113.172.210.19
113.173.182.119
139.59.224.234
If Statements
if [[ $# -eq 0 ]] ; then
exit 0
fi
if [ $1 == "one" ] || [ $1 == "two" ]
then
exit 0
else
echo "I require argument 1 to be one or two"
exit 1
fi
OR
NAME=${1}
if [ -z ${NAME} ]
then
exit 1
else
fi
if [ -z ${OWNER} ] || [ -z ${NAME} ]
then
exit 1
else
fi
While Loops
Run process for 5 Seconds
set -ex
count=0
echo "boot"
do
sleep 1
count=$((count + 1))
echo $count
done
kill $!
sleep 2
UPDATE_COMPLETE=false
UPDATE_STATUS=running
COUNT=0
do
if [ $count -gt 10 ]
then
exit 1
fi
if [ ${UPDATE_STATUS} == running ]
then
sleep 1
COUNT=$((COUNT+1))
if [ $count == 7 ]
then
UPDATE_COMPLETE=true
fi
then
UPDATE_COMPLETE=successful
else
exit 1
fi
done
echo "complete"
for Loops
done
Functions
message(){
NAME=${1}
message(){
Redirecting Outputs
Stdout, Stderr
Manipulating Text
$ STRING="abcdefghij"
$ echo ${STRING:3}
defghij
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.
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.
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.
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.
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.
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.
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.
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.
Puede importar solo las partes del módulo que necesita, así:
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 = {
};
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