Environment Configuration and Execution
Python operates as an interpreted scripting language compatible with Linux shells. It is widely utilized for scientific computation, automation, cloud services, web scraping, data analysis, and AI interfaces, often leveraging extensive third-party libraries.
Running Scripts in Linux
Modern Ubuntu distributions (e.g., 20.04+) include Python 3 by default. For older versions, installation via package manager is required.
Interactive Mode: Executing commands directly in the terminal returns results immediately without creating files.
Script Mode: Create a file and execute it via the interpreter.
touch script.py
# Edit file content...
python3 script.py
IDE Integration (VSCode)
While terminal editors like Vim are powerful for navigation, integrated development environments offer superior editing features, cross-platform support, and debugging capabilities.
Installation: Download the appropriate package and install via dpkg.
sudo dpkg -i vscode_package.deb
# To remove: sudo dpkg -r package_name
Configuration:
- Interpreter: Select the Python version via the status bar.
- Debugging: Generate a
launch.jsonconfiguration by selecting the Python Debugger. - Breakpoints: Click beside line numbers to toggle breakpoints. Use F5 to run and F11 for step-through debugging.
- Settings Transfer: Copy the
.vscodedirectory to new projects to retain configurations (cp -rf source/.vscode/ destination/).
Practical IDE Tips
- External Console: Modify
launch.jsonto set"console": "externalTerminal"for separate output windows. - Zoom: Use
Ctrl + =to zoom in andCtrl + -to zoom out. - Prevent Exit: To keep the terminal open after execution, add a delay.
import time
time.sleep(3)
- Font Settings: Configure terminal font size permanently via profile preferences.
Core Syntax Example
Python parses code sequentially. Functions ancapsulate logic to avoid repetition.
from time import sleep, ctime
system_mode = 'high_load'
def process_task():
print("Initializing resources")
print("------ Processing ------")
buffer = "start"
buffer = buffer + '_data'
print('Buffer status: ' + buffer)
if system_mode == 'high_load':
iteration = 0
while iteration < 5:
iteration += 1
print('Cycle: ' + str(iteration))
else:
print('Single pass execution')
buffer = buffer + '_end'
print('Buffer status: ' + buffer)
sleep(1)
print("Task Complete")
print(ctime())
print("============ System Check =============")
process_task()
process_task()
Numeric Representations
Base Literals
Python supports multiple integer bases directly in syntax.
Octal (Base 8):
Prefix with 0o.
val_oct = 0o77
print("Octal value: " + str(val_oct))
# Output: 63
Decimal (Base 10): Standard notation.
val_dec = 100
print("Decimal value: " + str(val_dec))
Hexadecimal (Base 16):
Prefix with 0x.
val_hex = 0xFF
print("Hex value: " + str(val_hex))
# Output: 255
Large Integers and Booleans
Integers have arbitrary precision. Booleans evaluate truthiness based on content.
big_num = 10 ** 10
print(big_num)
print(bool(1)) # True
print(bool(0)) # False
print(bool("data")) # True
print(bool("")) # False
print(bool([1, 2])) # True
print(bool([])) # False
Boolean values act as integers in arithmetic operations (True=1, False=0).
flag = 50 < 40
print(flag) # False
print(flag + 10) # 10
Floating Point Precision
Standard floats may exhibit precision errors due to binary representation.
print(0.1 + 0.2 == 0.3) # False
# Mitigation strategy
print((10 * 0.1 + 10 * 0.2) / 10 == 0.3) # True
For precise decimal arithmetic, use the decimal module. Note the difference between string and float initialization.
from decimal import Decimal
d1 = Decimal('0.1')
d2 = Decimal(0.1)
print(d1) # 0.1
print(d2) # 0.10000000000000000555...
Type and Base Conversion
Convert between types explicitly.
print(int(9.99)) # 9 (Truncates)
print(float(5)) # 5.0
print(complex(5)) # (5+0j)
# Base conversion
print(hex(200)) # 0xc8
print(oct(200)) # 0o310
ASCII conversion handles character codes.
print(chr(65)) # 'A'
print(ord('A')) # 65
Operators and Logic
Arithmetic
Standard math operators apply. Note floor division // and modulus %.
print(10 + 5 * 2 / 4)
print(10 % 3) # 1
print(2 ** 4) # 16
print(9 // 2) # 4
Comparison
Values and types are considered during equality checks.
x = 5
y = "5"
if x == y:
print("Equal")
else:
print("Not Equal")
z = 5.0
if x == z:
print("Value Equal")
Bitwise Operations
Operate on binary representations.
m = 17 # 10001
n = 6 # 00110
print(m & n) # 0 (00000)
print(m | n) # 23 (10111)
print(m ^ n) # 23 (10111)
print(~m) # -18
print(m << 1) # 34
print(m >> 1) # 8
Logical Flow
Combine conditions using and, or, not. Check membership with in.
user_age = 28
is_adult = user_age > 18 and user_age < 65
print(is_adult)
has_id = True
credits = 500
if has_id or credits > 1000:
print("Access Granted")
items = [10, 20, 30]
print(20 in items) # True
print(40 not in items) # True
data = {'id': 1}
ref = data
ref['id'] = 2
print(ref is data) # True (Same object)
Type Casting
Python requires explicit casting for mixed-type operations involving strings and numbers.
print(int(7.89) + 2) # 9
print(int('10') + 5) # 15
print(float(3) + 1.5) # 4.5
print(str(456) + 'abc') # '456abc'
# Dictionary to string
obj = {'key': 'value'}
print(str(obj) + ' logged')
Implicit conversion occurs in specific contexts, but operations like subtraction between strings fail.
name = "user"
print(name[0]) # 'u'
print('100' + 'ms') # '100ms'
# print('100' - 'ms') # TypeError