Python is a high-level, interpreted programming language known for its simplicity and readability. It supports multiple programming paradigms, including procedural, object-oriented, and functional programming.
Key Concepts:
Python syntax is known for its readability and simplicity. Key aspects include:
#
symbol. They are used to
explain code and are ignored during execution.# This is a comment
def hello_world():
print("Hello, World!")
hello_world()
Python supports several data types:
5
, -3
3.14
, -0.001
"Hello"
, 'World'
[1, 2, 3]
,
['a', 'b', 'c']
(1, 2, 3)
,
('a', 'b', 'c')
{'key1': 'value1', 'key2': 'value2'}
number = 10 # Integer
price = 19.99 # Float
name = "Alice" # String
numbers = [1, 2, 3] # List
coordinates = (10, 20) # Tuple
person = {'name': 'Alice', 'age': 25} # Dictionary
Python includes various operators for performing arithmetic, comparison, and logical operations.
+
, -
, *
,
/
, %
, **
(exponentiation), //
(floor
division)
==
, !=
, >
,
<
, >=
, <=
and
, or
, not
# Arithmetic Operators
a = 10
b = 3
print(a + b) # Output: 13
print(a - b) # Output: 7
print(a * b) # Output: 30
print(a / b) # Output: 3.3333
print(a % b) # Output: 1
# Comparison Operators
print(a == b) # Output: False
print(a > b) # Output: True
# Logical Operators
print(a > 5 and b < 5) # Output: True
print(not (a > 5)) # Output: False
Conditional statements control the flow of execution based on certain conditions.
score = 85
if score >= 90:
grade = 'A'
elif score >= 80:
grade = 'B'
else:
grade = 'C'
print(f"Grade: {grade}") # Output: Grade: B
Loops allow you to execute a block of code multiple times.
# for Loop
for i in range(3):
print(i) # Output: 0 1 2
# while Loop
count = 0
while count < 3:
print(count) # Output: 0 1 2
count += 1
Strings are sequences of characters and can be manipulated in various ways.
+
operator.*
operator.upper()
, lower()
, and
replace()
.
text = "Hello, World!"
print(text + " Welcome!") # Output: Hello, World! Welcome!
print(text * 2) # Output: Hello, World!Hello, World!
print(text[0:5]) # Output: Hello
print(text.upper()) # Output: HELLO, WORLD!
Control structures in Python allow for conditional execution and looping through code blocks.
if
,
elif
, and else
.
for
and while
.# Conditional Statement
age = 20
if age >= 18:
print("Adult")
else:
print("Minor")
# Loop Example
for i in range(5):
print(i) # Output: 0 1 2 3 4
Functions in Python are defined using the def
keyword. They can take arguments and
return values.
def
, followed by the
function name and parentheses.return
keyword.
def greet(name):
return f"Hello, {name}!"
print(greet("Alice")) # Output: Hello, Alice!
HTML (HyperText Markup Language) is the standard language used to create and design web pages. It provides the basic structure for web documents by defining elements like headings, paragraphs, links, images, and other content. HTML uses tags to structure content and attributes to provide additional information about elements.
Key Concepts:
The structure of an HTML document is organized into a series of nested elements. The fundamental tags include:
<html>
: The root element that contains all other HTML
elements.<head>
: Contains meta-information about the document, such
as the title and links to stylesheets. It does not display content directly on the page.<body>
: Contains the content of the document that is
displayed on the web page, including headings, paragraphs, images, and other elements.<!DOCTYPE html>
<html>
<head>
<title>Page Title</title>
<link rel="stylesheet" href="styles.css">
</head>
<body>
<h1>Welcome to My Website</h1>
<p>This is a paragraph.</p>
<img src="image.jpg" alt="Description">
</body>
</html>
HTML includes a variety of elements to structure content on a web page:
<h1>
to <h6>
: Headings that define the
importance of sections. <h1>
is the largest and most important, while
<h6>
is the smallest.
<p>
: Defines a paragraph of text.<a>
: Defines a hyperlink that links to another page or
resource. Uses the `href` attribute to specify the URL.<img>
: Embeds an image in the document. Uses `src` attribute
to specify the image URL and `alt` attribute for alternative text.<ul>
: Defines an unordered (bulleted) list.<ol>
: Defines an ordered (numbered) list.<li>
: Defines a list item in both unordered and ordered
lists.<h1>Main Heading</h1>
<p>This is a paragraph with a link to an external website.</p>
<img src="logo.png" alt="Company Logo">
<ul>
<li>Item 1</li>
<li>Item 2</li>
</ul>
<ol>
<li>First</li>
<li>Second</li>
</ol>
Attributes provide additional information about HTML elements and modify their behavior or appearance. They are included in the opening tag of an element.
id
: Provides a unique identifier for an element. Useful for
styling with CSS or targeting with JavaScript.class
: Specifies one or more class names for an element, allowing
you to apply CSS styles to multiple elements.src
: Specifies the source URL of an image or other media. Used
with the `` element.href
: Specifies the URL of the page or resource that a hyperlink
points to. Used with the `` element.alt
: Provides alternative text for an image if it cannot be
displayed. Used with the `` element.<img id="logo" class="responsive" src="logo.png" alt="Company Logo">
<a href="https://www.example.com" class="external-link">Visit Example</a>
JavaScript is a programming language that enables interactive web pages. It is a core technology of the World Wide Web, alongside HTML and CSS, and is used to enhance user interaction and control web page behavior. JavaScript can manipulate the DOM (Document Object Model), handle events, and perform various other tasks to make web pages dynamic and interactive.
Key Concepts:
Variables are containers for storing data values. In JavaScript, you can declare variables using `var`, `let`, and `const`:
var
: The oldest keyword for declaring variables. It is
function-scoped and can be re-declared and updated.let
: Introduced in ES6 (ECMAScript 2015), it is block-scoped and
can be updated but not re-declared in the same scope.const
: Also introduced in ES6, it is block-scoped and cannot be
updated or re-declared. It is used for variables whose values should remain constant.
let name = 'John'; // Block-scoped variable
const age = 30; // Block-scoped constant
var isStudent = true; // Function-scoped variable
console.log(name); // Output: John
console.log(age); // Output: 30
console.log(isStudent); // Output: true
JavaScript supports several data types:
String
: Represents a sequence of characters. Enclosed in single
quotes (`'`), double quotes (`"`), or backticks (`` ` ``).Number
: Represents numeric values, including integers and
floating-point numbers.Boolean
: Represents a true or false value.Array
: An ordered collection of values. Arrays can contain
elements of different types.Object
: A collection of key-value pairs. Objects are used to store
and manage data.
let name = 'Alice'; // String
let age = 25; // Number
let isStudent = false; // Boolean
// Array
let fruits = ['Apple', 'Banana', 'Cherry'];
// Object
let person = {
firstName: 'John',
lastName: 'Doe',
age: 30
};
console.log(fruits[0]); // Output: Apple
console.log(person.firstName); // Output: John
Functions are blocks of code designed to perform a specific task. They can be declared and called, and can accept parameters and return values:
function greet(name) {
return `Hello, ${name}!`;
}
let message = greet('Alice');
console.log(message); // Output: Hello, Alice!
Events are actions or occurrences that happen in the browser, such as clicks, form submissions, or key presses. JavaScript can be used to handle these events and execute code in response:
addEventListener
: Attaches an event handler to an element. It
allows you to specify the type of event and the function to be executed.
document.querySelector('button').addEventListener('click', function(event) {
alert('Button was clicked!');
console.log(event); // Output: Event object with details about the click event
});
Data types define the kind of data that can be stored and manipulated within a programming language. Understanding data types is fundamental to writing effective and error-free code. In JavaScript, data types are categorized into primitive and composite types, and you can perform type conversion between these types.
Key Concepts:
Primitive data types are the basic types of data in JavaScript. They represent single values and are immutable (cannot be changed).
Number
: Represents numeric values, including integers and
floating-point numbers. JavaScript does not differentiate between integer and floating-point
numbers; all numbers are of type `Number`.String
: Represents a sequence of characters enclosed in single
quotes (`'`), double quotes (`"`), or backticks (`` ` ``). Strings are immutable.Boolean
: Represents a logical entity with two possible values:
`true` or `false`.Null
: Represents a deliberate non-value. It is used to indicate
that a variable has no value or is empty.Undefined
: Represents a variable that has been declared but has
not been assigned a value. It is the default value for uninitialized variables.
let age = 25; // Number
let name = 'Alice'; // String
let isStudent = true; // Boolean
let emptyValue = null; // Null
let notAssigned; // Undefined
console.log(typeof age); // Output: number
console.log(typeof name); // Output: string
console.log(typeof isStudent); // Output: boolean
console.log(typeof emptyValue); // Output: object
console.log(typeof notAssigned); // Output: undefined
Composite data types are structures that can hold multiple values. They are mutable, meaning their contents can be modified.
Array
: An ordered collection of values, which can be of any data
type. Arrays are indexed, meaning each value has a numeric index starting from 0.Object
: A collection of key-value pairs where keys are strings (or
Symbols) and values can be any data type. Objects are useful for grouping related data together.
let fruits = ['Apple', 'Banana', 'Cherry']; // Array
let person = {
firstName: 'John',
lastName: 'Doe',
age: 30
}; // Object
console.log(fruits[1]); // Output: Banana
console.log(person.firstName); // Output: John
Type conversion refers to the process of converting one data type to another. In JavaScript, type conversion can be implicit (automatic) or explicit (manual).
let num = 5;
let str = '10';
// Implicit Conversion
let result = num + str; // '510' (number is converted to string)
console.log(result);
// Explicit Conversion
let numberFromStr = Number(str); // Converts string to number
console.log(numberFromStr + num); // Output: 15
let booleanValue = Boolean(0); // Converts 0 to boolean (false)
console.log(booleanValue); // Output: false
Control flow refers to the order in which individual statements, instructions, or function calls are executed or evaluated in a programming language. Understanding control flow is essential for writing effective and efficient code.
Key Concepts:
Conditional statements allow you to execute certain blocks of code based on specific conditions. They are fundamental to decision-making in programming.
# Python Example
age = 20
if age >= 18:
print("You are an adult.")
else:
print("You are a minor.")
# JavaScript Example
let day = "Monday";
switch (day) {
case "Monday":
console.log("Start of the work week.");
break;
case "Friday":
console.log("End of the work week.");
break;
default:
console.log("It's a regular day.");
}
Loops allow you to execute a block of code multiple times, which is useful for tasks that require repeated actions.
# Python Example
# for Loop
for i in range(5):
print(i) # Output: 0 1 2 3 4
# while Loop
count = 0
while count < 5:
print(count) # Output: 0 1 2 3 4
count += 1
# JavaScript Example
let i = 0;
do {
console.log(i); // Output: 0 1 2 3 4
i++;
} while (i < 5);
Exception handling allows you to manage errors and exceptional conditions that may occur during the execution of your program. It ensures that your program can handle errors gracefully without crashing.
# Python Example
try:
result = 10 / 0 # This will raise a ZeroDivisionError
except ZeroDivisionError:
print("Cannot divide by zero!")
finally:
print("Execution completed.")
# JavaScript Example
try {
let result = 10 / 0; // This will not raise an error in JavaScript
} catch (error) {
console.log("An error occurred:", error);
} finally {
console.log("Execution completed.");
}