Python for Generative CAD Design
Python Basics
Storing Information
Think of a variable as a labeled box where you can store information. You give the box a name, and you can put something inside it. Later, you can look inside the box or even change its contents. In Python, creating a variable is as simple as choosing a name and assigning it a value using the equals sign (=).
greeting = "Hello, world!"
user_age = 30
pi_value = 3.14159
The type of information you store determines the variable's data type. Python is smart and figures this out automatically. The most common data types are:
Strings: Used for text. You create them by wrapping text in single or double quotes. Integers: Used for whole numbers, like -5, 0, or 100. Floats: Used for numbers with a decimal point, like 98.6 or -0.5. Booleans: Can only be one of two values:
TrueorFalse. They are essential for making decisions in your code.
Making Decisions and Repeating Tasks
Programs often need to make choices or perform actions repeatedly. That's where control structures come in. They control the flow of your code.
To make a decision, you use an if statement. It checks if a condition is true. If it is, the code inside the statement runs. You can also provide alternative paths with elif (else if) and else.
temperature = 75
if temperature > 80:
print("It's a hot day!")
elif temperature < 60:
print("Better bring a jacket.")
else:
print("The weather is perfect.")
When you need to repeat a task, you use a loop. A for loop is great for iterating over a sequence, like a list of items. A while loop continues to run as long as a certain condition remains true.
# A for loop that prints numbers 0 through 4
for i in range(5):
print(i)
# A while loop that counts down from 3
count = 3
while count > 0:
print(f"Countdown: {count}")
count = count - 1 # This is crucial to avoid an infinite loop!
Creating Reusable Code
As your scripts get more complex, you'll find yourself writing the same lines of code over and over. Functions allow you to bundle up a block of code, give it a name, and reuse it whenever you need it. This makes your code more organized and easier to manage.
function
noun
A named block of organized, reusable code that is used to perform a single, related action.
You define a function using the def keyword. Functions can take inputs, called parameters, and can send back a result using the return keyword.
# Define a function that adds two numbers
def add_numbers(num1, num2):
result = num1 + num2
return result
# Call the function and store its return value
sum_result = add_numbers(5, 10)
print(sum_result) # This will print 15
Python also has a vast standard library of pre-written code organized into modules. You can bring the functionality from any module into your script using the import statement. For example, the math module contains useful mathematical functions and constants.
import math
# Use the sqrt function from the math module
square_root = math.sqrt(16)
print(square_root) # This will print 4.0
# Use the pi constant from the math module
print(math.pi)
Simple Communication
A program isn't very useful if it can't communicate. The most basic way to display information is with the print() function. To get information from a user, you can use the input() function, which prompts the user to type something and press Enter.
The
input()function always returns the user's entry as a string. If you need a number, you'll have to convert it usingint()orfloat().
# Ask the user for their name
user_name = input("What is your name? ")
# Ask for their age and convert it to an integer
age_string = input("How old are you? ")
user_age = int(age_string)
# Create a personalized greeting
print(f"Hello, {user_name}! You will be {user_age + 1} next year.")
Now you have a grasp of the fundamental pieces of Python. Let's see what you've learned.
In Python, what is the primary purpose of a variable?
What is the output of the following Python code snippet?
temperature = 25
if temperature > 30:
print("It's hot!")
elif temperature > 20:
print("It's nice.")
else:
print("It's cold.")