#๐Ÿ”’ Need help with if/else in a while loop as well as a def that will break out of the app.

205 messages ยท Page 1 of 1 (latest)

hot ravenBOT
#

@rigid laurel

Python help channel opened

Remember to:

  • Ask your Python question, not if you can ask or if there's an expert who can help.
  • Show a code sample as text (rather than a screenshot) and the error message, if you've got one.
  • Explain what you expect to happen and what actually happens.

:warning: Do not pip install anything that isn't related to your question, especially if asked to over DMs.

rigid laurel
#

my issues are with def exit() "this i think i need to rename to ext or something else as exit is a command.

#

my second issue is with the If else statement in the main loop, I can get it to change states one time, and correctly output the txt for that state, however after that it will no longer change, if i change the varable.

#

Thanks!

lofty trail
#

could you send your code please

#

and I'll have a look

#

Yeah there's already a built in function called exit() which might be causing you issues

rigid laurel
#

I think I did notice that earlier, and changed it to no effect....either way im trying to figure out how to paste in the code with the discord tool thing

lofty trail
#

!paste

hot ravenBOT
#
Pasting large amounts of code

If your code is too long to fit in a codeblock in Discord, you can paste your code here:
https://paste.pythondiscord.com/

After pasting your code, save it by clicking the Paste! button in the bottom left, or by pressing CTRL + S. After doing that, you will be navigated to the new paste's page. Copy the URL and post it here so others can see it.

lofty trail
#

Follow this link, paste the code in, and there should be a save button somewhere

rigid laurel
#

doing that now thanks

lofty trail
#

Then share the link that it generates in your address bar

rigid laurel
#

not sure if that is the correct link

lofty trail
#

yep that works

rigid laurel
#

cool, yeah im pretty new to using discord for code related stuff

lofty trail
#

so whats the problem

rigid laurel
#

2 things, 1 the ext() function dosnt work

#

and the HV_EN() will only correctly use the if/else statement once, and wont toggle on and off

lofty trail
#

okay lets do the exit first

#

you don't actually do anything with the users input once they tell you if they want to quit or not

#

rename the exit function, because there is already a python function called exit()

rigid laurel
#

i did

#

def ext():
prog = input("Would you like to EXIT? (1)YES (2)NO\n")
print("\tEnding Program\n")
time.sleep(2)
return prog

hot ravenBOT
#

Hey @rigid laurel!

It looks like you're trying to paste code into this channel.

Discord has support for Markdown, which allows you to post code with full syntax highlighting. Please use these whenever you paste code, as this helps improve the legibility and makes it easier for us to help you.

To do this, use the following method:
```py
print('Hello, world!')
```

This will result in the following:

print('Hello, world!')```
You can **edit your original message** to correct your code block.
lofty trail
#

mkay

rigid laurel
#

ok so am I not taking the input, and returning that to the prog var?

lofty trail
#

you're taking input, but not doing anything with it

#

line 21

#

the prog variable

#

what if they say "no"?

#

If they say yes, then you should call the exit() or quit() function to stop the program

rigid laurel
#

so returning that var out of the function to make the while loop false is not the correct way?

lofty trail
#

oh yes you could do that also

#

that would also work

#

but just returning the variable doesn't do anything right now

rigid laurel
#

that is what im doing there, and unless im doing it wrong something is funky

lofty trail
#

oh wait my bad...

#

hmmm

#

oh it's the wrong equals

#

== for comparison, = for assignment

rigid laurel
#

err ok lemmy try that

lofty trail
#

I didn't notice you assigning it inside of the while loop

rigid laurel
#

so the while loop needs the single = correct

lofty trail
#

on line 70

rigid laurel
#

ok

lofty trail
#

for the assignment of variables, it should be =

#

== for comparison. "Is this equal to this?"

rigid laurel
#

IDLE dosnt like that

lofty trail
#

= for assignments. "This variable is now equal to this value"

rigid laurel
#

its saying i need to do something else

lofty trail
#

whats it saying

rigid laurel
#

syntax error

lofty trail
#

lemme see

rigid laurel
lofty trail
#

send what you wrote

#

what ide are you using

#

what code editor]

rigid laurel
#

its IDLE

lofty trail
#

doesn't it give you a traceback?

#

Can you show me that line?

rigid laurel
lofty trail
#

Okay one more time. When you are checking if two things are equal to each other, you should use ==

#

when you want to make a variable equal to a value, it's one =

#

How come you changed that line with HV_state?

#

line 48 ^

rigid laurel
#

thats line 48, sorry IDLE kinda sucks I should prob be using Note++

#

i cant see line numbers

lofty trail
#

note++ also isn't meant for development, I don't recommend it

rigid laurel
#

ahh fair enough

lofty trail
#

anyway, you have the wrong = there

rigid laurel
#

so the whole Optoins choice area works fine...the == is correct as its sets opt to whatever functions i want to run

#

the function runs, however it doesnt exit the application...it just restarts the loop

lofty trail
#

Did you change line 70?

rigid laurel
#

so that works, however it dosnt give me the option not to exit, in case of a accident menu action

lofty trail
#

that's because you didn't actually use the user's input

#

on this line

#

what if they say no

rigid laurel
#

correct, what i do not get is Im returning the users imput, however it dosent seem to change the varable prog that should when not 0 break out of the loop

#

it works the same if i pass a 1, or a 2

#

it never actually exits

#

or even tries to

#

as you can see here, I chose 2, and it never passes the var to prog as seen in the BIt state area

outer hedge
#

Can you send your current code?

#

!paste

hot ravenBOT
#
Pasting large amounts of code

If your code is too long to fit in a codeblock in Discord, you can paste your code here:
https://paste.pythondiscord.com/

After pasting your code, save it by clicking the Paste! button in the bottom left, or by pressing CTRL + S. After doing that, you will be navigated to the new paste's page. Copy the URL and post it here so others can see it.

rigid laurel
#

yeah

hot ravenBOT
#
Format-strings

Creating a Python string with your variables using the + operator can be difficult to write and read. F-strings (format-strings) make it easy to insert values into a string. If you put an f in front of the first quote, you can then put Python expressions between curly braces in the string.

>>> snake = "pythons"
>>> number = 21
>>> f"There are {number * 2} {snake} on the plane."
"There are 42 pythons on the plane."

Note that even when you include an expression that isn't a string, like number * 2, Python will convert it to a string for you.

karmic rampart
#

please consider these in the future

#

they are very helpful

outer hedge
#

!e
First as they said on line 70 you're doing prog == ext(), == is for making comparisons, not assigning values:

a = 5
b = 5

print(f"a == b {a==b}")
a == 6
print(f"a == 6 {a}")
a = 6
print(f"a = 6 {a}")
hot ravenBOT
rigid laurel
#

@karmic rampart thanks i will def look at that, but im working with int at the moment...i cant seem to pass the input value to the var causing the while loop to be false

karmic rampart
#
def ext():
    prog = input("Would you like to EXIT? (1)YES (2)NO\n")
    print("\tEnding Program\n")
    time.sleep(2)
    return prog```
#

notice how NO returnds "2"

raw topaz
#

input returns a string

karmic rampart
#

instead of 0

#

yeah "2" != 0

#

which exits the while loop

outer hedge
#
>>> a = input("How old are you: ")
>>> print(type(a))
str
>>> a = int(input("Hold old are you: ")
>>> print(type(a))
int
karmic rampart
#

you will probably need to have some input sanitisation

#

otherwise many errors

outer hedge
#

Additionally if you did correct that to an integer no matter what it will still quit the program, 2 != 0 so the while loop will still quit.

rigid laurel
#

lol ok, are you two in agreeance or debating something...I will need to look through both your responses to understand

outer hedge
karmic rampart
#

since False == 0 could you just return prog == "2"

#

#esoteric-python moment

rigid laurel
#

just curious have either of you run this?

karmic rampart
#

im just eyeballing it as of now

outer hedge
karmic rampart
#

but the fact that there is no input sanitising scares me

outer hedge
karmic rampart
#

yeah

#

alr I gtg sorry

#

cya

rigid laurel
#

@karmic rampart what is sanitising? im about 2 years into my BS in comp sci...with some breaks due to covid and such

#

thanks!

outer hedge
rigid laurel
#

ok so this is not actully taking the input and converting it into an int?

#

the only reason im unclear, is that the other functions i have seem to work, and return the int correctly

rigid laurel
outer hedge
hot ravenBOT
outer hedge
#

@rigid laurel

rigid laurel
#

IDLE v3.12.3

#

I understand the two print statements you have there...one prints 5 as an int because no "" the other as a string because of the ""

outer hedge
rigid laurel
#

ok so in this...the input collected is NOT an int?

outer hedge
#

For example you can input hello and it would work:

***********|Options|***********

1. System Power
2. Door Access
3. High Voltage Enable/Disable
4. Exit

choose an option: 
1

Set System Power to hello
Power Set to hello %





XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
********|SYSTEM STATUS|********

**********|Bit State|**********

(High Voltage) HV_state  = 2
(Power Level)  level     = hello
(While Loop)   prog      = 0
(Door Access)  state     = 0 

**|System Levels and Access|***

::High Voltage Disabled::
System Power level is    = hello
Door Access is           = 0 
rigid laurel
#

thus the returned prog isnt an int?

outer hedge
#

Correct

rigid laurel
#

lol its kinda shitty it works in some places but not others...but thats code i guess

#

i didnt even think to try that

outer hedge
#

One way you could check this would to be to print out type(prog) before returning it:

def ext():
    prog = input("....")
    print("ending programing")
    time.sleep(2)
    print(type(prog))
    return prog
rigid laurel
#

LOL shit

outer hedge
#

!e
So using the int function:

a = "5"
print(type(a), a)
a = int(a)
print(type(a), a)
hot ravenBOT
rigid laurel
#

should I type cast the input in each function to an int...and that would prob solve the issues

#

do that prior to returning it i mean

outer hedge
rigid laurel
#

yeah so im using this menu program to kinda get back in to coding python...I never got deep...but its been a while so all of the stuff you are telling me is prob basic

outer hedge
#

Now this wont fix all of your problems however,
With 2 being your response for no the while loop will still become false as prog will not be equal to zero as it is equal to two.

rigid laurel
#

I guess i always though varx = input, on a input string would always return a int...however thinking about that its a bad assumption

outer hedge
rigid laurel
#

agreed, however Im looking to understand the greater concept vs the fix..so the input you have given me helps not just this but how I keep adding on

#

once this works, im going to tkinter a gui, and make each func a box...etc

#

if i cant get this base code to be very explicit on what its doing the gui will be a hot mess

#

lol

outer hedge
rigid laurel
#

hold on wife is buggin me about stuff...but yes in the end im not looking for someone to give me an answer that fixes the issue, but information that will help me understand what i did wrong so I can make code that is more robust to my own stupididty lol

raw topaz
#

writing a little function to help with the int input might help,

def int_input(prompt):
    while True:
        try:
            return int(input(prompt))
        except ValueError:
            print("Invalid input. Please enter an integer.")
outer hedge
#

The way I'd go about it is make ext return a boolean (true/false), which is what the other person did earlier,

  1. So first lets decide how the ext function should behave with a boolean being returned: The way I'd do it is it would return True if you should exit the program and False if you shouldn't

  2. Now you get the function to return True if the input is 1 using the == operator, so that could be broken down to prog == 1 (inside the ext function) if the user inputs 1 then 1 == 1 is True, if they enter 2 2 != 1 which is False.

Now the function will behave as I described in step 1, but you still need to handle how the value returned by the function behaves in the while loop, there's two main paths you can follow here,

1.1 Make the while loop run regardless of the prog variable, this can be done by using while True: instead of while prog == 0
1.2 Add an additional if statement to check if ext() returned True, and if it does break out of the loop

OR the way I would do it since it preserves the structure of your project this far:

2.1 Add an additional if statement to checking if ext() returned True, if it did set prog to 1 otherwise set it to 0

rigid laurel
#

ahh thanks let me read this

outer hedge
#

Take your time

rigid laurel
#

is a bool, always T/F?

outer hedge
#

Yes

#

!bool

#

ok thats not a command my bad lol

#

!boolean maybe?

rigid laurel
#

LOL i knew it...as i do this so much of my year 1 stuff comes back

outer hedge
#

ok nvm

rigid laurel
#

understand i did start in C, then moved to java

outer hedge
#

but yeah it is always True or False

#

Ah ok

rigid laurel
#

i use python because its more useful in my job right now with software automation

outer hedge
#

Ah

rigid laurel
#

im also an electrical engineer lol

#

but everything I have had to work with in the past 5 years has been software controlled so it just makes sense to learn software

outer hedge
#

Never can hurt to know how to code

rigid laurel
#

well i know it helps in the design process to understand the other side...i cant tell you how many times ive sat down with our programmers and explaned how an the electrical circuit they need to control works and they said...shit...i cant code it this way...ima do this instead lol

#

i started programming by trying to build my own PID loop to control a hex copter...and i can say it crashed a lot...dispite the understanding of the math lol

#

thanks again for the help i know its time intensive unless your extremely adept at the language

outer hedge
outer hedge
rigid laurel
#

i can tell you finding a good mentor in what you want to do is well worth while

#

do you know what the title of principal engineer means?

#

its one short of "fellow"

outer hedge
rigid laurel
#

so usually at any company you have all kinda of random names for engineers

#

software, mech, electrical.

#

principal is almost exclusively for someone who has demonstrated excellence, and in depth comprehension of their field through practical accomplishments

outer hedge
rigid laurel
#

a "quantified" expert

outer hedge
#

ah ok

rigid laurel
#

lol i dont know any that are less than 30+ years in there field currently

#

they are the old guys, who cant recall things off the top of their head, but will 100% find the answer in less than a few hours of going over the details

outer hedge
#

lol definetly cant hurt to have someone like that

rigid laurel
#

yeah where ever you work FIND those guys

#

be there friend, and ask them questions

#

almost to the point unless they reject you to say I would really like to learn X from you

outer hedge
#

Alright will do :D best of luck on your project I gotta go

rigid laurel
#

thanks again ill look over your notes

#

I might ping ya another time ๐Ÿ™‚

outer hedge
hot ravenBOT
#
Python help channel closed

This help channel has been closed and it's no longer possible to send messages here. If your question wasn't answered, feel free to create a new post in #1035199133436354600. To maximize your chances of getting a response, check out this guide on asking good questions.