#๐ 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)
@rigid laurel
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.
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!
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
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
!paste
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.
Follow this link, paste the code in, and there should be a save button somewhere
doing that now thanks
Then share the link that it generates in your address bar
yep that works
cool, yeah im pretty new to using discord for code related stuff
so whats the problem
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
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()
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
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.
mkay
still this applies^
ok so am I not taking the input, and returning that to the prog var?
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
so returning that var out of the function to make the while loop false is not the correct way?
oh yes you could do that also
that would also work
but just returning the variable doesn't do anything right now
that is what im doing there, and unless im doing it wrong something is funky
oh wait my bad...
hmmm
oh it's the wrong equals
== for comparison, = for assignment
err ok lemmy try that
I didn't notice you assigning it inside of the while loop
so the while loop needs the single = correct
on line 70
ok
for the assignment of variables, it should be =
== for comparison. "Is this equal to this?"
IDLE dosnt like that
= for assignments. "This variable is now equal to this value"
its saying i need to do something else
whats it saying
syntax error
lemme see
its IDLE
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 ^
thats line 48, sorry IDLE kinda sucks I should prob be using Note++
i cant see line numbers
note++ also isn't meant for development, I don't recommend it
ahh fair enough
anyway, you have the wrong = there
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
Did you change line 70?
so that works, however it dosnt give me the option not to exit, in case of a accident menu action
that's because you didn't actually use the user's input
on this line
what if they say no
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
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.
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.
!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}")
:white_check_mark: Your 3.12 eval job has completed with return code 0.
001 | a == b True
002 | a == 6 5
003 | a = 6 6
@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
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"
input returns a string
>>> a = input("How old are you: ")
>>> print(type(a))
str
>>> a = int(input("Hold old are you: ")
>>> print(type(a))
int
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.
lol ok, are you two in agreeance or debating something...I will need to look through both your responses to understand
I agree, though I'd leave that for now until the program works as intended with the correct inputs
Agreeing
just curious have either of you run this?
im just eyeballing it as of now
Honestly, no, I will now but the issues I see I'm certain are issues.
but the fact that there is no input sanitising scares me
Should clarify this is still relyingon the fact that the input isn't converted to an integer like I said earlier
@karmic rampart what is sanitising? im about 2 years into my BS in comp sci...with some breaks due to covid and such
thanks!
Basically checking the input the user gives is what it is supposed to be i.e.
a = input("Enter 1 or 2")
if a not in (1, 2):
print("Invalid input")
else:
print("Correct input, the program can proceed")
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
OK that I understand, and i see im not using that for ANY of the inputs
!e
They aren't actually,
print(5)
print("5")
They look the same but aren't, one is a string, one is an integer.
:white_check_mark: Your 3.12 eval job has completed with return code 0.
001 | 5
002 | 5
What are you using to edit your code?
@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 ""
Yes, your code all of those variables you're returning in functions are actually strings, not integers, subsequently they behave differently.
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
thus the returned prog isnt an int?
Correct
lol its kinda shitty it works in some places but not others...but thats code i guess
i didnt even think to try that
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
LOL shit
!e
So using the int function:
a = "5"
print(type(a), a)
a = int(a)
print(type(a), a)
:white_check_mark: Your 3.12 eval job has completed with return code 0.
001 | <class 'str'> 5
002 | <class 'int'> 5
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
That's what I would do, yes, however do know this will throw an error if you enter something that isnt a number, that's what the input sanitization the other person was talking about fixes.
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
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.
I guess i always though varx = input, on a input string would always return a int...however thinking about that its a bad assumption
The simplest way to fix this would be in the Global variables section to set the initial value of prog to 2 and in the while loop change the condition to prog == 2
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
So you want to use a solution that doesn't just solve the problem but solves it a more coherent way?
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
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.")
The way I'd go about it is make ext return a boolean (true/false), which is what the other person did earlier,
-
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
Trueif you should exit the program andFalseif you shouldn't -
Now you get the function to return
Trueif the input is1using the==operator, so that could be broken down toprog == 1(inside the ext function) if the user inputs1then1 == 1is True, if they enter22 != 1which isFalse.
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
ahh thanks let me read this
Take your time
is a bool, always T/F?
LOL i knew it...as i do this so much of my year 1 stuff comes back
ok nvm
understand i did start in C, then moved to java
i use python because its more useful in my job right now with software automation
Ah
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
Never can hurt to know how to code
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
My issue is the opposite of that lol, I understand the programming of stuff but struggle with the math. Albeit I don't know what else I'd expect since I haven't gone to college for this stuff yet lol
NP at all I love helping people and am just waiting a bit for a program I wrote to run so I got nothing better to do.
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"
No, what is it?
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
So basically an expert in the field?
a "quantified" expert
ah ok
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
lol definetly cant hurt to have someone like that
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
Alright will do :D best of luck on your project I gotta go
Alright ๐
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.