Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Tuples #556

Open
wants to merge 8 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from 7 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
189 changes: 65 additions & 124 deletions 03_Day_Operators/day-3.py
Original file line number Diff line number Diff line change
@@ -1,124 +1,65 @@
# Arithmetic Operations in Python
# Integers

print('Addition: ', 1 + 2)
print('Subtraction: ', 2 - 1)
print('Multiplication: ', 2 * 3)
print ('Division: ', 4 / 2) # Division in python gives floating number
print('Division: ', 6 / 2)
print('Division: ', 7 / 2)
print('Division without the remainder: ', 7 // 2) # gives without the floating number or without the remaining
print('Modulus: ', 3 % 2) # Gives the remainder
print ('Division without the remainder: ', 7 // 3)
print('Exponential: ', 3 ** 2) # it means 3 * 3

# Floating numbers
print('Floating Number,PI', 3.14)
print('Floating Number, gravity', 9.81)

# Complex numbers
print('Complex number: ', 1 + 1j)
print('Multiplying complex number: ',(1 + 1j) * (1-1j))

# Declaring the variable at the top first

a = 3 # a is a variable name and 3 is an integer data type
b = 2 # b is a variable name and 3 is an integer data type

# Arithmetic operations and assigning the result to a variable
total = a + b
diff = a - b
product = a * b
division = a / b
remainder = a % b
floor_division = a // b
exponential = a ** b

# I should have used sum instead of total but sum is a built-in function try to avoid overriding builtin functions
print(total) # if you don't label your print with some string, you never know from where is the result is coming
print('a + b = ', total)
print('a - b = ', diff)
print('a * b = ', product)
print('a / b = ', division)
print('a % b = ', remainder)
print('a // b = ', floor_division)
print('a ** b = ', exponential)

# Declaring values and organizing them together
num_one = 3
num_two = 4

# Arithmetic operations
total = num_one + num_two
diff = num_two - num_one
product = num_one * num_two
div = num_two / num_two
remainder = num_two % num_one

# Printing values with label
print('total: ', total)
print('difference: ', diff)
print('product: ', product)
print('division: ', div)
print('remainder: ', remainder)


# Calculating area of a circle
radius = 10 # radius of a circle
area_of_circle = 3.14 * radius ** 2 # two * sign means exponent or power
print('Area of a circle:', area_of_circle)

# Calculating area of a rectangle
length = 10
width = 20
area_of_rectangle = length * width
print('Area of rectangle:', area_of_rectangle)

# Calculating a weight of an object
mass = 75
gravity = 9.81
weight = mass * gravity
print(weight, 'N')

print(3 > 2) # True, because 3 is greater than 2
print(3 >= 2) # True, because 3 is greater than 2
print(3 < 2) # False, because 3 is greater than 2
print(2 < 3) # True, because 2 is less than 3
print(2 <= 3) # True, because 2 is less than 3
print(3 == 2) # False, because 3 is not equal to 2
print(3 != 2) # True, because 3 is not equal to 2
print(len('mango') == len('avocado')) # False
print(len('mango') != len('avocado')) # True
print(len('mango') < len('avocado')) # True
print(len('milk') != len('meat')) # False
print(len('milk') == len('meat')) # True
print(len('tomato') == len('potato')) # True
print(len('python') > len('dragon')) # False

# Boolean comparison
print('True == True: ', True == True)
print('True == False: ', True == False)
print('False == False:', False == False)
print('True and True: ', True and True)
print('True or False:', True or False)

# Another way comparison
print('1 is 1', 1 is 1) # True - because the data values are the same
print('1 is not 2', 1 is not 2) # True - because 1 is not 2
print('A in Asabeneh', 'A' in 'Asabeneh') # True - A found in the string
print('B in Asabeneh', 'B' in 'Asabeneh') # False -there is no uppercase B
print('coding' in 'coding for all') # True - because coding for all has the word coding
print('a in an:', 'a' in 'an') # True
print('4 is 2 ** 2:', 4 is 2 ** 2) # True

print(3 > 2 and 4 > 3) # True - because both statements are true
print(3 > 2 and 4 < 3) # False - because the second statement is false
print(3 < 2 and 4 < 3) # False - because both statements are false
print(3 > 2 or 4 > 3) # True - because both statements are true
print(3 > 2 or 4 < 3) # True - because one of the statement is true
print(3 < 2 or 4 < 3) # False - because both statements are false
print(not 3 > 2) # False - because 3 > 2 is true, then not True gives False
print(not True) # False - Negation, the not operator turns true to false
print(not False) # True
print(not not True) # True
print(not not False) # False
# Basic arithmetic operations
print('Addition:', 5 + 3) # Outputs: Addition: 8
print('Subtraction:', 10 - 7) # Outputs: Subtraction: 3
print('Multiplication:', 4 * 6) # Outputs: Multiplication: 24

# Division
print('Division:', 15 / 4) # Outputs: Division: 3.75

# Integer Division
print('Integer Division:', 15 // 4) # Outputs: Integer Division: 3

# Modulus (Remainder)
print('Modulus:', 15 % 4) # Outputs: Modulus: 3

# Exponentiation
print('Exponential:', 2 ** 5) # Outputs: Exponential: 32
# Floating point arithmetic
print('Floating Point Division:', 17.5 / 2.5) # Outputs: Floating Point Division: 7.0

# Mixed operations
result = 2.5 * 3 + 7 / 2 - 1
print('Mixed Operations:', result) # Outputs: Mixed Operations: 9.5
# Variable assignments and reassignments
x = 5
y = 3
z = x + y
print('Value of z:', z) # Outputs: Value of z: 8

# Increment and decrement
counter = 0
counter += 1 # Increment
print('Counter:', counter) # Outputs: Counter: 1

counter -= 1 # Decrement
print('Counter:', counter) # Outputs: Counter: 0
# Calculating area of a triangle
base = 6
height = 4
area_of_triangle = 0.5 * base * height
print('Area of triangle:', area_of_triangle) # Outputs: Area of triangle: 12.0

# Calculating volume of a cube
side_length = 10
volume_of_cube = side_length ** 3
print('Volume of cube:', volume_of_cube) # Outputs: Volume of cube: 1000
# Boolean expressions
print('True and False:', True and False) # Outputs: True and False: False
print('True or False:', True or False) # Outputs: True or False: True
print('Not True:', not True) # Outputs: Not True: False

# Comparison operators
print('Greater than:', 5 > 3) # Outputs: Greater than: True
print('Less than or equal to:', 7 <= 7) # Outputs: Less than or equal to: True
print('Not equal to:', 10 != 12) # Outputs: Not equal to: True
# Membership operators
print('Substring in string:', 'python' in 'python programming') # Outputs: Substring in string: True
print('Character not in string:', 'a' not in 'hello') # Outputs: Character not in string: True

# Identity operators
a = 5
b = a
print('Identity:', a is b) # Outputs: Identity: True

c = 10
print('Identity:', a is not c) # Outputs: Identity: True
177 changes: 177 additions & 0 deletions 06_Day_Tuples/Tuples_Example
Original file line number Diff line number Diff line change
@@ -0,0 +1,177 @@
In Python, a tuple is an ordered collection of items, which is immutable and enclosed within parentheses `()`.
Tuples are similar to lists but cannot be modified once created, meaning you cannot add, remove, or modify elements after creation. Here's a breakdown of tuples in Python:

### Syntax:
```python
my_tuple = (item1, item2, item3, ...)
```
- **Note**: The parentheses `()` are optional in tuple creation but often used for clarity.

### Example:
```python
# Creating tuples
tuple1 = (1, 2, 3, 4, 5)
tuple2 = ('apple', 'banana', 'cherry')
tuple3 = (1, 'hello', 3.14, True)
```

### Types of Access:
1. **Indexing**: Access individual items by their position, similar to lists.
```python
print(tuple1[0]) # Output: 1
print(tuple2[2]) # Output: 'cherry'
```

2. **Slicing**: Extract a portion of the tuple.
```python
print(tuple1[1:4]) # Output: (2, 3, 4)
print(tuple3[:2]) # Output: (1, 'hello')
```

### Examples:

#### Immutable Nature:
```python
tuple1[0] = 10 # Raises TypeError: 'tuple' object does not support item assignment
```
Tuples cannot be changed after creation, making them suitable for storing data that should not be modified accidentally.

#### Tuple Packing and Unpacking:
```python
# Packing multiple values into a tuple
my_tuple = 1, 2, 'hello'
print(my_tuple) # Output: (1, 2, 'hello')

# Unpacking a tuple into variables
a, b, c = my_tuple
print(a) # Output: 1
print(b) # Output: 2
print(c) # Output: 'hello'
```

#### Tuple with Single Element:
```python
single_element_tuple = (1,)
print(single_element_tuple) # Output: (1,)
```
A trailing comma distinguishes a tuple with a single element from an expression in parentheses.

### Use Cases:
- **Returning Multiple Values**: Functions can return tuples to convey multiple pieces of information.
- **Immutable Keys in Dictionaries**: Tuples can serve as dictionary keys because they are immutable.
- **Efficient Iteration**: Tuples are faster than lists when iterating through data that doesn’t change.

### Conclusion:
Tuples provide a way to store and access data in Python, emphasizing immutability and order. While less flexible than lists, they are useful for situations where you want to ensure data integrity or use hashable types as keys in dictionaries.





-------------------------------------------------------------------------------------------------------------------------------------
Advanced Tuples

Certainly! Here are more examples demonstrating various aspects and uses of tuples in Python:

### 1. Returning Multiple Values from a Function:
Tuples are often used to return multiple values from a function efficiently.

```python
def get_circle_properties(radius):
circumference = 2 * 3.14 * radius
area = 3.14 * radius * radius
return circumference, area

radius = 5
circle_info = get_circle_properties(radius)
print(circle_info) # Output: (31.400000000000002, 78.5)

# Unpacking the returned tuple
circumference, area = circle_info
print(f"Circumference: {circumference}, Area: {area}")
# Output: Circumference: 31.400000000000002, Area: 78.5
```

### 2. Iterating through a Tuple:
You can iterate over the elements of a tuple using a for loop.

```python
my_tuple = ('a', 'b', 'c', 'd', 'e')

for item in my_tuple:
print(item)

# Output:
# a
# b
# c
# d
# e
```

### 3. Tuple Concatenation and Repetition:
You can concatenate tuples using the `+` operator and repeat tuples using the `*` operator.

```python
tuple1 = (1, 2, 3)
tuple2 = ('a', 'b', 'c')

concatenated_tuple = tuple1 + tuple2
print(concatenated_tuple) # Output: (1, 2, 3, 'a', 'b', 'c')

repeated_tuple = tuple1 * 3
print(repeated_tuple) # Output: (1, 2, 3, 1, 2, 3, 1, 2, 3)
```

### 4. Using Tuples as Dictionary Keys:
Since tuples are immutable and hashable, they can be used as keys in dictionaries.

```python
location = (25.1234, 45.6789)
weather_data = {
location: 'Sunny',
(37.7749, -122.4194): 'Cloudy',
(40.7128, -74.0060): 'Rainy'
}

print(weather_data[location]) # Output: Sunny
```

### 5. Tuple Comprehension (Python 3.9+):
Although tuples themselves do not support comprehension like lists do, you can create a tuple using a generator expression inside parentheses.

```python
tuple_from_generator = tuple(x for x in range(5))
print(tuple_from_generator) # Output: (0, 1, 2, 3, 4)
```

### 6. Named Tuples (collections.namedtuple):
Named tuples are a subclass of tuples that allow accessing fields by name as well as by index.

```python
from collections import namedtuple

# Declaring a named tuple type 'Point' with fields 'x' and 'y'
Point = namedtuple('Point', ['x', 'y'])

# Creating instances of named tuple
p1 = Point(10, 20)
p2 = Point(30, 40)

print(p1.x, p1.y) # Output: 10 20
print(p2.x, p2.y) # Output: 30 40
```

### 7. Tuple as Function Arguments:
Tuples are often used to pass a fixed collection of arguments to a function.

```python
def print_person_info(name, age, city):
print(f"Name: {name}, Age: {age}, City: {city}")

person_info = ('Alice', 30, 'New York')
print_person_info(*person_info)
# Output: Name: Alice, Age: 30, City: New York
```

These examples illustrate various practical uses and capabilities of tuples in Python, highlighting their immutability, efficient packing and unpacking, and suitability for scenarios requiring ordered, immutable collections of data.
Loading