# Python Tutorial 9: Conditional Forces

Tutorial Objectives and Overview

Tychos has the ability to evaluate a condition based on a comparison between two values. This can be used to activate or deactivate a force given a specific condition. In this tutorial we will introduce conditional statements and how they can be used to simulate a force that conditionally acts on an object. The objectives for this tutorial are:

* Learn how to define a conditional statement and use it to modify a variable's value conditionally.
* Learn how to model a force that acts on an object during an interval of time.
* Learn how to model a force that acts on an object based on the position of the object.

## Forces That Act *Conditionally*

To follow along in this tutorial, open the scenario in a new tab by clicking on the link below:

[Python Tutorial 9 - Conditional Forces](https://www.tychos.org/en/scenarios/4RloCS)

In the previous tutorials, we wrote code to define forces that acted on objects the entire duration of the simulation. This works fine if you are trying to simulate gravity acting on an object on Earth for example because the force of gravity is always acting upon that object.

But as you know, not all forces work like this. For example, you might only be pushing on a ball for a certain amount of time, so you want the force to disappear once the ball has left your hand.

In these cases, we want to model a force that acts on an object only when a certain condition is met. Let's look at an example. Below is a simulation of a particle (represented by a rocket!) that is being accelerated by a force that exists for the entire duration of the simulation. In this case it is a force that only points in the positive horizontal direction.

The code for that force is as you would expect:

```python
F1 = vec(10, 0)
```

And we then define a net force, which right now only includes this one force:

```python
Fnet = F1
```

But lets say we want to have the force *F1* only act on it during a certain time interval - this is where we must use something called a conditional operation.

### Conditional Statement

In Tychos (actually in the Python programming language) we can use a conditional statement which evaluates an expression to either *true* or *false*. Here is an example of a conditional statement:

<pre class="language-python" data-line-numbers><code class="lang-python"><strong>if t > 2:
</strong>    F1 = vec(0, 0)
    
print(F1)
</code></pre>

When this code is placed in the **Loop Code** pane, Tychos evaluates *if* 2 seconds have passed in the simulation, and *if* that is true, it changes the value of `F1`.

Place this code in the **Loop Code** and then run the simulation for at least 2 seconds, and you should see in **Console** that the value of F1 changes from (10, 0) to (0, 0).

Before the simulation time reaches 2 seconds, Tychos evaluates the statement as *false*. Once the time in the simulation has passed 2 seconds, Tychos evaluates the conditional statement and changes the value of F1.

### Comparison Operators

Conditional statements use comparison operators to compare values of two things. You have seen some of the comparison operators before, but some you might not be familiar with. Here is a list of some of the comparison operators and how they work:

<table data-header-hidden><thead><tr><th width="142">Operator</th><th width="254">Example</th><th>Evaluates</th><th>Description</th></tr></thead><tbody><tr><td>Operator</td><td>Example</td><td>Evaluates</td><td>Description</td></tr><tr><td>&#x3C;</td><td>1 &#x3C; 2</td><td>True</td><td>Less than</td></tr><tr><td>></td><td>1 > 2</td><td>False</td><td>Greater than</td></tr><tr><td>&#x3C;=</td><td>1 &#x3C;= 2</td><td>True</td><td>Less than or equal</td></tr><tr><td>>=</td><td>1 >= 2</td><td>False</td><td>Greater than or equal</td></tr><tr><td>!=</td><td>1 != 2</td><td>True</td><td>Not equal</td></tr><tr><td>==</td><td>1 == 2</td><td>False</td><td>Equal</td></tr><tr><td>equals</td><td>equals(vec(0, 0), vec(0, 1))</td><td>False</td><td>Equality of vectors</td></tr></tbody></table>

The last one is actually a function, not a comparison operator and it is used to check if two vector elements are both equivalent.

### Another Way - Using A Conditional Operator&#x20;

In Python, and many other computer languages, the value *True* can be represented as the number 1, and the value of *False* is also represented as 0. Let's demonstrate to make this more obvious.

Add this line of code to your **Loop Code** pane:

```python
print(5 * (t < 2))
```

What you should see now in the **Console** is that before the 2 seconds have elapsed, you should see the digit *5*, but then when the time is greater than 2 seconds, the value printed to the screen is *0*. What we have done here is used the fact that when *t* is less than 2, the statement is evaluated as true which is mathematically equivalent to 1. Once *t* is larger than 2, the conditional statement is evaluated as false which is mathematically equivalent to 0.

Multiplying a force with a conditional statement can allow us to "turn on" or "turn off" a force based on a condition - in this case the condition that time is less than 2 seconds. Change the line of code for *F1* so that it now looks like this:

```python
F1 = vec(10, 0) * (t < 2)
print(F1)
```

Now play the simulation and you should see that the rocket accelerates for 2 seconds, and then after that, it moves at a constant velocity. Look at the graph to verify that this is how it behaves. You should see a graph for the X position that shows a curve at the beginning but then it becomes a straight line with an unchanging slope:

<figure><img src="https://2165864134-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F-LCBQtB7AkKJtVQIbOdo%2Fuploads%2FKSMWOivc5MYijvnAUxSH%2Frocket_position_graph.png?alt=media&#x26;token=0f3919c2-975b-4ed5-b394-e99870e628a5" alt=""><figcaption></figcaption></figure>

We now have a way to model a force acting on an object such that it stops after a specified amount of time.

### Logical Operators

In the example above the force exists until two seconds into the simulation and then it becomes zero forever afterward. What if we wanted a force to exist between two times?

We can actually set a condition for an interval by using what is known as a **logical operator**. A logical operator allows you to combine conditions. So for example you might want the force to act on the object after 3 seconds AND before 5 seconds. This is done by using the keyword *and*.

Let's define a second force that will exist during this interval:

```python
F2 = vec(-10, 10) * ((t > 3) and (t < 5))
```

Notice that we added another conditional statement *(t < 5)* after the logical operator *and*. It is important that you use another set of parentheses around both conditional statements. We now need to change the net force calculation:

```python
Fnet = F1 + F2
```

When you start the simulation, you should see that after three seconds, a different force is applied on the object and then it disappears after 5 seconds.

Another logical operator that can be used is the logical *or*. This can be used to define two different conditions that are exclusive. For example we could say that the force exists on the object before 2 seconds OR after 5 seconds. Let's change the code that defines *F1*:

```python
F1 = vec(10, 0) * ((t < 2) or (t > 5))
```

Now when you run the simulation, you can see that the object is once again acted on by *F1* after 5 seconds.

You can even combine logical operators as long as you use parentheses like this:

```python
F1 = vec(10, 0) * ((t < 2) or ((t > 5) and (t < 7)))
```

Now when you run the simulation, you should see that *F1* now acts on the object from 0 to 2 seconds, and then again between 5 seconds and 7 seconds.

The above conditional value could also be achieved using this conditional statement if you prefer:

```python
if ((t < 2) or ((t > 5) and (t < 7))):
    F1 = vec(10, 0)
else:
    F1 = vec(0,0)
```

## Aside: Turning The Rocket!

There is a way to get the rocket to turn in the direction that it is headed. There is a function that can be used called `rotate`. If we want the rocket to turn a certain number of degrees, we simply write:

```python
rocket.rotate(radians(-90))
```

If want it to turn the direction of its own velocity, we use a different function called `direction` which returns the direction in radians for a vector. Combining the two like this:

```
rocket.rotate(direction(rocket.v) - radians(90))
```

For this example, I had to turn the rocket by -90 degrees, so you will have to do that as well.

### Other Conditions

You can use a conditional in many ways. So far we have seen how you could use it to control *when* a force is being applied, but you could also use it to define *where* a force is applied. For example, what if we wanted to simulate a ball moving across a table, but once it reached the end of the table, it behaved like a projectile.

Look at the simulation below:

[Demo: Ball Rolling Off A Table](https://www.tychos.org/en/scenarios/ndpW5S)

When you play the simulation, the ball continues to travel in a straight path off our virtual table, and floats! In this simulation, the normal force continues to act on the ball after it has left the table. What we really want to do is make the normal force disappear once the ball reaches the end of the table. We can easily fix this with a conditional. Notice that the table edge is located at X = 50.  Open the **Calculations** pane and change this line of code:

```python
Fn = -Fg
```

To this:

```python
Fn = -Fg * (ball.pos.x < 50)
```

When you play the simulation, you should see that when the ball reaches the table's end, it begins to move like a projectile!

This demonstrates that we can control the forces acting on a particle by conditionally changing the force based on a time interval or where the object is.

## Conclusion

This was a brief but important tutorial on how to simulate forces that exist conditionally. The actual programming concept is what is known as a conditional statement.

Here are the basic steps of defining a conditional force:

1. Define a force using a conditional statement:.

   ```python
   if t > 3:
       F1 = vec(10 , 0)
   else:
       F1 = vec(0,0)
   ```
2. Or you can simplify this if the force just disappears using a conditional as an operator. Multiply the force with conditional statement using one of the **comparison operators** above (<, >, !=, ==, etc.)

   ```python
   F1 = vec(10, 0) * (t > 3)
   ```
3. Use a logical operator to define multiple conditions:<br>

   ```python
   F1 = vec(10, 0) * ((t > 3) and (t < 5))
   ```
4. Define a net force that is just the sum of all fores acting on the object. This way you can combine more than one conditional force.

   ```python
   Fnet = F1 + F2
   ```
5. Use the same method that we have used (the Momentum Principle!) to update the particle's velocity, and then its position.


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://docs.tychos.org/docs/for-teachers/tutorials-python/lesson-9-conditional-forces.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
