Python Basics: Variables, Control Flow, and Functions
Welcome to this comprehensive Python fundamentals course. Whether you are new to programming or transitioning from another language, this module will solidify your understanding of three…

What will be printed by the following code? x = int(input('첫번째 정수를 입력하시오: ')) y = int(input('두번째 정수를 입력하시오: ')) print(x, '+', y, '=', x + y) If the user enters 300 and 400 respectively?
In the grade‑determination program, which condition correctly assigns grade 'C'?
What is the output of the following loop? for i in range(1, 5, 2): print(i, end=' ')
When using the break statement inside a for loop, which numbers will be printed? for i in range(100): if i == 5: break print(i, end=' ')
Which function definition correctly creates a function that returns the area of a circle given its radius?
What will be the value of variable 'shipping_cost' after executing the following code? price = int(input('상품 가격을 입력하세요: ')) if price > 20000: shipping_cost = 0 else: shipping_cost = 3000
Which statement correctly describes the effect of the continue statement in the loop below? for i in range(20): if i % 2 == 0: continue print(i, end=' ')
What is the result of evaluating the expression '23' + '56' in Python?
In the function call 'calc(x, y)', which of the following best describes what 'x' and 'y' are?
Python Basics: Variables, Control Flow, and Functions
Welcome to this comprehensive Python fundamentals course. Whether you are new to programming or transitioning from another language, this module will solidify your understanding of three core concepts: variables, control flow, and functions. Each section includes clear explanations, practical examples, and common pitfalls to avoid, all optimized for search engines so you can easily find the information you need.
1. Variables in Python
Variables are symbolic names that reference values stored in memory. In Python, variable names must follow specific rules:
- Start with a letter (a‑z, A‑Z) or an underscore (
_). - Contain only letters, numbers, or underscores.
- Are case‑sensitive (
total≠Total). - Cannot be a reserved keyword such as
deforif.
Consider the following quiz question:
Which of the following variable names is valid in Python?
- total price
- 2total
- total-price
- _total2 (correct)
The correct answer, _total2, starts with an underscore and contains only alphanumeric characters, satisfying all naming rules.
2. Getting Input and Simple Arithmetic
Python’s input() function reads user input as a string. To perform arithmetic, you must convert the string to an integer or float using int() or float().
x = int(input('첫번째 정수를 입력하시오: '))
y = int(input('두번째 정수를 입력하시오: '))
print(x, '+', y, '=', x + y)
If the user enters 300 and 400, the program prints:
300 + 400 = 700
This demonstrates proper type conversion and string formatting.
3. Control Flow: Conditional Statements
Conditional statements let your program decide which block of code to execute based on Boolean expressions. The basic structure uses if, elif, and else clauses.
score = int(input('Score: '))
if score >= 90:
grade = 'A'
elif score >= 80:
grade = 'B'
elif score >= 70:
grade = 'C'
else:
grade = 'D'
print('Grade:', grade)
Notice the grade ‘C’ condition:
elif score >= 70:
This correctly captures scores from 70 up to, but not including, 80.
4. Loops: for and while
Loops repeat a block of code multiple times. The for loop iterates over a sequence, often generated by range(). The range(start, stop, step) function creates numbers from start up to (but not including) stop, incrementing by step.
for i in range(1, 5, 2):
print(i, end=' ')
Output:
1 3
Explanation: The loop starts at 1, adds 2 each iteration, and stops before 5, producing 1 and 3.
4.1 Using break to Exit a Loop Early
The break statement terminates the nearest enclosing loop immediately.
for i in range(100):
if i == 5:
break
print(i, end=' ')
Result:
0 1 2 3 4
When i reaches 5, break stops the loop, so 5 is never printed.
4.2 Using continue to Skip an Iteration
The continue statement skips the rest of the current loop iteration and proceeds with the next one.
for i in range(20):
if i % 2 == 0:
continue
print(i, end=' ')
Output:
1 3 5 7 9 11 13 15 17 19
Only odd numbers are printed because even numbers trigger continue, which bypasses the print statement.
5. Functions: Defining Reusable Code
Functions encapsulate logic that can be called multiple times with different arguments. A function definition starts with the def keyword, followed by the function name and parameters in parentheses.
def get_area(radius):
return 3.14 * radius ** 2
This definition correctly calculates the area of a circle using the formula πr². The quiz question highlighted the correct syntax:
def get_area(radius): return 3.14*radius**2
Other options either omitted the parameter, mis‑calculated the area, or placed the return statement incorrectly.
6. Practical Example: Shipping Cost Calculator
Combining input, conditionals, and variables, let’s build a simple shipping cost calculator:
price = int(input('상품 가격을 입력하세요: '))
if price > 20000:
shipping_cost = 0
else:
shipping_cost = 3000
print('Shipping cost:', shipping_cost)
The logic follows the rule: free shipping for orders over 20,000. The correct answer to the related quiz question is:
0 if price > 20000, otherwise 3000
7. Key Takeaways
- Variable naming: Use letters, numbers, and underscores; start with a letter or underscore.
- Input handling: Convert strings to numeric types before arithmetic.
- Conditional logic: Order
if/elif/elsestatements from most specific to most general. - Loops:
range()controls start, stop, and step;breakexits early;continueskips to the next iteration. - Functions: Define with
def, accept parameters, and return values.
8. Frequently Asked Questions (FAQ)
What makes a variable name invalid?
Names that start with a digit, contain spaces, hyphens, or match Python keywords are invalid. For example, 2total and total-price will raise a SyntaxError.
How does break differ from continue?
break stops the entire loop, while continue only skips the current iteration and proceeds with the next one.
Can I define a function without parameters?
Yes, but if the function needs external data (like a radius), you must pass it as an argument. A function without parameters cannot access undefined variables, leading to a NameError.
9. Practice Exercises
- Create a variable named
_score5and assign it the integer85. Print the variable. - Write a program that asks for two numbers and prints their sum in the format
num1 + num2 = result. - Implement a loop that prints numbers from 10 to 0 (inclusive) using
range()andbreakwhen the number reaches 5. - Define a function
fahrenheit_to_celsius(f)that returns the Celsius equivalent of a Fahrenheit temperature.
These exercises reinforce the concepts covered and help you build confidence in writing clean, functional Python code.
