Python programming Codes-Part_1
Tags: python, beginners, tutorial
Published: 2023-09-14 12:35:58

Hi Dev Community 😊 👩‍💻👨‍💻

I'm posting here some codes to help you start you Python journey, I hope they can be useful for you.

English is my second language, I apologize if I have made anywhere writing mistakes 😅

- Basic Syntax

```
# Print "Hello, world!" to the console
print("Hello, world!")

# Declare and assign a variable
my_variable = 10

# Conditional statement
if my_variable > 5:
    print("my_variable is greater than 5")
else:
    print("my_variable is less than or equal to 5")

# Loop through a list
my_list = [1, 2, 3, 4, 5]
for item in my_list:
    print(item)

# Define a function
def my_function(param1, param2):
    return param1 + param2

# Call a function
result = my_function(2, 3)
print(result)
```

- Data types and structures

```
# Integer
my_int = 10

# Float
my_float = 3.14

# String
my_string = "Hello, world!"

# Boolean
my_bool = True

# List
my_list = [1, 2, 3, 4, 5]

# Tuple
my_tuple = (1, 2, 3)

# Set
my_set = {1, 2, 3}

# Dictionary
my_dict = {"name": "John", "age": 30, "city": "New York"}
```
-File handling 

```
# Open a file
file = open("file.txt", "w")

# Write to a file
file.write("Hello, world!")

# Close a file
file.close()

# Open a file for reading
file = open("file.txt", "r")

# Read from a file
contents = file.read()

# Close a file
file.close()
```
-Libraries and modules 

```
# Import a module
import math

# Use a function from a module
result = math.sqrt(16)
print(result)

# Import a specific function from a module
from random import randint

# Use the imported function
random_number = randint(1, 10)
print(random_number)

# Import a custom module
import my_module

# Use a function from the custom module
result = my_module.my_function(2, 3)
print(result)
```
-List Operations

```
# Create a list
my_list = [1, 2, 3, 4, 5]

# Append to a list
my_list.append(6) = ("new_element")

# Remove from a list
my_list.remove(3)

# Get the length of a list
length = len(my_list)

# Sort a list
my_list.sort()

# Reverse a list
my_list.reverse()

# Sort a list in alphabetic reserve order
my_list.sort(reverse="True")

# Extend the list with another list
my_list.extend(["element","element1"])

```
-List Comprehension

```
# Create a new list using list comprehension
my_list = [1, 2, 3, 4, 5]
new_list = [x * 2 for x in my_list]
print(new_list)

# Create a new list with condition using list comprehension
my_list = [1, 2, 3, 4, 5]
new_list = [x for x in my_list if x % 2 == 0]
print(new_list)
```
-Tuples Operations

```
# Creating a tuple
my_tuple = (1, 2, 3, 4, 5)

# Creating a single-element tuple (note the comma)
single_element_tuple = (42,)

# Creating an empty tuple
empty_tuple = ()
```
-Accessing elements in tuples

```
# Accessing elements by index
first_element = my_tuple[0]
last_element = my_tuple[-1]

# Slicing a tuple
subset_tuple = my_tuple[1:4]

# Tuple unpacking
a, b, c, d, e = my_tuple
```
-Iterating trough a tuple

```
for item in my_tuple:
    print(item)

# Using enumerate to access both index and value
for index, value in enumerate(my_tuple):
    print(f"Index {index}: {value}")
```
-Checking "membership"

```
# Checking if an element exists in a tuple
if 3 in my_tuple:
    print("3 is in the tuple")
```
-Tuples immutability

Trying/attempting to modify a tuple will result in a error

```
my_tuple[0] = 10  # Raises a TypeError: 'tuple' object does not support item assignment
```
-Soo how to "add elements" to it? You can concatenate 2 tuples into 1 

```
# Concatenating two tuples
tuple1 = (1, 2, 3)
tuple2 = (4, 5, 6)
concatenated_tuple = tuple1 + tuple2

# Repeating a tuple
repeated_tuple = (0,) * 3  # Creates (0, 0, 0)
```
-Dictionary Operations

```
# Create a dictionary
my_dict = {"name": "John", "age": 30, "city": "New York"}

# Access a value in a dictionary
name = my_dict["name"]

# Add a new key-value pair to a dictionary
my_dict["country"] = "USA"

# Remove a key-value pair from a dictionary
del my_dict["age"]

# Check if a key exists in a dictionary
if "name" in my_dict:
    print("Name exists in the dictionary")

# Get the keys and values of a dictionary as lists
keys = list(my_dict.keys())
values = list(my_dict.values())
```
-Classes Operations

```
# Define a class
class Person:
    def __init__(self, name, age):
        self.name = name
        self.age = age

    def say_hello(self):
        print(f"Hello, my name is {self.name} and I am {self.age} years old.")

# Create an object of a class
person1 = Person("John", 30)

# Call a method of an object
person1.say_hello()
```
-Sets operations

Sets are unordered,unique and mutable collections but they don't repeat elements, if you want to convert a list into a set and there are 2 elements repeated like: my_list={"computer","mouse","mouse-pad","keyboard","mouse-pad"}, when printing set(my_list) it only has mouse-pad 1 time because of the propriety of uniqueness (don't allow duplicate elements).

```
# Creating a set
my_set = {1, 2, 3}

# Adding elements to a set
my_set.add(4)

# Removing an element from a set
my_set.remove(2)

# Checking if an element is in a set
if 3 in my_set:
    print("3 is in the set")

# Iterating through a set
for item in my_set:
    print(item)

# Set operations
set1 = {1, 2, 3}
set2 = {3, 4, 5}

# Union of two sets
union_set = set1.union(set2)

# Intersection of two sets
intersection_set = set1.intersection(set2)

# Difference between two sets
difference_set = set1.difference(set2)

# Symmetric difference between two sets
symmetric_difference_set = set1.symmetric_difference(set2)
```

Stay tuned for part_2 🥰