To begin writing and running Python code, install a Python interpreter and a suitable development enviroment. A standard setup includes:
- Python Interpreter: Provides runtime execution of Python scripts. Available from the official python.org site; ensure version compatibility with your operating system.
- Code Editor or IDE: Simplifies writing, testing, and debugging. Popular choices include Visual Studio Code, PyCharm, Sublime Text, or IDLE (bundled with Python).
- Package Manager:
pipis included with modern Python distributions and enables installing third-party libraries.
With these components ready, practice basic concepts through concise examples.
Displaying a Greeting
msg_printer = lambda text: print(text)
msg_printer("Hello, World!")
Simple Addision Utility
def collect_and_add():
val_a = float(input("Input first value: "))
val_b = float(input("Input second value: "))
total = val_a + val_b
print(f"Total: {total}")
collect_and_add()
Number Guessing Game
import random
def run_guess_game():
secret = random.randrange(1, 101)
attempt = int(input("Pick a number from 1 to 100: "))
if attempt == secret:
print("Well done! Correct guess.")
else:
print(f"Incorrect. The answer was {secret}.")
run_guess_game()
Reverse Input Text
def reverse_text():
entry = input("Type some text: ")
inverted = ''.join(reversed(entry))
print(f"Backwards: {inverted}")
reverse_text()
Convert Celsius to Fahrenheit
def c_to_f():
cel = float(input("Celsius temperature: "))
fahr = cel * 9 / 5 + 32
print(f"Fahrenheit: {fahr}")
c_to_f()
Double Elements in a Sequence
def double_items(seq):
return [item * 2 for item in seq]
initial = [1, 2, 3, 4, 5]
print(f"Start: {initial}")
print(f"Doubled: {double_items(initial)}")
Compute Quadratic Roots
import math
def solve_quadratic():
coeff_a = float(input("Coefficient a: "))
coeff_b = float(input("Coefficient b: "))
coeff_c = float(input("Coefficient c: "))
disc = coeff_b ** 2 - 4 * coeff_a * coeff_c
if disc > 0:
root1 = (-coeff_b + math.sqrt(disc)) / (2 * coeff_a)
root2 = (-coeff_b - math.sqrt(disc)) / (2 * coeff_a)
print(f"Distinct roots: {root1}, {root2}")
elif disc == 0:
root = -coeff_b / (2 * coeff_a)
print(f"Single root: {root}")
else:
real = -coeff_b / (2 * coeff_a)
imag = math.sqrt(-disc) / (2 * coeff_a)
print(f"Complex roots: {real}+{imag}i, {real}-{imag}i")
solve_quadratic()
Write and Read a File
def file_demo():
with open("sample.txt", "w") as fh:
fh.write("Demo line for file handling.")
with open("sample.txt", "r") as fh:
data = fh.read()
print(f"Contents: {data}")
file_demo()
Define and Use a Class
class Canine:
def __init__(self, pet_name, pet_age):
self.title = pet_name
self.years = pet_age
def vocalize(self):
print("Woof!")
dog_instance = Canine("Max", 4)
print(f"{dog_instance.title} is {dog_instance.years} years old.")
dog_instance.vocalize()
Handle Runtime Errors
def safe_division():
try:
x = int(input("Provide a number: "))
y = int(input("Provide another number: "))
outcome = x / y
print(f"Outcome: {outcome}")
except ValueError:
print("Invalid numeric input.")
except ZeroDivisionError:
print("Division by zero is not allowed.")
except Exception as err:
print(f"Unexpected issue: {err}")
safe_division()
These snippets illustrate fundamental mechanics: console intercation, branching logic, collection processing, file I/O, class instantiation, and defensive programming using exceptions.