Skip to content

Latest commit

 

History

History
590 lines (412 loc) · 7.78 KB

README.md

File metadata and controls

590 lines (412 loc) · 7.78 KB

Chapter 3: Data Types and Operators

Table of Contents

Basic Data Types

Python supports several basic data types, including integers, floats, strings, and booleans.

Integer (int)

Integers are whole numbers without a decimal point.

x = 50
print(x)
print(type(x))

Output:

50
<class 'int'>

Float (float)

Floats are numbers with a decimal point.

decimal_number = -5.000005
print(decimal_number)
print(type(decimal_number))

Output:

-5.000005
<class 'float'>

String (str)

Strings are sequences of characters enclosed in quotes.

word = "Python"
print(word)
print(type(word))

Output:

Python
<class 'str'>

Boolean (bool)

Booleans represent one of two values: True or False.

b = True
print(b)
print(type(b))

b = False
print(b)
print(type(b))

Output:

True
<class 'bool'>
False
<class 'bool'>

Mathematical Operators

Python provides various mathematical operators for arithmetic operations.

Assignment Operator

The assignment operator = is used to assign a value to a variable.

x = 10
print(x)

Output:

10

Addition Operator

The addition operator + adds two numbers.

a = 3 + 5
print(a)

Output:

8

Subtraction Operator

The subtraction operator - subtracts one number from another.

a = 10 - 5
print(a)

Output:

5

Multiplication Operator

The multiplication operator * multiplies two numbers.

a = 5 * 6
print(a)

Output:

30

Division Operator

The division operator / divides one number by another.

a = 10 / 4
print(a)

Output:

2.5

Floor Division Operator

The floor division operator // divides one number by another and returns the largest integer less than or equal to the result.

a = 10 // 4
print(a)

Output:

2

Modulus Operator

The modulus operator % returns the remainder of the division of one number by another.

a = 10 % 4
print(a)

Output:

2

Exponentiation Operator

The exponentiation operator ** raises one number to the power of another.

a = 5 ** 3
print(a)

Output:

125

String Data Type

Strings in Python can be manipulated in various ways.

Basic String Operations

word = 'Python'
print(word)

Output:

Python

Multi-line Strings

You can use triple quotes to create multi-line strings.

text = """
Python

1) Python is an interesting programming language.
2) It is a simple language.
"""
print(text)

Output:

Python

1) Python is an interesting programming language.
2) It is a simple language.

String Length

You can use the len() function to get the length of a string.

country = "Azerbaijan"
print(len(country))

Output:

9

String Slicing

You can slice strings to get a substring.

s = "Hello, Python!"
print(s[7:13])

Output:

Python

String Methods

Python provides various string methods for manipulation.

s = "Hello, Python!"
print(s.upper())       # Convert to uppercase
print(s.lower())       # Convert to lowercase
print(s.strip())       # Remove whitespace
print(s.replace("n","z"))  # Replace characters
print(s.capitalize())  # Capitalize the first letter
print(s.count("on"))   # Count occurrences
print(s.find("on"))    # Find substring
print(s.isdigit())     # Check if all characters are digits
print(s.isalpha())     # Check if all characters are alphabetic

Output:

HELLO, PYTHON!
hello, python!
Hello, Python!
Hello, Pythoz!
Hello, python!
2
9
False
False

Basic Type Conversions

You can convert between different data types using built-in functions.

Convert to Integer

a = int(1.15)  # From float
print(a, type(a))

a = int("100")  # From string
print(a, type(a))

Output:

1 <class 'int'>
100 <class 'int'>

Convert to Float

a = float(10)  # From integer
print(a, type(a))

a = float("10.5")  # From string
print(a, type(a))

Output:

10.0 <class 'float'>
10.5 <class 'float'>

Convert to String

a = str(12)  # From integer
print(a, type(a))

a = str(10.05)  # From float
print(a, type(a))

Output:

12 <class 'str'>
10.05 <class 'str'>

User Input

You can get input from the user using the input() function.

Basic Input

name = input("Enter your name: ")
print(f"Hello, {name}")

Output:

Enter your name: John
Hello, John

Input with Type Conversion

number = int(input("Enter a number: "))
print(number ** 2)

Output:

Enter a number: 4
16

List Data Type

Lists are used to store multiple items in a single variable.

Basic List Operations

fruits = ["Apple", "Quince", "Pomegranate", "Pear", "Orange"]
print(fruits)

Output:

['Apple', 'Quince', 'Pomegranate', 'Pear', 'Orange']

Adding Items

fruits.append("Kiwi")
print(fruits)

Output:

['Apple', 'Quince', 'Pomegranate', 'Pear', 'Orange', 'Kiwi']

Inserting Items

fruits.insert(3, "New Element")
print(fruits)

Output:

['Apple', 'Quince', 'Pomegranate', 'New Element', 'Pear', 'Orange', 'Kiwi']

Removing Items

fruits.remove("Orange")
print(fruits)

Output:

['Apple', 'Quince', 'Pomegranate', 'New Element', 'Pear', 'Kiwi']

Popping Items

fruits.pop(2)
print(fruits)

Output:

['Apple', 'Quince', 'New Element', 'Pear', 'Kiwi']

Sorting Items

fruits.sort()
print(fruits)

Output:

['Apple', 'Kiwi', 'New Element', 'Pear', 'Quince']

2D List

2D lists (matrices) are lists of lists.

matrix = [
    [1, 2, 3],
    [4, 5, 6],
    [7, 8, 9]
]
print(matrix[2][2])

Output:

9

Tuple Data Type

Tuples are immutable sequences of items.

programming_languages = ("Python", "Java", "C++", "Javascript", "TypeScript")
print(programming_languages[1:3])

Output:

('Java', 'C++')

Set Data Type

Sets are unordered collections of unique items.

s = {10, 100, 5, 3, 4, 9}
print(s)

s.add("Python")
print(s)

s.remove(5)
print(s)

s.discard(90)
print(s)

s.clear()
print(s)

Output:

{3, 4, 5, 100, 9, 10}
{3, 4, 5, 100, 9, 10, 'Python'}
{3, 4, 100, 9, 10, 'Python'}
{3, 4, 100, 9, 10, 'Python'}
set()

Dictionary Data Type

Dictionaries store data in key-value pairs.

person = {
    "name": "Ahmed",
    "surname": "Ahmedov",
    "birthdate": "01.01.2001"
}
print(person.get("name"))
print(person.keys())
print(person.items())

Output:

Ahmed
dict_keys(['name', 'surname', 'birthdate'])
dict_items([('name', 'Ahmed'), ('surname', 'Ahmedov'), ('birthdate', '01.01.2001')])

Summary

In this chapter, we covered basic data types, mathematical operators, string manipulations, type conversions, user input, and various data structures like lists, tuples, sets, and dictionaries.

Tasks

  1. Write a program that takes two numbers from the user and prints their sum, difference, product, and quotient.
  2. Create a list of your favorite fruits and perform various list operations like adding, removing, and sorting items.
  3. Create a dictionary to store information about a person (name, age, city) and print each piece of information.

Next Chapter: Control Flow and Conditionals