Python Core Syntax and Basic Programming Constructs
Python source files are typical saved using UTF-8 encoding to ensure proper handling of characters during storage and transmission. The print function sends data to the console. By default, print adds a newline character after the output, but this behavior can be modified using the end parameter.
# Output without a newline
print("Loading modules", end=" ")
print("[OK]")
# Output: Loading modules [OK]
Data Types and Conversion
Python supports several built-in data types. Integers (int) represent whole numbers and support standard arithmetic operations. Strings (str) represent text and are enclosed in single, double, or triple quotes. Strings support concatenation and repetition.
# Arithmetic expressions
value_a = 25
value_b = 5
print(value_a / value_b) # Output: 5.0
# String manipulation
project_name = "Apollo"
print(project_name * 2) # Output: ApolloApollo
print(project_name + " Mission") # Output: Apollo Mission
Type conversion allows switching between data types. Functions like int(), str(), and bool() are used for explicit conversion. Boolean logic operates on True and False values. In Python, values such as 0, empty strings "", None, and empty collections evaluate to False, while most other values evaluate to True.
active_status = bool(1)
print(active_status) # Output: True
# Integer to String conversion
label = str(100)
print(type(label)) # Output: <class 'str'>
Variables and Naming Conventions
Variables act as references to objects stored in memory. When a variable is assigned, it points to a specific memory address. If a variable is reassigned, it simply points to a new memory location; the original object may be garbage collected if no other references exist. Variable naming should be descriptive, use snake_case for multiple words, and avoid Python reserved keywords.
user_score = 95
user_name = "Alice"
# Variable reassignment logic
identifier = "ID-001"
backup_id = identifier
identifier = "ID-002"
print(backup_id) # Output: ID-001 (backup_id still points to the original object)
User Input and Comments
The input() function pauses program execution to accept text from the user. The entered data is always returned as a string, requiring casting to other types if numerical operations are needed. Comments explain code logic and are ignored by the interpreter, denoted by # for single lines or triple quotes for multi-line blocks.
# Get user age
user_age = int(input("Enter your age: "))
current_year = 2024
birth_year = current_year - user_age
print(f"Born in: {birth_year}")
Control Flow
Conditional statements execute code blocks based on boolean evaluations. The if, elif, and else structure handles multiple branching paths. Logical indentation defines the scope of each block.
system_status = "active"
if system_status == "active":
print("System running")
elif system_status == "idle":
print("System standby")
else:
print("Unknown status")
Loops
while loops repeat a block of code as long as a condition remains true. The break statement terminates the loop immediately, while continue skips the current iteration and proceeds to the next cycle.
counter = 10
while counter > 0:
if counter == 5:
print("Halfway there")
counter -= 1
continue
print(f"Countdown: {counter}")
counter -= 1
A common application of loops involves input validation or guessing games. The following example simulates a number guessing logic where the loop breaks upon a correct guess.
target_number = 7
attempts = 0
while attempts < 3:
guess = int(input("Guess a number between 1 and 10: "))
if guess == target_number:
print("Correct!")
break
else:
print("Incorrect.")
attempts += 1
String Formatting
String formatting inserts variable values into text templates. While the % operator exists for legacy compatibility, the .format() method and f-strings (Literal String Interpolation) provide more readable and flexible syntax for modern Python development.
item = "GPU"
price = 999.99
# using f-string
invoice_msg = f"The {item} costs ${price}"
print(invoice_msg)
# using format method
template = "Item: {}, Price: {}".format(item, price)
print(template)