[Go to site: main page, start]

0% found this document useful (0 votes)
11 views15 pages

Python Data Types and Examples

The document provides an overview of fundamental data types in Python, including integers, floats, strings, lists, tuples, dictionaries, booleans, sets, and NoneType, along with examples of their usage. It also includes Python programs for calculating the area of a triangle and performing arithmetic operations, demonstrating user input handling and function definitions. Additionally, it covers variable swapping techniques in Python and provides HTML examples for implementing similar functionalities in web applications.

Uploaded by

rubiakahelohei
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
11 views15 pages

Python Data Types and Examples

The document provides an overview of fundamental data types in Python, including integers, floats, strings, lists, tuples, dictionaries, booleans, sets, and NoneType, along with examples of their usage. It also includes Python programs for calculating the area of a triangle and performing arithmetic operations, demonstrating user input handling and function definitions. Additionally, it covers variable swapping techniques in Python and provides HTML examples for implementing similar functionalities in web applications.

Uploaded by

rubiakahelohei
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

01.

Integer (“int”)
An integer represents whole numbers, positive or negative, without any decimal points.

# Example of an integer
my_integer = 42
print(my_integer)
# Output: 42

02. Float (“float”)


A float represents floating-point numbers, which include decimal points.

# Example of a floating-point number


my_float = 3.14
print(my_float)
# Output: 3.14

03. String (“str”)


Strings represent sequences of characters, enclosed in either single quotes (' ') or double quotes ("
").

# Example of a string
my_string = "Hello, Python!"
print(my_string)
# Output: Hello, Python!

04. List
Lists are ordered collections of items that are mutable (can be changed).

# Example of a list
my_list = [1, 2, 3, 'a', 'b', 'c']
print(my_list)
# Output: [1, 2, 3, 'a', 'b', 'c']

05. Tuple
Tuples are ordered collections similar to lists, but they are immutable (cannot be changed).

# Example of a tuple
my_tuple = (4, 5, 'x', 'y')
print(my_tuple)
# Output: (4, 5, 'x', 'y')

06. Dictionary (“dict”)


Dictionaries are collections of key-value pairs.

# Example of a dictionary
my_dict = {'name': 'Alice', 'age': 30, 'city': 'New York'}
print(my_dict)
# Output: {'name': 'Alice', 'age': 30, 'city': 'New York'}
07. Boolean (“bool”)
Booleans represent truth values, either True or False.
# Example of a boolean
my_boolean = True
print(my_boolean)
# Output: True

08. Set
Sets are unordered collections of unique elements.

# Example of a set
my_set = {1, 2, 3, 4, 4, 3, 2} # Note: Duplicates are automatically removed in a set
print(my_set)
# Output: {1, 2, 3, 4}

09. NoneType (“None”)


None represents the absence of a value.

# Example of NoneType
my_none = None
print(my_none)
# Output: None

These are some of the fundamental data types in Python. Each type serves its purpose in different
scenarios and allows for flexible and versatile programming.

# Integer data type


my_integer = 42
print("Integer data type:", my_integer)

# Float data type


my_float = 3.14
print("Float data type:", my_float)

# String data type


my_string = "Hello, Python!"
print("String data type:", my_string)

# List data type


my_list = [1, 2, 3, 'a', 'b', 'c']
print("List data type:", my_list)

# Tuple data type


my_tuple = (4, 5, 'x', 'y')
print("Tuple data type:", my_tuple)
# Dictionary data type
my_dict = {'name': 'Alice', 'age': 30, 'city': 'New York'}
print("Dictionary data type:", my_dict)

# Boolean data type


my_boolean = True
print("Boolean data type:", my_boolean)

# Set data type


my_set = {1, 2, 3, 4, 4, 3, 2} # Duplicates are automatically removed in a set
print("Set data type:", my_set)

# NoneType data type


my_none = None
print("NoneType data type:", my_none)

Output:
Integer data type: 42
Float data type: 3.14
String data type: Hello, Python!
List data type: [1, 2, 3, 'a', 'b', 'c']
Tuple data type: (4, 5, 'x', 'y')
Dictionary data type: {'name': 'Alice', 'age': 30, 'city': 'New York'}
Boolean data type: True
Set data type: {1, 2, 3, 4}
NoneType data type: None

# Python Program for Area of Triangle:


b = float(input('Enter the base: '))
h= float(input('Enter the height: '))

# calhculate the area


area = 1/2*b*h
print('The area of the triangle is %0.2f' % area)

Output:
Enter the base: 10
Enter the height: 5
The area of the triangle is 25.00
def calculate_triangle_area(base, height):
# Area of a triangle formula: area = 0.5 * base * height
area = 0.5 * base * height
return area

# Example values for base and height


base_length = 8
height_length = 5

# Calculating the area of the triangle


triangle_area = calculate_triangle_area(base_length, height_length)

# Displaying the result


print(f"The area of the triangle with base {base_length} and height
{height_length} is: {triangle_area}")

Output:
The area of the triangle with base 8 and height 5 is: 20.0

 The f at the beginning of the print statement is a prefix indicating an f-string in


Python. It stands for "formatted string."
 In Python, an f-string is a string literal that has an f at the beginning and curly
braces { } containing expressions that will be replaced with their values when the
string is formatted. It allows for easy string interpolation, allowing variables and
expressions to be directly embedded within the string.

def calculate_triangle_area(base, height):


# Area of a triangle formula: area = 0.5 * base * height
area = 0.5 * base * height
return area

# Accepting user input for base and height


base_length = float(input("Enter the base length of the triangle: "))
height_length = float(input("Enter the height of the triangle: "))

# Calculating the area of the triangle


triangle_area = calculate_triangle_area(base_length, height_length)

# Displaying the result


print(f"The area of the triangle with base {base_length} and height
{height_length} is: {triangle_area}")
Output:
Enter the base length of the triangle: 10
Enter the height of the triangle: 5
The area of the triangle with base 10.0 and height 5.0 is: 25.0

<!DOCTYPE html>
<html>
<head>
<title>Triangle Area Calculator</title>
</head>
<body bgcolor=yellow>
<h1>Triangle Area Calculator</h1>

<label for="base">Enter Base of the Triangle:</label></br></br>


<input type="number" id="base"></br></br>

<label for="height">Enter Height of the Triangle:</label></br></br>


<input type="number" id="height"></br></br>

<button Area</button>

<p id="result"></p>

<script>
function calculateArea() {
// Get base and height values from user input
var base = parseFloat([Link]('base').value);
var height = parseFloat([Link]('height').value);

// Calculate the area of the triangle


var area = 0.5 * base * height;

// Display the result


[Link]('result').innerText = "The area of the
triangle is: " + area;
}
</script>
</body>
</html>
Output:

# Define two numbers


num1 = 20
num2 = 7

# Addition
addition = num1 + num2
print(f"Addition: {num1} + {num2} = {addition}")

# Subtraction
subtraction = num1 - num2
print(f"Subtraction: {num1} - {num2} = {subtraction}")

# Multiplication
multiplication = num1 * num2
print(f"Multiplication: {num1} * {num2} = {multiplication}")

# Division
division = num1 / num2
print(f"Division: {num1} / {num2} = {division}")

# Modulo (Remainder)
modulo = num1 % num2
print(f"Modulo: {num1} % {num2} = {modulo}")

Output:
Addition: 20 + 7 = 27
Subtraction: 20 - 7 = 13
Multiplication: 20 * 7 = 140
Division: 20 / 7 = 2.857142857142857
Modulo: 20 % 7 = 6
# Function to perform arithmetic operations
def perform_arithmetic_operations(num1, num2):
addition = num1 + num2
subtraction = num1 - num2
multiplication = num1 * num2
division = num1 / num2
modulo = num1 % num2

# Displaying the results


print(f"Addition: {num1} + {num2} = {addition}")
print(f"Subtraction: {num1} - {num2} = {subtraction}")
print(f"Multiplication: {num1} * {num2} = {multiplication}")
print(f"Division: {num1} / {num2} = {division}")
print(f"Modulo: {num1} % {num2} = {modulo}")

# Accepting input from the user


num1 = float(input("Enter the first number: "))
num2 = float(input("Enter the second number: "))

# Calling the function to perform arithmetic operations


perform_arithmetic_operations(num1, num2)

Output:
Enter the first number: 21
Enter the second number: 11
Addition: 21.0 + 11.0 = 32.0
Subtraction: 21.0 - 11.0 = 10.0
Multiplication: 21.0 * 11.0 = 231.0
Division: 21.0 / 11.0 = 1.9090909090909092
Modulo: 21.0 % 11.0 = 10.0

 This program defines a function perform_arithmetic_operations that takes two numbers


as input arguments and performs addition, subtraction, multiplication, division, and
modulo operations on those numbers.
 The user is prompted to input two numbers, which are then used as arguments to the
function to perform arithmetic operations on them.
 The float() function is used to convert the user input into floating-point numbers
for accurate arithmetic calculations.
# Store input numbers:
num1 = input('Enter first number: ')
num2 = input('Enter second number: ')

# Add two numbers


sum = float(num1) + float(num2)

# Subtract two numbers


min = float(num1) - float(num2)

# Multiply two numbers


mul = float(num1) * float(num2)

# Divide two numbers


div = float(num1) / float(num2)

# Display the sum


print('The sum of {0} and {1} is {2}'.format(num1, num2, sum))

# Display the subtraction


print('The subtraction of {0} and {1} is {2}'.format(num1, num2, min))

# Display the multiplication


print('The multiplication of {0} and {1} is {2}'.format(num1, num2, mul))

# Display the division


print('The division of {0} and {1} is {2}'.format(num1, num2, div))

Output:
Enter first number: 20
Enter second number: 10
The sum of 20 and 10 is 30.0
The subtraction of 20 and 10 is 10.0
The multiplication of 20 and 10 is 200.0
The division of 20 and 10 is 2.0
<!DOCTYPE html>
<html>
<head>
<title>Arithmetic Operations</title>
</head>
<body bgcolor= cyan>
<h1>Arithmetic Operations</h1>

<label for="num1">Enter the first number:</label><br/><br/>


<input type="number" id="num1"><br/><br/>

<label for="num2">Enter the second number:</label><br/><br/>


<input type="number" id="num2"><br/><br/>

<button Operations</button>

<div id="results"></div>

<script>
function performOperations()
{
var num1 = parseFloat([Link]('num1').value);
var num2 = parseFloat([Link]('num2').value);

var addition = num1 + num2;


var subtraction = num1 - num2;
var multiplication = num1 * num2;
var division = num1 / num2;
var modulo = num1 % num2;

var results = [Link]('results');


[Link] = "<h3>Arithmetic Operations Results:</h3>" +
"<p>Addition: " + num1 + " + " + num2 + " = " + addition +
"</p>" +
"<p>Subtraction: " + num1 + " - " + num2 + " = " + subtraction
+ "</p>" +
"<p>Multiplication: " + num1 + " * " + num2 + " = " +
multiplication + "</p>" +
"<p>Division: " + num1 + " / " + num2 + " = " + division +
"</p>" +
"<p>Modulo: " + num1 + " % " + num2 + " = " + modulo + "</p>";
}
</script>
</body>
</html>
Output:

# Initial values of two variables


variable1 = 5
variable2 = 10

print("Before swapping:")
print("variable1 =", variable1)
print("variable2 =", variable2)

# Swapping the values using a third variable


temp = variable1
variable1 = variable2
variable2 = temp

print("\nAfter swapping:")
print("variable1 =", variable1)
print("variable2 =", variable2)

Output:
Before swapping:
variable1 = 5
variable2 = 10

After swapping:
variable1 = 10
variable2 = 5
This Python program demonstrates how to swap the values of two variables (variable1 and
variable2). It uses a third variable temp to temporarily hold one of the values during
the swapping process. After the values are interchanged, the new values of the variables
are printed to display the swapping results.
# Accepting input from the user
variable1 = input("Enter the value for variable 1: ")
variable2 = input("Enter the value for variable 2: ")

print("\nBefore swapping:")
print("variable1 =", variable1)
print("variable2 =", variable2)

# Swapping the values without using a third variable


variable1, variable2 = variable2, variable1

print("\nAfter swapping:")
print("variable1 =", variable1)
print("variable2 =", variable2)

Output:
Enter the value for variable 1: 45
Enter the value for variable 2: 90

Before swapping:
variable1 = 45
variable2 = 90

After swapping:
variable1 = 90
variable2 = 45

<!DOCTYPE html>
<html>
<head>
<title>Variable Swapping</title>
</head>
<body bgcolor=orange>
<h1>Variable Swapping</h1>

<label for="variable1">Enter value for variable 1:</label></br></br>


<input type="text" id="variable1"></br></br>

<label for="variable2">Enter value for variable 2:</label></br></br>


<input type="text" id="variable2"></br></br>

<button Variables</button></br></br>

<p>Before Swapping:</p>
<p id="beforeSwap"></p>
<p>After Swapping:</p>
<p id="afterSwap"></p>

<script>
function swapVariables() {
var var1 = [Link]('variable1').value;
var var2 = [Link]('variable2').value;

// Display values before swapping


[Link]('beforeSwap').innerText = "Variable 1: " + var1 + ",
Variable 2: " + var2;

// Swapping the variables using destructuring assignment


[var1, var2] = [var2, var1];

// Display values after swapping


[Link]('afterSwap').innerText = "Variable 1: " + var1 + ",
Variable 2: " + var2;
}
</script>
</body>
</html>

Output:

This HTML file includes a simple form where users can input values for two variables.
Upon clicking the "Swap Variables" button, the swapVariables JavaScript function is
triggered. This function retrieves the values entered by the user and then swaps the
variables using destructuring assignment. The values before and after swapping are
displayed in the HTML elements with the IDs beforeSwap and afterSwap, respectively.
Odd and Even numbers:
If you divide a number by 2 and it gives a remainder of 0 then it is known as even
number, otherwise an odd number.
Even number examples: 2, 4, 6, 8, 10, etc.
Odd number examples: 1, 3, 5, 7, 9 etc.

num = int(input("Enter a number: "))


if (num % 2) == 0:
print("{0} is Even number".format(num))
else:
print("{0} is Odd number".format(num))

Output:
Enter a number: 10
10 is Even number

Enter a number: 11
11 is Odd number

In this program:
 The user is prompted to input a number.
 The program checks if the entered number is divisible by 2 using the modulo operator
(%).
 If the remainder is 0, it prints that the number is even; otherwise, it prints that
the number is odd.

# Function to check if a number is odd or even


def check_odd_even(number):
if number % 2 == 0:
print(f"{number} is an even number.")
else:
print(f"{number} is an odd number.")

# Accepting input from the user


num = int(input("Enter a number: "))

# Calling the function to check odd or even


check_odd_even(num)

Output:
Enter a number: 10
10 is an even number.

Enter a number: 11
11 is an odd number.
In this program:
 The check_odd_even function takes a number as an argument and uses the modulo operator
(%) to check if the number is divisible by 2.
 If the remainder is 0, it prints that the number is even; otherwise, it prints that
the number is odd.
 The user is prompted to input a number, and the program calls the check_odd_even
function to determine and print whether the entered number is odd or even.

<!DOCTYPE html>
<html>
<head><title>Even Odd</title></head>
<body bgcolor="green">
<h1> Program to check number is even or odd </h1>
<script type="text/Javascript">
var a,b;
a=prompt("Enter your value:-");
b=parseInt(a) ;
// input is converted into number data type
if(b%2==0)
alert("Number is even");
else
alert("Number is odd");
</script>
</body>
</html>

Output:

OR
<!DOCTYPE html>
<html>
<head>
<title>Odd or Even Checker</title>
</head>
<body bgcolor=yellow>
<h1>Odd or Even Checker</h1>

<label for="number">Enter a number:</label>


<input type="number" id="number"><br/><br/>

<button Odd/Even</button>

<p id="result"></p>

<script>
function checkOddEven()
{
var num = parseInt([Link]('number').value);

if (num % 2 === 0)
{
[Link]('result').innerText = num + " is an even number.";
}
else
{
[Link]('result').innerText = num + " is an odd number.";
}
}
</script>
</body>
</html>

Output:

Common questions

Powered by AI

In Python, arithmetic operations can be neatly formatted and displayed using f-strings, which allow variables and expressions to be directly embedded in a string, enhancing clarity and conciseness, such as `print(f"Addition: {num1} + {num2} = {addition}")`. In contrast, JavaScript uses string concatenation or template literals for similar results, with expressions placed within backticks (``) and variable interpolation marked by `${}` syntax: `console.log(`Addition: ${num1} + ${num2} = ${addition}`)`. Both techniques provide readable output, but Python f-strings are typically more concise due to fewer syntax requirements .

The Python program for calculating the area of a triangle typically uses the `input()` function to collect user input directly within the console environment, whereas the JavaScript implementation involves HTML elements where users input data through a web interface. In JavaScript, user interaction occurs via forms and event handlers (e.g., `onclick` for buttons), which is suited to dynamic web applications where visual feedback is provided immediately in the browser .

An HTML and JavaScript program calculates the area of a triangle by taking user input for the base and height via HTML input fields. A JavaScript function `calculateArea` is triggered upon clicking a button, which retrieves these input values, computes the area using the formula 0.5 * base * height, and then displays the result within a designated HTML element. This setup demonstrates a simple interaction between user input and computation performed in the browser .

The primary difference between a list and a tuple in Python is that lists are mutable, meaning their elements can be changed after the list is created, while tuples are immutable, meaning once a tuple is created, its elements cannot be modified. This fundamental difference determines how each type can be used in a Python program .

The Python program determines if a number is odd or even by checking if the number, when divided by 2, gives a remainder of 0 using the modulo operator (%). If the remainder is 0, it is an even number; otherwise, it is odd. If the input is 10, the output will be '10 is an even number.' .

The key differences between 'set' and 'list' in Python revolve around order and duplicates. A 'set' is an unordered collection of unique elements, meaning the order of elements is not preserved and duplicates are automatically removed. In contrast, a 'list' is an ordered collection, allowing duplicates and maintaining the order in which elements are added. These differences affect how each is used; 'set' is suited for membership tests and unique collections, whereas 'list' works well with ordered data .

The modulo operator (%) is used to determine if a number is odd or even by checking if there is a remainder when the number is divided by 2. In JavaScript, this is implemented by using `if (num % 2 === 0)` to check evenness: if the condition is true, the number is even; otherwise, it is odd. For example, in an HTML document, a JavaScript function `checkOddEven` can be triggered to perform this check when the user inputs a number and clicks a button .

The JavaScript `parseInt` function assists in handling user input by converting a string input to an integer, which is crucial for performing arithmetic operations. When a user inputs a value through an HTML form, it is usually retrieved as a string. `parseInt` ensures these inputs are converted to numerical values that can be used in calculations like addition or determining if a number is odd or even, ensuring the program operates correctly without type errors .

Two common methods to swap variable values in Python include using a temporary third variable and using tuple unpacking. The first method involves storing one variable's value in a temporary variable before swapping: temp = variable1; variable1 = variable2; variable2 = temp. The second method uses tuple unpacking, which is more concise: `variable1, variable2 = variable2, variable1`. This eliminates the need for a temporary variable and is considered more Pythonic .

An f-string in Python is a string literal prefixed with an 'f' that allows embedded expressions inside curly braces which are replaced with their values. It facilitates easy, readable string formatting and interpolation. For instance, when calculating the area of a triangle, f-strings can be used to format the output, such as: `print(f"The area of the triangle with base {base_length} and height {height_length} is: {triangle_area}")`. This allows the direct embedding of variables and expressions within the string .

You might also like