04-1 Python Input and Output and Functions: From Basics to Advanced

One of the basic and commonly used features of Python programming is using input, output, and functions. In this course, you will learn about various input and output methods, the concept of functions, and practical usage.

Input and Output

Output Methods

The most basic output method is to use the print() function. This function outputs the content given within the parentheses to the screen. It provides various options for output by converting different types of data into strings.


print('Hello, world!')
print(3.14159)
print('Number', 42)  # Outputs multiple arguments separated by a space
print(f'The value is {42}')  # Formatting using f-string
    

Let’s take a closer look at various output methods.

Formatted Output

String formatting can organize and structure the output content to make it more understandable.

  1. Classical Method
  2. Using str.format() Method
  3. f-string (Python 3.6+)

Input Methods

The way to receive input from the user is by using the input() function. input() function always returns a string, so you may need to convert it to the appropriate type if necessary.


user_name = input('Enter your name: ')
age = input('Enter your age: ')
age = int(age)  # Convert to a number
print(f'Hello, {user_name}. You are {age} years old.')
    

Validating Input Values

It is essential to validate the received input before using it, especially in the case of numeric input.


while True:
    try:
        age = int(input('Enter a valid age: '))
        break  # Exit the loop if valid input is received
    except ValueError:
        print('Invalid input. Please enter a number.')
print(f'Thank you! You entered: {age}')

Chapter 03: Building the Structure of a Python Program! Control Statements

In this chapter, we will delve into the control statements in Python with a deep understanding. Control statements are important tools that manage the flow of a program and make logical decisions. By effectively utilizing control statements, we can write more complex and efficient programs.

1. Basic Concepts of Control Statements

In programming, control statements are commands that change the execution flow of code. Controlling this flow allows the execution or repetition of code based on conditions, ensuring that the program operates correctly and runs more efficiently.

Common control statements used in Python include conditional statements and loop statements. Conditional statements are used to decide whether to execute a code block based on a given condition, while loop statements are used when a specific code block needs to be executed multiple times.

2. Conditional Statements: if, elif, else

2.1 Basic If Statement

Conditional statements allow us to implement the logic of ‘if some condition is true, execute this code’. A basic if statement is written as follows:


if condition:
    code_to_execute
        

Here, if the condition is true, the indented code block will be executed.

2.2 If-Else Statement

An if statement can be combined with an else statement to specify an alternative code to execute when the condition is false.


if condition:
    code_to_execute_if_true
else:
    code_to_execute_if_false
        

This structure allows us to write more robust code by providing a code block to execute when the condition is false.

2.3 If-Elif-Else Statement

When multiple conditions are needed, we can use elif (short for else if). This checks multiple conditions in order and executes only the code block for the first true condition.


if condition1:
    code_to_execute1
elif condition2:
    code_to_execute2
else:
    code_to_execute_default
        

This structure allows us to execute only the corresponding code block if any of several conditions are met, and specifies a default code block to execute otherwise.

3. Loop Statements: for, while

3.1 While Statement

The while statement is used to repeatedly execute a code block as long as a given condition is true. Here is the basic structure of a while statement:


while condition:
    code_to_repeat
        

When the condition is true, the code block to repeat is executed, and the repetition ends when the condition becomes false.

3.2 For Statement

The for statement is primarily used when the number of repetitions is specified or when iterating over items of iterable objects (e.g., lists, tuples, strings, etc.).


for variable in iterable_object:
    code_to_repeat
        

The code to repeat is executed for each element of the iterable object, and the iteration ends when there are no more elements.

4. Nested Control Statements

Control statements can be nested within each other. This is useful for implementing complex conditions or looping structures. For example, you can place an if statement inside a for statement or a while statement inside a for statement.


for i in range(5):
    if i % 2 == 0:
        print(f"{i} is even.")
    else:
        print(f"{i} is odd.")
        

The above example iterates over numbers from 0 to 4, determining whether each number is even or odd and printing the result.

5. break and continue Statements

5.1 Break Statement

The break statement immediately terminates a loop. It is commonly used when you want to stop the loop when a specific condition is met.


for i in range(10):
    if i == 5:
        break
    print(i)
        

The code above iterates from 0 to 9, but stops repeating when it reaches 5.

5.2 Continue Statement

The continue statement skips the remaining code in the current iteration and starts the next iteration. It is useful when you want to perform the next iteration before checking the next condition.


for i in range(5):
    if i == 2:
        continue
    print(i)
        

This example iterates from 0 to 4, skipping 2 and printing the remaining numbers.

6. Example Program Using Control Statements

Finally, let’s write a simple program utilizing the control statements we’ve learned. Here, we will create a program that generates a Fibonacci sequence based on a number entered by the user.


# Fibonacci sequence generator
def fibonacci(n):
    a, b = 0, 1
    while a < n:
        print(a, end=' ')
        a, b = b, a + b
    print()

num = int(input("Please enter the range to generate the Fibonacci sequence: "))
fibonacci(num)
        

This program generates and prints the Fibonacci sequence up to the number entered by the user. It uses a while statement to calculate the sequence and limits the generation of the sequence based on user input.

In this chapter, we learned about the basic control statements in Python. Control statements are important components that determine the logical flow of a program, and understanding and utilizing them well allows us to write stronger and easier-to-maintain code. In the next chapter, we will expand on control statements and cover various application scenarios.

Python Course: for loop

In this course, we will take a closer look at one of the important control structures in Python, the for loop. The for loop is primarily used to iterate over a specific range of values. In Python, the for loop is useful for traversing sequences (lists, tuples, strings, etc.) and helps to efficiently handle repetitive tasks.

1. Basic Structure of for Loop

The for loop in Python is designed to repeatedly execute a specific block of code for each element in a sequence. The basic structure is as follows:

for variable in sequence:
    code to execute
    

Here, “variable” will receive one element of the sequence in each iteration, and “code to execute” contains the actual tasks to perform.

2. Example: Iterating Over a List

Let’s take a look at the most basic example of iterating over a list.

fruits = ['apple', 'banana', 'cherry']
for fruit in fruits:
    print(fruit)
    

This code will print each fruit name from the fruits list. The output will be as follows:

apple
banana
cherry
    

3. Using for Loop with range() Function

The range() function is mainly used with the for loop to repeat code a specified number of times. It has the syntax range(start, stop[, step]), and the parameters are as follows:

  • start: The number where the count begins. The default is 0.
  • stop: The number where the count ends (not included).
  • step: The interval between counts. The default is 1.

Let’s understand this with an example:

for i in range(3):
    print(i)
    

Output:

0
1
2
    

4. Nested for Loops

A nested for loop simply means having another for loop inside a for loop. Here is an example of a nested for loop that iterates over a two-dimensional list:

matrix = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
for row in matrix:
    for num in row:
        print(num)
    

This code will print all the numbers in the 2D list.

5. for Loop and else

Surprisingly, in Python, the for loop can be used with else. You can write code in the else block that will execute when the for loop has completed normally. Let’s see the following example:

for fruit in fruits:
    if fruit == 'banana':
        print('Banana found!')
        break
else:
    print('No bananas.')
    

In this case, ‘Banana found!’ will be printed, demonstrating how the for-else construct works.

6. Using with enumerate()

The enumerate() function helps to deal with both index and elements simultaneously when iterating through a sequence. Let’s take a closer look with the following example:

for index, fruit in enumerate(fruits):
    print(index, fruit)
    

Output:

0 apple
1 banana
2 cherry
    

7. Using Break to Avoid Infinite Loops

If you want to stop the for loop under certain conditions, you can use the break statement. This helps avoid infinite loops or unnecessary iterations.

for i in range(10):
    if i == 5:
        break
    print(i)
    

Output:

0
1
2
3
4
    

8. Performance Considerations

When using multiple loops, performance should be considered. Especially with large datasets, nested loops can adversely affect performance. Here are some tips to minimize this:

  • Use list comprehensions when possible.
  • Utilize ‘break’ and ‘continue’ statements appropriately to avoid unnecessary iterations.

9. for Loop and List Comprehensions

List comprehensions are a way to create lists more concisely. They can be shorter than loops and sometimes faster:

numbers = [1, 2, 3, 4, 5]
squared = [n**2 for n in numbers]
print(squared)
    

Output:

[1, 4, 9, 16, 25]
    

Conclusion

The for loop in Python is an essential tool for traversing and processing various data structures and greatly aids in writing efficient code. Understanding the various uses of the for loop and applying them to actual code is important for writing effective code.

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.