Jump to content

Recommended Posts

Just now, Shpaget said:

Having near exactly the same names (as in with the only difference being the upper or lower case) will lead to confusion and usage of the wrong one, which will result in unexpected behavior that can be very difficult to debug.

Fair enough I may add a "II" to the second one like I did with my other vars

Link to comment
Share on other sites

5 hours ago, Cheif Operations Director said:

3.a. How will it know if I want it to be if var==True of var==False

Checking for True boolean:

if var:

   ...

Checking for False boolean:

if not var:

   ...
Quote

3.c. I will make the underscore change but I will not remove the Capital as I intend to have a "soft" abort function by the same name that will not destroy the whole rocket but just the part I need it too. ( I can not do this until the rocket is built because I need to know more about the rocket itself)

As @Shpaget mentions, if you have two abort functions, call them something like hard_abort and soft_abort; depending on subtle casing differences will be a recipe for long nights of painful debugging later on.

Link to comment
Share on other sites

On 6/26/2019 at 11:25 PM, Cheif Operations Director said:

First... I checked multiple times and did not get notifications weird.
@Shpaget

I tried that and it did not work correctly


T=10000
x2=0
if T>x2:
    a = [1, 300]
    
if a==300:
     print("hello")
if a==1:
    print("hello")

 

[1,300] is a list.  It is not a number.

if a[0]==1:
   print("True\n")
if  a[1]==300:
    print("True\n")

will print:

True
True

If you really want it to work on either case, try something like:

For i in a:
    if i==300:
      print("hello from 300\n")
    if i==1:
      print("hello from 1\n")

and you should get (but don't cut and paste due my issues trying to type into the fora's silly single space typing difficulties):

hello from 300
hello from 1

#note that I'm still using Python 2.x, I don't really know if you still need the \n linefeeds in Python 3.  I did fix the print functions for Python 3 (you didn't need the parentheses for python 1/2).



 


 

Link to comment
Share on other sites

7 hours ago, Kerbart said:

Checking for True boolean:




if var:

   ...

Checking for False boolean:


if not var:

   ...

As @Shpaget mentions, if you have two abort functions, call them something like hard_abort and soft_abort; depending on subtle casing differences will be a recipe for long nights of painful debugging later on.

1 & 2 nice and thanks

3 yea I suppose so

Link to comment
Share on other sites

If I set up a while loop and make it dependent on a variable it will always check to make sure that this variable is "true". Can I make the determination of truth based on another while loop? I'm asking this because I'm trying to make my code now determined based off of altitude and not time. The altitude is determined by some code in the flightcomputer function that multiplies 1 x 2 each time it cycles through. The flight computer is a while loop that is activate by the statement flight_computer_call =True If it is false it stops working (as it should). I know that someone brought up that a while loop runs until the code is no longer fulfilled. Is this causing the problem? It should still be referencing back to the code that sent the call for the function though to determine if the requirements are still met. As a note when I add the return altitude line to my flight computer function I can no longer change the value of altitude. If anyone has an ideas but needs the full code you can find it in the hidden box thing.

while 0<=altitude<=100:
        INFLIGHTVAR=True
        INFLIGHTVARII=False
        flight_computer_call=True
        if altitude>=100 or altitude<=0:
            flight_computer_call=False
        flightcomputer(0,0,0,1,1,1,1,1,1)
    print("---------------------------------------------1")
Spoiler

#Constant Variables
#most but not all sections marked as print will interface with electrical outlets to
#trigger events in the rocket.  





#global variables

#--------------------Altitude numbers in meters/ Other units most likley in metric
global FTminx
global FTmaxx
global FTminy
global FTmaxy
global FTminz
global FTmaxz
global EASLES2
global FLIGHTVAR
global FLIGHTVARII
global INFLIGHTVAR         
global ACTIVATELAUNCHSEQUENCEII      
global LOCKOUT_ON_NO_LAUNCH_YET
global altitude              
global flight_computer_call       
global truetool                              
#variables
NFP=20
FTminx=-0.1
FTmaxx=0.1
FTminy=-0.1
FTmaxy=0.1
FTminz=-0.1
FTmaxz=0.1
minangletolerance=20
maxangletolerance=340
FLIGHTVAR=0
FLIGHTVARII=1
EASLES2=True
INFLIGHTVAR=True
INFLIGHTVARII=False
ACTIVATELAUNCHSEQUENCEII=False
LOCKOUT_ON_NOFLIGHT=False
flight_computer_call=False
truetool=True
altitude=1
T1=2
a=0
#---------------Import Section
import time
import timeit
#--------------Class Section
#--------------Functions
#---Math
def addition (x,y):
        add = x+y
        print(add)
def subtraction (x,y):
        sub = x-y
        print(sub)
def multiplication (x,y):
        mult = x*y
        print(mult)
def division (x,y):
        div = x/y
        print(div)
def checksen2():
    pass    
#---Engine Control
def RME(A5):
    if A5>0:
        print("Activate Engine")
#------- Testing Simulators to be removed for actual flight software
        
#--------------------------------------------------------------------
def calibrategyroscopes():
    #do stuff
    print("pending code")
    
def Parachute_Activation_Stage_One(altitude):
    if altitude>=4:
        print("Fire_Safety_Pyro_Charges_to_release_parachute")
    elif altitude<4:
        print("Safety... No_Release_of_parachute")
    
def coursecorrectionxp():
    print("coursecorrection x to the positive")
def coursecorrectionxn():
    print("coursecorrection x to the negative")
def coursecorrectionyp():
    print("coursecorrection y to the positive")
def coursecorrectionyn():
    print("coursecorrection y to the negative")
def coursecorrectionzp():
    print("coursecorrection z to the positive")
def coursecorrectionzn():
    print("coursecorrection z to the negative")

def Emergencyabortfunction():
        while EASLES2==True:
            EASLES=1
            if EASLES>0:
                print("Place_Holder_to_detonate_all_stages_and_all_charges")
                time.sleep(4)
                print("Fire_Safety_Pyro_Charges_to_release_parachute_")
                EASLES = False
#---------------Flight Code Section primary
#-------------------------------------------------Note to self remove altitude var in final product
def flightcomputer(gx,gy,gz,c1,c2,c3,c4,interval,altitude):
   while flight_computer_call==True:
        time.sleep(interval)
#Gyro x axis
        if truetool==True:
            if FTminx<gx<FTmaxx:
                print("On course no adjustment needed (x)")
            elif FTminx>gx:
                print("Course Correction to the Negative (x)")
                coursecorrectionxn()
            elif FTmaxx<gx:
                print("Course Correction to the Positive (x)")
                coursecorrectionxp()
            #--- 
            if INFLIGHTVARII==True:
                if FLIGHTVAR>FLIGHTVARII:
                    if gx<minangletolerance or gx>maxangletolerance:
                        print("safe destruction x ")
                        Emergencyabortfunction()            
            #---
            if INFLIGHTVAR==True:
                if gx>minangletolerance and gx<maxangletolerance:
                    print("safe destruction x ")
                    Emergencyabortfunction()
            elif gx<0:
                print("safe destruction x ")
                Emergencyabortfunction()
#Gyro y axis
        if truetool==True:
            if FTminy<gy<FTmaxy:
                print("On course no adjustment needed (y)")
            elif FTminy>gy:
                print("Course Correction to the Negative (y)")
                coursecorrectionyn()
            elif FTmaxy<gy:
                print("Course Correction to the Positive (y)")
                coursecorrectionyp()
            #---
            if INFLIGHTVARII==True:
                if FLIGHTVAR>FLIGHTVARII:
                    if gy<minangletolerance or gy>maxangletolerance:
                        print("safe destruction y ")
                        Emergencyabortfunction()
            #---
            
            if INFLIGHTVAR==True:
                if gy>minangletolerance and gy<maxangletolerance:
                    print("safe destruction y ")
                    Emergencyabortfunction()
            elif gy<0:
                print("safe destruction y ")
                Emergencyabortfunction()  
#gyro z axis
        if truetool==True:
            if FTminz<gx<FTmaxz:
                print("On course no adjustment needed (z)")
            elif FTminz>gz:
                print("Course Correction to the Negative (z)")
                coursecorrectionzn()
            elif FTmaxz<gz:
                print("Course Correction to the Positive (z)")
                coursecorrectionzp()
            #---
            if INFLIGHTVARII==True:
                if FLIGHTVAR>FLIGHTVARII:
                    if gz<minangletolerance or gz>maxangletolerance:
                        print("safe destruction z ")
                        Emergencyabortfunction()
           #---
            if INFLIGHTVAR==True:
                if gz>minangletolerance and gz<maxangletolerance:
                    print("safe destruction z ")
                    Emergencyabortfunction()
            elif gz<0:
                print("safe destruction z ")
                Emergencyabortfunction()
#-------Sensor code    
        if truetool==True:
            if c1 > a:
                print("Activate Response 1") 
                print("The Value of Voltage +", c1)
                #Open RCS Valve Code
            elif c1==0:
                print("No Excessive Aerodynamic Forces sensor1")
                pass
#---Sensor 2
        if truetool==True:
            if c2 > a:
                print("Activate Response 2") 
                print("The Value of Voltage +", c2)
                #Open RCS Valve Code
            elif c2==0:
                print("No Excessive Aerodynamic Forces sensor2")
                pass
#---Sensor 3
        if truetool==True:
            if c3 > a:
                print("Activate Response 3") 
                print("The Value of Voltage +", c3)
                #Open RCS Valve Code
            elif c3==0:
                print("No Excessive Aerodynamic Forces sensor3")
                pass
#---Sensor 4
        if truetool==True:
            if c4 > a:
                print("Activate Response 4") 
                print("The Value of Voltage +", c4)
                #Open RCS Valve Code
            elif c4==0:
                print("No Excessive Aerodynamic Forces sensor4")
                pass
 #--------------------------------------temporary code for simulating flight charachteristics
        if truetool==True:
            altitude=altitude * 2
            print(altitude)
        return altitude
        
#---------------Flight Operations Section
ACTIVATELAUNCHSEQUENCE=1

if ACTIVATELAUNCHSEQUENCE>0:
    ACTIVATELAUNCHSEQUENCEII=True
    
while ACTIVATELAUNCHSEQUENCEII==True:
    time.sleep(1)
    print("Liftoff")
#---Engine Ignition
    RME(2)
#---first turn event
    while 0<=altitude<=100:
        INFLIGHTVAR=True
        INFLIGHTVARII=False
        flight_computer_call=True
        flightcomputer(0,0,0,1,1,1,1,20,1)
    if 0>=altitude>=100:
        flight_computer_call=False
    print("---------------------------------------------1")
    
#------------------------------------Everything beneath this does not work-----------------------------------------------# 
    #---second turn event
    while 100<=altitude<=609.6:
        FTminx=FTminx + 20
        FTmaxx=FTmaxx + 21
        FTminy=FTminy + 20
        FTmaxy=FTmaxy + 21
        FTminz=FTminz + 20
        FTmaxz=FTmaxz + 21
        minangletolerance=minangletolerance + 20
        maxangletolerance=maxangletolerance + 20
        FLIGHTVAR=0
        FLIGHTVARII=1
        INFLIGHTVAR=True
        INFLIGHTVARII=False
        flight_computer_call=True
        flightcomputer(20,20,20,1,1,1,1,1,altitude)
    print("---------------------------------------------2")
    #---third turn event
    while 609.6<=altitude<=1828.8:
        FTminx=FTminx + 70
        FTmaxx=FTmaxx + 71
        FTminy=FTminy + 70
        FTmaxy=FTmaxy + 71
        FTminz=FTminz + 70
        FTmaxz=FTmaxz + 71
        minangletolerance=minangletolerance + 50
        maxangletolerance=maxangletolerance -250
        FLIGHTVAR=1
        FLIGHTVARII=0
        INFLIGHTVAR=False
        INFLIGHTVARII=True
        flight_computer_call=True
        flightcomputer(90,90,90,1,1,1,1,1,altitude)
    print("---------------------------------------------3")
    #---parachute release 
    time.sleep (1)
        #---
        #altitude=16
        #---
    Parachute_Activation_Stage_One(altitude)
    time.sleep(2)
    ACTIVATELAUNCHSEQUENCEII=False
    LOCKOUT_ON_NOFLIGHT=True
#-------
if LOCKOUT_ON_NOFLIGHT==False:
    while ACTIVATELAUNCHSEQUENCEII==False:
        print("No Launch Yet")

 

 

Edited by Cheif Operations Director
trying to debug code right now so I changed the code in the box so it was up to date
Link to comment
Share on other sites

I have tried to debug this for a few hours now and I am at a loss. I have simplified it down to the point where it will run in real life (I think) but not simulated. I need one thing to happen. Basically in the flight computer while loop it changes the value of the simulated altitude from 1 to 128 ( as it is supposed to) however when I tell the same while loop to return altitude it returns 1 and not 128. It should have changed to 128 as the that now the value of the variable. Im sure im making a dumb mistake somewhere on the math. I think this will work in real life however because the sensor will be directly imputing the altitude into the sensors for the computer to do its work. The problem here is with the simulator. I need the simulator to test if the rest of the code will work the way I want it too.

 

Link to comment
Share on other sites

Why the insistence on so many while loops?

In order to exit a while loop, you need to satisfy the condition from inside that while loop, since no other while loop is running parallel.

while a == 1
	twiddleFingers()
	rollEyes()
	
while b == 3
	CheckTheValueOfa()

This will never exit the first loop since you never check if a changed to something other than 1. The program is stuck inside the first loop and has no way of exiting and advancing to any other piece of code (assuming that finger twiddling and eye rolling doesn't check the value of a). Moving the CheckTheValueOfa() function inside the first loop will make sure it will exit once a is no longer 1.

Link to comment
Share on other sites

45 minutes ago, Shpaget said:

Why the insistence on so many while loops?

In order to exit a while loop, you need to satisfy the condition from inside that while loop, since no other while loop is running parallel.




while a == 1
	twiddleFingers()
	rollEyes()
	
while b == 3
	CheckTheValueOfa()

This will never exit the first loop since you never check if a changed to something other than 1. The program is stuck inside the first loop and has no way of exiting and advancing to any other piece of code (assuming that finger twiddling and eye rolling doesn't check the value of a). Moving the CheckTheValueOfa() function inside the first loop will make sure it will exit once a is no longer 1.

I ditched that system in some regard because I did not get what has happening. However That is really not what I did. This would be more accurate.

 

def rolleyes(x)
	while x<100
  		print("reading a newspaper")
    	#Code that counts up too 100
      	if x>100
        	y=False

while y=True
	rolleyes(1)

 

Edited by Cheif Operations Director
Link to comment
Share on other sites

This is the problem im having. If you run this program It will only temporarily change the value of x. I  need to convince the program that the new value (200) is now the new value across the board 


global x
x=0

def function1(x):
    print(x)
    x=x+200
    print(x)
    
    

function1(x)
print("-----------------------")
print(x)

 

Edited by Cheif Operations Director
Link to comment
Share on other sites

Hopefully that will help with reinforcing why it's important to be careful with variable and function names.

As for the funness of the bug, it is a nice one.

Edited by Shpaget
Link to comment
Share on other sites

Some will say that introducing globals to solve certain issues with the way code is structured is a bad idea, but they probably never ran into a challenge like this.

Still, the tendency to introduce Heisenbugs into your code is a reason to avoid it as much as possible.

Link to comment
Share on other sites

If using globals, it's a good idea to make sure the name isn't reused, usually by having a prefix of some kind.  Many people use an underscore in c#, I'm not familiar enough with python coding to make any suggestions beyond this

Edited by linuxgurugamer
Link to comment
Share on other sites

11 hours ago, Kerbart said:

Some will say that introducing globals to solve certain issues with the way code is structured is a bad idea, but they probably never ran into a challenge like this.

Still, the tendency to introduce Heisenbugs into your code is a reason to avoid it as much as possible.

Do you have a different solution in mind? 

Link to comment
Share on other sites

3 hours ago, Cheif Operations Director said:

Do you have a different solution in mind? 

There's a couple of solutions, depending on what does cryptic (*cough*) variable names represent. If these are flight parameters representing values to be shared between various functions, you could pass them along through a dictionary like this:

def main():
  flight_data = {x: 0, y: 0, total_mass: 0, t=0.0}
  pre_flight(flight_data) # initialize flight data
  lift_off(flight_data)
  grav_roll(flight_data)
  coast(flight_data)
  circularize(flight_data)

Some will argue that it's hardly better than global data, or that it's only semantically different from global data, but at least you're aware of where the data resides. And it's easier to scale. Perhaps an in-flight calculation needs data that is retrieved from simulating 5s of flight. Now you can, using cloned flight data; with one set of global variables you cannot.

One step further would be to create a class for your flight data, which can also take care of some of the recurring data processing. I'm making stuff up as I go along here, but something like this:

def main():
  fd = FlightData(0.0, 0.0, 200.0)
  pre_flight(fd)
  lift_off(fd)
  # etc
  
class FlightData:
  def __init__(self, x, y, mass):
    self.x = x
    self.y = y
    self.mass = mass
    
  def apply_velocity(self, v, t):
    '''Apply velocity vector v for t seconds'''
    self.x += v.x * t
    self.y += v.y * t

You could then even take it a step further and have a RocketShip class:

class RocketShip:
  def __init__(self, name):
	self.name = name
	self.flight_data = FlightData(0.0, 0.0, 200.0)
    
  def lift_off(self):
    while self.flight_data.y <= 200:
      # do lift-off stuff
      ...

And now your main code would look something like this:

def main():
  rs_cheif = RocketShip("Cheif's rocket ship")
  rs_cheif.lift_off()
  rs_cheif.grav_roll()
  # etc

Instead of having one big monolithic block of code, everything is compartimentalized which makes fixing issues a lot simpler.

Edited by Kerbart
Link to comment
Share on other sites

On ‎7‎/‎2‎/‎2019 at 9:46 PM, Kerbart said:

Some will argue that it's hardly better than global data, or that it's only semantically different from global data, but at least you're aware of where the data resides. And it's easier to scale. Perhaps an in-flight calculation needs data that is retrieved from simulating 5s of flight. Now you can, using cloned flight data; with one set of global variables you cannot.

One step further would be to create a class for your flight data, which can also take care of some of the recurring data processing. I'm making stuff up as I go along here, but something like this:

Why could I not just say in pseudo code. Then I can clone this flight data and manipulate it right? 

 

global x
x = 1

x = y

 

On ‎7‎/‎2‎/‎2019 at 9:46 PM, Kerbart said:

def main(): flight_data = {x: 0, y: 0, total_mass: 0, t=0.0}

Does this mean that x equals 0, y = ), total_mass = 0?

Sorry for taking so long too reply. An another note do you have any knowledge on getting "ports" to activate according to the code so I an interface this with my rocket? I saw some python robotics stuff on yotube so their has to be some libraries for it right? I did not find any in the actual libraries list however.

Link to comment
Share on other sites

12 hours ago, Cheif Operations Director said:

Why could I not just say in pseudo code. Then I can clone this flight data and manipulate it right? 

One of the nice things about Python is that the code tends to be so clean and simple that there's really no gain in using pseudo code. That's why you will hardly find any pseudo code in books of Python programming; what's the point?

12 hours ago, Cheif Operations Director said:

Does this mean that x equals 0, y = ), total_mass = 0?

Yes, but I made a mistake there (rushed, using iPad to enter code, etc). Inside the dictionary you use labels as keys, so it would be:

flight_data = {'x': 0, 'y': 0, 'mass': 0.0}

At that point you can refer to them as indexed values, but instead of a numeric index, you can use the labels:

print(flight_data['x'])
print(flight_data['y'])

For brevity you could shorten flight_data to fd, and create constants for the labels at the top of your code

X = 'x coord' # allowing for more elaborate descriptions
Y = 'y coord'
MASS = 'mass'
VX = 'x velocity'

# ---------
# some code
# ---------

fd = {X: 0.0, Y: 0.0, MASS: 200.0}

# --------------
# even more code
# --------------

print(fd[MASS])

Python doesn't really have explicit constants, but a common practice is to write them in capitals, to indicate that you're not changing them. "But wait," you say, "aren't those effectively the global variables you were trying to avoid?" Technically, yes. But remember that the main issue with globals is that they're being changed when you don't expect it. These are constants. They don't change. So you're not breaking "rules" (good practice, really) with them.

12 hours ago, Cheif Operations Director said:

Sorry for taking so long too reply. An another note do you have any knowledge on getting "ports" to activate according to the code so I an interface this with my rocket? I saw some python robotics stuff on yotube so their has to be some libraries for it right? I did not find any in the actual libraries list however.

Check out adafruit.com  - they sell all kinds of little circuit boards that run Python. Their Circuit Playground Express for instance comes with a ton of input and output ports, leds, sensors, and easy ways to interact with them. It runs a special verson of Python called Circuit Python which in itself is a fork from micropython, a Python build intended to run on embedded systems. Adafruit is now even equipping Arduino's (what, eventually, is what you probably want to use to control your rocket) with Circuit Python. The Adafruit website has a forum and tons of examples on how to make their circuit boards interact with other hardware.

Link to comment
Share on other sites

26 minutes ago, Kerbart said:

One of the nice things about Python is that the code tends to be so clean and simple that there's really no gain in using pseudo code. That's why you will hardly find any pseudo code in books of Python programming; what's the point?

I have frankly no idea what I was trying to utter in that sentence. :)

31 minutes ago, Kerbart said:

Yes, but I made a mistake there (rushed, using iPad to enter code, etc). Inside the dictionary you use labels as keys, so it would be:




flight_data = {'x': 0, 'y': 0, 'mass': 0.0}

At that point you can refer to them as indexed values, but instead of a numeric index, you can use the labels:

why bother with the ' ' s? When I do not use them I get an undefined message HOWEVER it still runs the same 
flight_data = {x: 5, 'y': 0, 'mass': 0.0}
print(flight_data[x])

This does not work and im not sure why


flight_data = {x: 5, 'y': 0, 'mass': 0.0}
print(flight_data[x])
x = x + 5
print(flight_data[x])

 

37 minutes ago, Kerbart said:

Technically, yes. But remember that the main issue with globals is that they're being changed when you don't expect it. These are constants. They don't change. So you're not breaking "rules" (good practice, really) with them.

How are they being changed unless I tell them to be changed. I can change these constants in the same way I change a global variable. 

Link to comment
Share on other sites

1 hour ago, Kerbart said:

Check out adafruit.com  - they sell all kinds of little circuit boards that run Python. Their Circuit Playground Express for instance comes with a ton of input and output ports, leds, sensors, and easy ways to interact with them. It runs a special verson of Python called Circuit Python which in itself is a fork from micropython, a Python build intended to run on embedded systems. Adafruit is now even equipping Arduino's (what, eventually, is what you probably want to use to control your rocket) with Circuit Python. The Adafruit website has a forum and tons of examples on how to make their circuit boards interact with other hardware.

I checked out Adafruit before and they seem pretty good. I found this sensor which I think will do the trick https://www.adafruit.com/product/2472#description-anchor

I still need to do a little more looking around first though to ensure I am right

Link to comment
Share on other sites

1 hour ago, Cheif Operations Director said:

I have frankly no idea what I was trying to utter in that sentence. :)

why bother with the ' ' s? When I do not use them I get an undefined message HOWEVER it still runs the same 
flight_data = {x: 5, 'y': 0, 'mass': 0.0}
print(flight_data[x])

This does not work and im not sure why



flight_data = {x: 5, 'y': 0, 'mass': 0.0}
print(flight_data[x])
x = x + 5
print(flight_data[x])

 

How are they being changed unless I tell them to be changed. I can change these constants in the same way I change a global variable. 

The dictionary is a list of values, just like [1, 2, 3]. But instead of referring to them by position df[0], df[1]. df[2], you refer to them by name. Names suggest text (although dictionary keys can be numeric as well) and text needs to be enclosed in quotes to differentiate it from code.

df = {x: 100. y: 200}

This would create a dictionary with keys of the values of variable x and y. So if x=5 and y=0, what you're really doing is:

df = {5: 100, 0: 200}

If now, somewhere in your code x gets another value (x=6) your code will run into problems:

print(df[x])

Now really means df[6], and that is not defined in the dictionary. Aside from that, what you really want is something like this:

df = {'value of x': 100, 'value of y': 200}

# but that is a lot of typing
# so instead we use shorthand names:

df = {'x': 100, 'y': 200}

There are better ways - using classes - but I'd focus on the dictionaries for now. they get you results quicker.

Link to comment
Share on other sites

3 minutes ago, Kerbart said:

The dictionary is a list of values, just like [1, 2, 3]. But instead of referring to them by position df[0], df[1]. df[2], you refer to them by name. Names suggest text (although dictionary keys can be numeric as well) and text needs to be enclosed in quotes to differentiate it from code.




df = {x: 100. y: 200}

This would create a dictionary with keys of the values of variable x and y. So if x=5 and y=0, what you're really doing is:




df = {5: 100, 0: 200}

If now, somewhere in your code x gets another value (x=6) your code will run into problems:




print(df[x])

Now really means df[6], and that is not defined in the dictionary. Aside from that, what you really want is something like this:




df = {'value of x': 100, 'value of y': 200}

# but that is a lot of typing
# so instead we use shorthand names:

df = {'x': 100, 'y': 200}

There are better ways - using classes - but I'd focus on the dictionaries for now. they get you results quicker.

Is x a string or is x a variable? it looks like a string

Link to comment
Share on other sites

1 minute ago, Cheif Operations Director said:

Is x a string or is x a variable? it looks like a string

You are correct. it's a string. look at it like label for a value, or what it really is - a key in a lookup table.

Link to comment
Share on other sites

3 minutes ago, Cheif Operations Director said:

ok but it needs to be a variable right?

No. The dictionary (let's name if fd for flightdata) is the variable. (Python pro's spare me the flaming I know we're mangling semantics here), but it helps you in reducing the number of variables you'd have to pass around (or to bypass that define as globals).

So instead of:

x = 100
y = 200
mass = 350

(and many more like those) you do:

fd = {'x': 100, 'y': 200, 'mass': 350}

And instead of doing print(x) you now do print(fd['x']) - but in return for that little extra typing you only have to pass one variable around, that holds all your flight data values - accessible through keys that are defined as readable strings

Link to comment
Share on other sites

This thread is quite old. Please consider starting a new thread rather than reviving this one.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.
Note: Your post will require moderator approval before it will be visible.

Guest
Reply to this topic...

×   Pasted as rich text.   Paste as plain text instead

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...