Python Course: while statement

Python Course: while Statement

In Python, there are mainly two ways to create loops: the for statement and the while statement. In this course, we will learn in detail how the while statement works and how to use it. The while statement allows the block of code to be executed as long as the given condition is True.

Basic Structure of the while Statement

The basic syntax of the while statement is as follows:

while condition:
    block of code to execute
    (usually includes code that makes the condition false)

In simple terms, for the while statement, the block of code below is repeatedly executed every time the condition is true. And when the condition becomes false, the loop ends. Now let’s look at a simple example of a while statement.

Basic Example

Let’s examine how the while statement works through an example. Here, we will look at a simple example that prints the numbers from 1 to 5.

i = 1
while i <= 5:
    print(i)
    i += 1

In this example, the initial variable i is set to 1. The while statement continues executing the loop as long as the condition i <= 5 is true. Inside the loop, it prints the value of i and adds 1 to i. Eventually, when i becomes 6, the condition evaluates to false, and the loop ends.

Infinite Loop

If the condition is always true, the while statement can enter an infinite loop. This means that the program will keep running without stopping. Infinite loops can be useful when paired with control mechanisms that appropriately end the loop.

while True:
    user_input = input("Enter 'q' to exit: ")
    if user_input == 'q':
        break

The above code runs indefinitely because of the condition True, but when the user enters ‘q’, the loop will terminate through the break statement.

Using an else Block with a while Statement

You can also attach an else block to the while statement. The else block is executed after the&nbps; while block is finished, unless the loop was terminated by a break statement.

i = 1
while i <= 5:
    print(i)
    i += 1
else:
    print("The loop has ended naturally.")

In this code, when i becomes 6, the while loop ends, and the statements in the else block are executed.

Practical Applications of the while Statement

Through examples, we will explore some useful ways to use the while statement. Each example demonstrates how the while statement can be used to solve more complex problems.

User Input Validation

You can write a program that keeps requesting input from the user until valid input is received.

while True:
    number_str = input("Please enter a number: ")
    try:
        number = int(number_str)
        break
    except ValueError:
        print("That's not a valid number. Please try again.")

In this case, the program continues to prompt for input until the user enters a number. If an invalid input is received, it shows an error message.

Reading Until End of File

You can write a program that reads a file line by line and stops when there is no more data to read.

with open('some_file.txt', 'r') as file:
    line = file.readline()
    while line:
        print(line, end='')
        line = file.readline()

This code opens a file and prints its content while reading each line sequentially. The loop ends when there are no more lines to read.

Things to Be Careful About When Using while Statements

When using the while statement, it is important to set the condition clearly to avoid getting stuck in an infinite loop. Infinite loops can often stop the program and create unintended situations. Therefore, within the loop, you should properly modify the condition or use statements like break to ensure the loop ends as intended.

Additionally, when using the while statement, if the number of iterations is not properly limited, performance issues may arise. It is important to optimize operations within the loop and avoid unnecessary tasks to minimize long processing times.

Conclusion

Now you understand how the while statement works and have learned ways to use it in various situations. The while statement is a powerful structure that executes repeatedly as long as the given condition is true, and can be used in various scenarios such as infinite loops and user input validation. I hope this course enables you to use the while statement with confidence.

Understanding Python If Statements

One of the most fundamental and essential control statements in Python programming is the if statement. In this tutorial, we will explore Python’s if statement in depth and practice through various examples. Through this, you can enhance your programming logic and problem-solving skills.

What is an if statement?

An if statement is a conditional statement used to control the flow of code. It allows you to execute statements only when a specific condition is true, thereby structuring the logic of the program. This conditional flow control helps to simplify complex problems.

Syntax of if statements in Python

The basic syntax of an if statement in Python is as follows:

if condition:
    code to execute

Here, the condition contains a boolean expression, and if this expression is true, the indented ‘code to execute’ block is executed. This condition can be created using various comparison operators (<, >, ==, !=, <=, >=) and logical operators (and, or, not).

Example

Basic example

age = 18
if age >= 18:
    print("You are an adult.")

In the above code, the variable age is set to 18. The if statement checks whether age >= 18 is true, and if so, it prints “You are an adult.”

if-else statement

By using the else clause that pairs with the if statement, you can define the code to be executed when the condition is not true:

age = 15
if age >= 18:
    print("You are an adult.")
else:
    print("You are a minor.")

In this example, since age is less than 18, “You are a minor.” is printed.

if-elif-else statement

When you need to check multiple conditions, you can use elif to specify additional conditions:

score = 85
if score >= 90:
    print("Grade A")
elif score >= 80:
    print("Grade B")
elif score >= 70:
    print("Grade C")
else:
    print("Grade D")

Here, since score is 85, the output will be “Grade B”. The program evaluates the conditions from top to bottom, executing the block of the first true condition and skipping the rest.

Nested if statements

You can include another if statement inside an if statement to perform nested condition checks as needed:

num = 10
if num >= 0:
    print("Positive number.")
    if num == 0:
        print("This is zero.")
else:
    print("Negative number.")

The above code checks if num is greater than or equal to 0, and then checks if it is equal to 0 to print a message if the condition is met.

Complex conditions using logical operators

If you need to evaluate multiple conditions at once, you can use logical operators and, or, not. Here is an example using these logical operators:

age = 25
income = 4000

if age > 18 and income > 3000:
    print("You are eligible to apply for a loan.")
else:
    print("You do not meet the loan application conditions.")

This example will execute the output statement “You are eligible to apply for a loan.” only if the age is greater than 18 and income exceeds 3000.

Conditional expressions (ternary operator)

In Python, you can use a ternary operator, also known as a conditional expression, to simplify if statements. The general form is as follows:

value to execute if true if condition else value to execute if false

Here is an example utilizing it:

num = 5
result = "Even" if num % 2 == 0 else "Odd"
print(result)

This code checks whether num is divisible by 2 and assigns “Even” or “Odd” to result accordingly.

Conclusion

The if statement in Python plays an essential role in controlling the flow of programs, providing flexible syntax to handle various conditions. We have covered from basic if statements to nested if statements, the use of and/or logical operators, and ternary operators. I hope this tutorial helps you improve your programming skills.

02: Basics of Python Programming – Data Types

Chapter 02: Basics of Python Programming – Data Types

In programming, data types help to indicate what kind of value each piece of data holds. Python offers a variety of built-in data types, and understanding and using them correctly is essential for writing efficient and error-free code. In this chapter, we will delve deeply into Python’s main data types and their usage.

Main Data Types in Python

Python’s data types can be broadly classified into boolean (bool), integer (int), floating-point (float), complex (complex), string (str), list (list), tuple (tuple), set (set), and dictionary (dict).

Boolean Type (bool)

The boolean type represents logical true (True) and false (False). It is mainly used in conditional statements and is also employed in logical operations.

Example

is_raining = True
is_sunny = False
print(is_raining and is_sunny)  # Output: False
print(is_raining or is_sunny)   # Output: True

Integer Type (int)

The integer type represents whole numbers. Python supports arbitrary precision, so there is no limit on the number of digits in an integer as long as memory allows.

Example

large_number = 10000000000000000000
small_number = -42
print(large_number + small_number)  # Output: 9999999999999999958

Floating-Point Type (float)

The floating-point type is used to represent numbers with decimal points (real numbers). The accuracy of floating-point numbers may vary slightly based on the binary representation used by the system.

Example

pi = 3.141592653589793
radius = 5.0
area = pi * (radius ** 2)
print("Area of the circle:", area)  # Output: Area of the circle: 78.53981633974483

Complex Type (complex)

The complex type is used to represent complex numbers composed of a real part and an imaginary part. Complex numbers are primarily used in scientific calculations or engineering mathematics.

Example

z = 3 + 4j
print("Real part:", z.real)  # Output: Real part: 3.0
print("Imaginary part:", z.imag)  # Output: Imaginary part: 4.0

String Type (str)

String represents text and is enclosed in single or double quotes. Strings are immutable data types.

Example

greeting = "Hello, World!"
name = 'Alice'
message = greeting + " " + name
print(message)  # Output: Hello, World! Alice

List Type (list)

A list is a data type that can store multiple values in order and is defined with square brackets ([]). Lists are mutable data types, allowing for the addition, deletion, and modification of elements.

Example

fruits = ["apple", "banana", "cherry"]
fruits.append("orange")
print(fruits)  # Output: ['apple', 'banana', 'cherry', 'orange']
fruits[1] = "blueberry"
print(fruits)  # Output: ['apple', 'blueberry', 'cherry', 'orange']

Tuple Type (tuple)

A tuple is similar to a list, but it has immutable characteristics. It is useful for managing objects that should not change. Tuples are defined with parentheses ().

Example

coordinates = (10.0, 20.0)
# coordinates[0] = 15.0 # Error: 'tuple' object does not support item assignment
print(coordinates)  # Output: (10.0, 20.0)

Set Type (set)

A set is a collection of unique elements with no defined order. It is useful for performing set-related operations. Sets are defined with curly braces ({}).

Example

fruit_set = {"apple", "banana", "cherry"}
fruit_set.add("orange")
print(fruit_set)  # Output's order is random: {'orange', 'banana', 'cherry', 'apple'}

# Example of removing an element
fruit_set.remove("banana")
print(fruit_set)  # Output: {'orange', 'cherry', 'apple'}

Dictionary Type (dict)

A dictionary is a data type for storing key/value pairs. It is defined with curly braces ({}), and keys must be unique.

Example

person = {"name": "John", "age": 30, "job": "developer"}
print(person["name"])  # Output: John

# Adding a new key/value pair
person["city"] = "New York"
print(person)  # Output: {'name': 'John', 'age': 30, 'job': 'developer', 'city': 'New York'}

Type Conversion

Converting data types in Python is very useful. It mainly occurs through explicit conversion or implicit conversion.

Explicit Conversion (Type Conversion)

Explicit conversion is done by the developer explicitly stating the conversion in the code. Python provides various functions for type conversion.

Example

# Converting an integer to a string
num = 123
num_str = str(num)
print(type(num_str))  # Output: 

# Converting a string to an integer
str_num = "456"
num_int = int(str_num)
print(type(num_int))  # Output: 

# Converting an integer to a floating-point number
int_num = 10
float_num = float(int_num)
print(float_num)  # Output: 10.0

Implicit Conversion (Automatic Type Conversion)

Implicit conversion refers to type conversion that is automatically carried out by Python. It mainly occurs when there is no risk of data loss.

Example

int_num = 5
float_num = 2.3
result = int_num + float_num
print(result)  # Output: 7.3
print(type(result))  # Output: 

Conclusion

In this chapter, we learned about the various data types in Python. Understanding the characteristics and proper usage of each data type is very important for gaining a deeper understanding of Python programming. In the next chapter, we will cover more advanced topics such as control statements and functions, which will help you write more complex and powerful programs using Python.

02-8 Basics of Python Programming, Storage Space for Data Type Values, Variables

For those who are learning Python for the first time, variables are one of the core concepts of programming. A variable refers to a named storage space used to store and manipulate data, allowing the program to perform various operations and obtain desired results. In this course, we will explore in detail what variables are in Python programming, how to use them, and the basic concepts related to variables.

What is a Variable?

A variable is a named memory space for storing data. Its purposes can be summarized in two main points.

  1. It stores data.
  2. It can retrieve or change the stored data.

In Python, variables can hold various values regardless of data type, and you can access the stored values via the name of the variable. This allows programmers to easily access and manipulate data.

Variable Assignment and Basic Syntax in Python

In Python, there is no need to specify the data type when declaring a variable. You can create a variable and assign a value using the following syntax.

variable_name = value

For example, here’s how to assign a number and a string to a variable:

x = 10
name = "Alice"

In this case, ‘x’ stores the number 10, and ‘name’ stores the string “Alice”. Python automatically determines the type based on the assigned value.

Naming Rules for Variables

When creating variable names in Python, you must follow these rules:

  • Variable names can include letters, numbers, and underscores (_).
  • Variable names cannot start with a number.
  • Whitespace is not allowed. Instead, you can use underscores (e.g., my_variable).
  • Pythons reserved words cannot be used as variable names (e.g., defclass, etc.).

By following these rules, you can improve the readability of your code and make it easier to maintain.

Dynamic Characteristics of Variables

Python variables support dynamic typing. This means that a variable can hold values of different types than what it was initially set to. For example:

x = 10     # Integer
x = "Hello" # String

In this case, ‘x’ initially holds the integer 10 and later is changed to the string “Hello”. This provides programmers with great flexibility.

Variable Scope

The scope of a variable refers to the area of the program where the variable is valid. Python mainly has two types of scopes:

  • Local Variables: Declared within a function or block and cannot be accessed outside that block.
  • Global Variables: Declared outside a function block and can be accessed throughout the program.

For example:

global_var = "I am global"

def my_function():
    local_var = "I am local"
    print(local_var)

my_function()
print(global_var)
# print(local_var)  # Error: local_var is only accessible within the function

Basic Operations on Variables

Basic operations related to variables include assignment, update, and deletion. In Python, you can perform these operations as follows:

# Assign value to variable
x = 5

# Update variable value
x = x + 2

# Delete variable
del x

Variables allow for easy referencing and modification of the assigned data.

Memory Management of Variables

The Python interpreter manages variables and automatically handles memory through a garbage collector. When the reference count of a variable reaches zero, the associated memory is automatically freed, allowing for effective resource management.

Variable and Object Reference

In Python, variables do not directly store objects but reference them. This means that multiple variables can reference a single object. For example:

a = [1, 2, 3]
b = a

Here, ‘a’ and ‘b’ reference the same list object. This means that changes will be reflected in all referencing variables.

Understanding these characteristics is important to avoid unexpected errors when manipulating data.

Conclusion

In Python, variables are essential for storing and manipulating data. Variable names should be written accurately and clearly, and understanding the dynamic characteristics and scope of variables helps minimize errors in the program. Familiarizing yourself with the concepts and functions of variables as a foundation of Python programming will enhance your programming efficiency and provide a basic framework for solving more complex problems.

Based on these fundamental concepts, try writing programs and exploring Python’s various data types and functionalities. In the next course, we will delve into more advanced topics.

Basic of Python Programming: Boolean Data Type

Introduction

Understanding data types in programming is important. Data types define the values that variables and constants can store and manipulate. In this tutorial, we will learn about the Boolean (Bool) data type, which is one of the basic data types in Python. The Bool type plays an important role in computer science and is mainly used in conditional statements and control structures. In this article, we will take a deep dive into the characteristics and applications of the Bool data type.

What is a Boolean Data Type?

The Boolean data type is a type used to represent true (True) and false (False). This type can logically represent one of two states. In Python, the Boolean data type is implemented as a class called bool, and it can only have the following values:

  • True
  • False

It is important to note that True and False must start with uppercase letters. If they start with lowercase letters, they will not be recognized in Python.

Examples of Using the Boolean Data Type

The Boolean data type is primarily used within conditional statements. Conditional statements control the flow of the program based on whether certain conditions are true or false. Boolean values are also frequently used as return values from functions and as results of comparison operations. For example, you can use the following comparison operation:


a = 10
b = 20
result = a < b  # True
            

In the above code, result holds the value True. This is because a is less than b.

Relationship with Conditional Statements

The Boolean data type is the most commonly used data type in conditional statements. Boolean values are used to control the flow of the program, such as in if statements or while loops. Here is an example using an if statement:


if result:
    print("a is less than b.")
else:
    print("a is greater than or equal to b.")
            

In the above example, since result is True, the string “a is less than b.” will be printed.

Boolean Operators

Python provides various logical operators that can be used with Boolean data types. These operators perform logical operations on Boolean values. Typical Boolean operators include and, or, and not.

  • and: Returns True only if both operands are True.
  • or: Returns True if at least one of the operands is True.
  • not: Inverts the Boolean value of the operand. Converts True to False and False to True.

These logical operators are useful for evaluating complex logical conditions. For example, you can use and to check if both logical conditions are met:


x = True
y = False
result = x and y  # False
            

In this code, result is False. While x is True, y is False.

Boolean Type Conversion

Python also provides methods to convert other data types to the Boolean type. This can be done using the bool() function. Almost all data values are considered true, with a few exceptions that are considered false. Values considered false correspond to null or 0, including the following:

  • False
  • None
  • Number 0: 0, 0.0
  • Empty sequences: '', [], (), {}

Understand these concepts through the following examples:


bool(0)  # False
bool(1)  # True
bool("")  # False
bool("Python")  # True
            

Here, values like 0 and "" are evaluated as False, while values like 1 and "Python" are evaluated as True.

Applications of Boolean Data Type

The Boolean data type is widely used in various programming patterns and algorithms. For example, Boolean values can be used to track whether a specific condition is met using flag variables or to check the existence of data. This kind of application of Boolean values helps in making complex program logic easier to understand.

Let’s look at an example of a simple application:


def is_even(num):
    return num % 2 == 0

numbers = [1, 2, 3, 4, 5]
even_numbers = [num for num in numbers if is_even(num)]

print(even_numbers)  # Output: [2, 4]
            

In this example, we filter out even numbers from the list numbers to obtain the even_numbers list. The is_even() function checks whether a number is even and consequently returns a Boolean value.

Conclusion

The Boolean data type in Python is an essential element that determines the control flow of programs. Understanding how the Boolean type is used in conditional statements and loops will allow you to write more complex and powerful programs. We hope you apply the concepts learned in this tutorial to various problem-solving scenarios, deepening your understanding of Python programming.