Python Basic

Programming is the process of creating computer software or applications using a specific programming language. It involves writing code using the language's syntax to create a set of instructions that the computer can execute.

In order to create a computer program, a programmer needs to have a clear understanding of the problem they are trying to solve and how the program should work. This requires analyzing the requirements of the software and designing a solution that will meet those requirements.

The programmer then writes the code using the syntax of the programming language they are working with. This involves using keywords, data types, and syntax rules to create a set of instructions that the computer can understand and execute.

Once the code is written, it needs to be compiled or interpreted to create a machine-readable program that the computer can execute. This involves using a compiler or interpreter to translate the code into machine code, which is a set of instructions that the computer's processor can understand.

Programming is a complex process that requires a great deal of attention to detail and a strong understanding of computer systems and programming languages. It is used to create a wide range of software applications, from simple scripts and command-line tools to complex web applications and video games.

Here are some common phrases used in Python programming:

Variable


Variable: A container used to store data values in Python

In Python, a variable is a container that is used to store data values. The data stored in a variable can be of various types, such as numbers, strings, or objects. Variables are assigned values using the equals sign (=) and can be used throughout a program to represent the data they store.

python
# Assigning a value to a variable
age = 25
# Assigning a string value to a variable
name = "John"
# Assigning the result of a calculation to a variable
result = 5 + 3

# Printing the value of the variable
print(age)

In this example, we have created a variable called "age" and assigned it the value of 25 using the equals sign (=). We have then printed the value of the variable using the "print()" function.

We can also assign strings to variables, like the above example.

Function


Function: A block of code that performs a specific task. It can be called multiple times with different inputs. In Python, a function is a block of code that performs a specific task. Functions can be called multiple times with different inputs, making them a useful tool for modularizing code and making it more reusable.

Here is an example of a simple function in Python:

python
# Defining a function that adds two numbers
def add_numbers(x, y):
result = x + y
return result

# Calling the function with arguments
sum = add_numbers(5, 7)

# Printing the result
print(sum)

In this example, we have defined a function called "add_numbers" that takes two arguments (x and y) and returns their sum. The function first adds the two numbers together and stores the result in a variable called "result". It then returns the value of "result" to the calling code.

We have then called the function with the arguments 5 and 7, and stored the result in a variable called "sum". Finally, we have printed the value of "sum" using the "print()" function.

Functions can also be used to perform more complex tasks, such as manipulating data or interacting with external systems. Here is an example of a function that reads data from a file and returns it as a string:

python
# Defining a function that reads data from a file
def read_file(file_path):
with open(file_path, "r") as file:
data = file.read()
return data

# Calling the function with a file path
file_data = read_file("example.txt")

# Printing the file data
print(file_data)

In this example, we have defined a function called "read_file" that takes a single argument (the path to a file) and returns the contents of the file as a string. The function first opens the file using the "open()" function and reads its contents using the "read()" method. It then returns the contents of the file to the calling code.

We have then called the function with the path to a file called "example.txt", and stored the result in a variable called "file_data". Finally, we have printed the value of "file_data" using the "print()" function

Loop


Loop: A control structure that repeats a block of code until a certain condition is met.

In Python, a loop is a way of repeating a block of code multiple times. There are two types of loops in Python: the "for" loop and the "while" loop.

Here is an example of a "for" loop in Python:

python
# Looping through a list of numbers and printing them
numbers = [1, 2, 3, 4, 5]
for num in numbers:
print(num)

In this example, we have created a list of numbers called "numbers" and used a "for" loop to iterate over each item in the list. The loop assigns the value of each item to the variable "num" and then prints it using the "print()" function.

Here is an example of a "while" loop in Python:

python
# Looping until a condition is met
count = 0
while count < 5:
print("Count is:", count)
count += 1

In this example, we have initialized a variable called "count" to 0 and used a "while" loop to repeat a block of code until the condition "count < 5" is no longer true. The loop prints the current value of "count" using the "print()" function, and then increments it by 1 using the "+=" operator.

Loops can be used to perform a wide variety of tasks, such as iterating over data structures, processing input from a user, or running simulations. They are a powerful tool for automating repetitive tasks and can help make code more concise and easier to read.

Conditional statements


Conditional statements: Used to control the flow of a program based on certain conditions. The two most common types of conditional statements in Python are if and else.In Python, conditional statements allow you to make decisions based on whether a certain condition is true or false. There are two main types of conditional statements in Python: the "if" statement and the "if-else" statement.

Here is an example of an "if" statement in Python:

python
# Checking if a number is greater than 10
num = 15
if num > 10:
print("The number is greater than 10")

In this example, we have defined a variable called "num" and used an "if" statement to check whether its value is greater than 10. If the condition is true, the code inside the "if" block is executed, which prints a message to the console using the "print()" function.

Here is an example of an "if-else" statement in Python:

python
# Checking if a number is positive or negative
num = -5
if num > 0:
print("The number is positive")
else:
print("The number is negative")

In this example, we have defined a variable called "num" and used an "if-else" statement to check whether its value is positive or negative. If the condition in the "if" block is true, the code inside that block is executed, which prints a message to the console saying that the number is positive. If the condition is false, the code inside the "else" block is executed, which prints a message saying that the number is negative.

Conditional statements can be combined using logical operators such as "and" and "or" to create more complex conditions. For example:

python
# Checking if a number is between 10 and 20
num = 15
if num >= 10 and num <= 20:
print("The number is between 10 and 20")
else:
print("The number is not between 10 and 20")

In this example, we have used the logical "and" operator to check whether the value of "num" is between 10 and 20. If the condition is true, the code inside the "if" block is executed, which prints a message to the console saying that the number is between 10 and 20. If the condition is false, the code inside the "else" block is executed, which prints a message saying that the number is not between 10 and 20.

List


List: A collection of values that are ordered and changeable. In Python, a list is a collection of items that can be of different types, such as numbers, strings, or other objects. Lists are mutable, which means that you can modify them by adding, removing, or changing items. Here is an example of how to create and use a list in Python:

python
# Creating a list of numbers
numbers = [1, 2, 3, 4, 5]

# Accessing an item in the list
print(numbers[2]) # Output: 3)

# Modifying an item in the list
numbers[2] = 6

# Adding an item to the end of the list
numbers.append(7)

# Removing an item from the list
numbers.remove(4)

# Looping through the list and printing each item
for num in numbers:
print(num)

In this example, we have created a list of numbers called "numbers" and performed several operations on it. We have accessed an item in the list using its index (which starts at 0), modified an item by assigning a new value to it, added an item to the end of the list using the "append()" method, and removed an item from the list using the "remove()" method. Finally, we have used a "for" loop to iterate over each item in the list and print it to the console.

Lists are a powerful tool for organizing and manipulating data in Python, and they can be used in a wide variety of applications, such as data analysis, machine learning, and web development.

Tuple


Tuple: A collection of values that are ordered and unchangeable. In Python, a tuple is similar to a list, but it is immutable, which means that its items cannot be modified once it is created. Tuples are often used to store related pieces of information that should not be changed, such as the coordinates of a point or the RGB values of a color. Here is an example of how to create and use a tuple in Python:

python
# Creating a tuple of RGB values color = (255, 0, 0) # Accessing an item in the tuple print(color[1]) # Output: 0 # Looping through the tuple and printing each item for value in color: print(value)

In this example, we have created a tuple of RGB values called "color" and performed some operations on it. We have accessed an item in the tuple using its index (which also starts at 0), and we have used a "for" loop to iterate over each item in the tuple and print it to the console.

Although tuples are immutable, you can create a new tuple by concatenating existing tuples or by converting other iterable objects like lists or strings to tuples. Here is an example:

makefile
# Concatenating two tuples tuple1 = (1, 2, 3) tuple2 = (4, 5, 6) new_tuple = tuple1 + tuple2 print(new_tuple) # Output: (1, 2, 3, 4, 5, 6) # Converting a list to a tuple my_list = [1, 2, 3] my_tuple = tuple(my_list) print(my_tuple) # Output: (1, 2, 3)

Tuples can be a useful tool in Python when you need to store data that should not be changed, and they can also help improve the performance of your code in certain situations because they are immutable

Dictionary


Dictionary: A collection of key-value pairs that are unordered, changeable, and indexed. In Python, a dictionary is a collection of key-value pairs that allows you to access, insert, and remove items based on their keys. Dictionaries are often used to represent real-world objects or concepts that have many attributes or properties, such as a person or a car. Here is an example of how to create and use a dictionary in Python:

python
# Creating a dictionary of a person's attributes person = { "name": "John", "age": 30, "gender": "male", "height": 175 } # Accessing a value in the dictionary using its key print(person["age"]) # Output: 30 # Modifying a value in the dictionary using its key person["age"] = 35 # Adding a new key-value pair to the dictionary person["occupation"] = "engineer" # Removing a key-value pair from the dictionary using its key del person["height"] # Looping through the dictionary and printing each key-value pair for key, value in person.items(): print(key + ": " + str(value))

In this example, we have created a dictionary of a person's attributes called "person" and performed several operations on it. We have accessed a value in the dictionary using its key, modified a value by assigning a new value to its key, added a new key-value pair to the dictionary using the square bracket notation, and removed a key-value pair from the dictionary using the "del" keyword. Finally, we have used a "for" loop to iterate over each key-value pair in the dictionary and print them to the console.

Dictionaries are a powerful tool for organizing and manipulating data in Python, and they can be used in a wide variety of applications, such as web development, data analysis, and machine learning.

String


String: A sequence of characters enclosed in quotes, used to represent text in Python. In Python, a string is a sequence of characters that is enclosed in quotation marks (either single quotes or double quotes). Strings are used to represent text or other sequences of characters, such as file paths or URLs. Here is an example of how to create and use a string in Python:

makefile
# Creating a string my_string = "Hello, World!" # Accessing a character in the string using its index print(my_string[1]) # Output: "e" # Slicing the string to extract a substring print(my_string[7:12]) # Output: "World" # Concatenating two strings first_name = "John" last_name = "Doe" full_name = first_name + " " + last_name print(full_name) # Output: "John Doe" # Formatting a string using placeholders age = 30 occupation = "engineer" message = "I am {} years old and work as an {}." print(message.format(age, occupation)) # Output: "I am 30 years old and work as an engineer."

In this example, we have created a string called "my_string" and performed several operations on it. We have accessed a character in the string using its index (which starts at 0), sliced the string to extract a substring using the colon notation, concatenated two strings using the plus operator, and formatted a string using placeholders and the "format" method.

Strings are an essential part of Python programming, and they are used extensively in a wide variety of applications, such as web development, data processing, and natural language processing. Understanding how to manipulate and format strings is a fundamental skill that every Python programmer should have.

Integer


Integer: A whole number in Python. In Python, an integer is a whole number (i.e., a number without any fractional or decimal part) that can be positive, negative, or zero. Integers are used to represent quantities that can be counted or measured, such as the number of items in a list or the height of a building. Here is an example of how to create and use an integer in Python:

python
# Creating an integer my_int = 42 # Performing arithmetic operations on the integer print(my_int + 8) # Output: 50 print(my_int - 18) # Output: 24 print(my_int * 2) # Output: 84 print(my_int / 7) # Output: 6.0 # Converting a string to an integer using the "int" function my_string = "123" my_int2 = int(my_string) print(my_int2) # Output: 123

In this example, we have created an integer called "my_int" and performed several arithmetic operations on it using the plus, minus, multiplication, and division operators. We have also demonstrated how to convert a string to an integer using the built-in "int" function.

Integers are a fundamental data type in Python, and they are used in many different contexts, such as mathematical calculations, data analysis, and programming logic. Understanding how to work with integers and perform arithmetic operations on them is a crucial skill for any Python programmer.

Float


Float: A decimal number in Python. In Python, a float is a number that has a fractional part (i.e., a decimal point followed by one or more digits). Floats are used to represent quantities that can be measured in decimal or fractional units, such as time, distance, or temperature. Here is an example of how to create and use a float in Python:

python
# Creating a float my_float = 3.14159 # Performing arithmetic operations on the float print(my_float + 1.5) # Output: 4.64159 print(my_float - 2.0) # Output: 1.14159 print(my_float * 2) # Output: 6.28318 print(my_float / 2) # Output: 1.570795 # Converting a string to a float using the "float" function my_string = "2.71828" my_float2 = float(my_string) print(my_float2) # Output: 2.71828

In this example, we have created a float called "my_float" and performed several arithmetic operations on it using the plus, minus, multiplication, and division operators. We have also demonstrated how to convert a string to a float using the built-in "float" function.

Floats are an essential data type in Python, and they are used in many different contexts, such as scientific calculations, financial analysis, and data visualization. Understanding how to work with floats and perform arithmetic operations on them is a crucial skill for any Python programmer.

Boolean


Boolean: A value that represents either True or False. In Python, a Boolean is a data type that can have one of two possible values: True or False. Booleans are used to represent logical values and are typically used in programming to make decisions based on the outcome of comparisons or conditions. Here is an example of how to create and use a Boolean in Python:

python
# Creating a Boolean my_bool = True # Performing logical operations on the Boolean print(my_bool and False) # Output: False print(my_bool or False) # Output: True print(not my_bool) # Output: False # Comparing two values to create a Boolean x = 10 y = 5 result = x > y print(result) # Output: True

In this example, we have created a Boolean called "my_bool" with a value of True and performed several logical operations on it using the and, or, and not operators. We have also demonstrated how to create a Boolean by comparing two values using the greater than operator (>).

Booleans are an essential data type in Python, and they are used extensively in programming logic and decision-making. Understanding how to work with Booleans and perform logical operations on them is a crucial skill for any Python programmer.

Popular posts from this blog

Class & Function

Series & Dataframe