Explanation
Variables
In programming, a variable is a named storage location that holds a value. It’s like a labeled box where you can put things (data) for later use. In Python, variables play a crucial role in working with data and manipulating it. Here are some key points to understand about variables in Python:
name and Name are treated as different variables.
=. For example: age = 25 assigns the value 25 to the variable age.
(int), floating-point numbers (float), strings (str), and more complex types like lists (list), dictionaries (dict), tuples (tuple), and sets (set).
Dynamic Typing: Unlike some other programming languages, Python is dynamically typed. This means that you don’t need to declare the data type of a variable explicitly; Python figures it out based on the assigned value.
age = 26 changes the value of the age variable.
print() function. For example: print(age) will output the value stored in the age variable.
Variable Scope: Variables have a scope, which defines where the variable is accessible and where it is not. Variables defined inside a function have a local scope and are only accessible within that function. Variables defined outside any function have a global scope and can be accessed from anywhere in the program.
total_students instead of ts makes the code more readable.
name = "Alice"
age = 30
height = 5.7
is_student = True
print("Name:", name)
print("Age:", age)
print("Height:", height)
print("Is Student:", is_student)
In this example, we declare variables to store a name, an age, a height, and a student status. Then, we print out their values using the print() function.
Numeric Variables
Integer: A number consisting of negative, 0, and positive numbers.
ex) 33, -44, -3, 0, 7, 88, 38378, etc.
Floating Point: Number with decimal point.
ex) -333.44, -38.333, 0.0, 3.14, 3663.373, etc.
String Variables
Consists of one or more letters.
The string is wrapped around the string with single quotation marks (‘) or double quotation marks (“).
ex) ‘ga’, ‘gadana’, ‘a’, ‘b’, ‘abc’, ‘I am happy!’, '2020/10/20', ‘010-1234-5678', “apple”
List Data Type
Set of strings.
Composed of multiple numbers, strings, etc.
Use the ‘[]’’ symbol
ex) List name = [Element1, Element2, … ]
Odd number from 1 to 10
ex) odd = [1, 3, 5, 7, 9]
list indexing
starts from 0
ex) odd[0] = 1, odd[1] = 3, … , odd[4] = 9
Can proceed in reverse direction
ex) odd[-1] = 9, odd[-2] = 7, … , odd[-5] = 1
List slicing
Select part of the list separately
List name[start:end]
ex)
odd[0:2] = [1, 3]
odd[1:2] = [3]
odd[1:3] = [3, 5]
odd[0:2] = [1, 3]
odd[0:5] = [1, 3, 5, 7, 9]
odd[:5] = [1, 3, 5, 7, 9]
odd[0:5] = [1, 3, 5, 7, 9]
Tuple Data Type
Set of strings.
Use the ‘()’ symbol.
ex) Tuple name = (element1, element2, …)
Differences from lists
List: Values can be created, deleted, and modified.
Tuple: Creation, deletion, or modification of values is not possible.
Dictionary Data Type
Dictionary literally means ‘dictionary’.
For example, just as the word “people” matches the meaning of “person” and the word “baseball” matches the meaning of “baseball”.
A dictionary is a data type that has a pair of Key and Value.
If the Key is “baseball”, the Value will be “baseball”.
A dictionary does not obtain the value of its elements sequentially like a list or tuple, but obtains the value through the key. This is the biggest feature of the dictionary.
Instead of sequentially searching through the contents of the dictionary to find the meaning of the word baseball,
All you have to do is look at the places where the word baseball appears.
Set Data Type
A set is a data type created to easily process things related to sets.
Obviously, a set data type was created with the “Hello” string, but the created data type is missing one l character and the order is mixed. The reason is that sets have the following two characteristics.
Duplication is not allowed.
Unordered.
Bool Data Type
The bool data type is a data type that represents True and False.
The Boolean data type can have only two values.
True
False
Control Statements
Control statements are essential for controlling the flow of a program. They allow you to make decisions, repeat actions, and create structured logic in your code. In Python, control statements come in the form of conditional statements (if, elif, else), loops (for and while), and branching mechanisms.
Here’s an explanation of control statements with examples:
if statement, which checks a condition and executes a block of code if the condition is true. The elif and else branches allow for more complex decision-making.
temperature = 25
if temperature > 30:
print("It's hot outside.")
elif temperature > 20:
print("The weather is pleasant.")
else:
print("It's a bit chilly.")
for loop iterates through a sequence (like a list) and performs the specified actions for each element. The while loop continues as long as a specified condition is true.
fruits = ["apple", "banana", "orange"]
for fruit in fruits:
print(fruit)
count = 0
while count < 5:
print("Count:", count)
count += 1
3. Break and Continue: The break statement is used to exit a loop prematurely, even if the loop condition is still true. The continue statement is used to skip the remaining code inside the current iteration and move to the next one.
for number in range(10):
if number == 5:
break
print(number)
for num in range(10):
if num % 2 == 0:
continue
print(num)
4. Nested Loops: You can have loops inside other loops, creating nested loops. This is useful for handling more complex patterns or situations that require multiple levels of iteration.
for i in range(3):
for j in range(2):
print(i, j)
Control statements are fundamental to programming because they allow you to add logic and decision-making to your code, enabling it to respond dynamically to different situations.
if Statement
if conditional statement:
Executes subcode to determine true/false for a condition.
Configuration example:
if (condition): (statement to be executed)
In case of complex conditions, use and, or.
Configuration example:
if (condition 1) and (condition 2): (statement to be executed)
Use not when verifying ‘if the condition is false’
Configuration example:
rich = False if not rich: print("It's time to go to work…")
elif conditional statement:
If a condition does not correspond to the condition of the if statement, the condition is given again to determine whether it is true or false and the subcode is executed.
Configuration example:
if (conditiona): (statement to be executed) elif (condition b): (statement to be executed)
else conditional statement:
If any condition does not correspond to the condition of the if statement or the condition of the elif statement, the subcode is executed.
Configuration example:
if (conditiona): (statement to be executed) else: (statement to be executed)
while Statement
while statement:
Determine whether a condition is true or false and repeat the subcode infinitely.
Configuration example
while (condition): (statement to be executed)
while True: and while(1): have the same condition.
break statement:
Used to break and escape while statement.
continue statement:
Used to return to the beginning of a while statement.
for Statement
for statement:
Subcode is repeated and executed as many times as a specific condition.
Configuration example:
for (variable) in (list, tuple, string): (statement to be executed)
range function:
Often used with a For statement.
Create a list of a specific range.
Configuration example:
range(10) = range(0,10) = range(0, 10, 1) = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] range(1,10) = [1, 2, 3, … , 7, 8, 9] range(0, 10, 2) = [0, 2, 4, 6, 8]
Functions and Classes
Functions and classes are fundamental concepts in programming that help you organize and structure your code for better readability, reusability, and modularity.
Here’s an explanation of functions and classes with examples:
1. Functions: A function is a block of code that performs a specific task. It takes input, processes it, and produces an output. Functions help avoid code repetition and make your code more manageable.
def greet(name):
return f"Hello, {name}!"
message = greet("Alice")
print(message)
2. Functions with Default Parameters: Functions can have default parameter values, which are used when an argument is not provided during the function call.
def add_numbers(a, b=0):
return a + b
result1 = add_numbers(5, 3)
result2 = add_numbers(7)
print("Result 1:", result1)
print("Result 2:", result2)
3. Classes: A class is a blueprint for creating objects that have attributes (variables) and methods (functions). It allows you to model real-world entities in your code.
class Rectangle:
def __init__(self, width, height):
self.width = width
self.height = height
def calculate_area(self):
return self.width * self.height
rect1 = Rectangle(10, 5)
rect2 = Rectangle(8, 6)
area1 = rect1.calculate_area()
area2 = rect2.calculate_area()
print("Area 1:", area1)
print("Area 2:", area2)
In this example, we define a Rectangle class with an __init__ constructor method to initialize width and height attributes. The calculate_area() method calculates and returns the area of the rectangle. We create objects of the class and call the methods to calculate and print their areas.
Functions and classes are building blocks that allow you to create more organized, reusable, and maintainable code. They are essential for implementing complex logic and creating custom data types in your programs.
Functions
Used to perform a specific task with input values and then output them.
Configuration example:
def function name (input): statement to execute return result value
When there is no input value, when there is no result value.
When there are multiple input and result values or none.
When you need to set an initial value for the input value.
When designating a global variable to maintain the result value (global variable name).
Can be used in various situations such as.
Classes
Used to create objects and encapsulate them or increase data reusability.
A big blueprint-like concept for creating objects.
Provides a way to structure and organize your code by allowing you to create objects with shared properties and behavior.
instance:
An object that belongs to the object and is specifically implemented.
A specific entity created based on a blueprint defined in a class.
Configuration example:
class Class name: … Detailed features… Instance name = class name ()