Python while loops never ends (on a numworks calculator) [duplicate] - python

This question already has answers here:
Asking the user for input until they give a valid response
(22 answers)
Closed 3 years ago.
Just grabbed a calculator with python integrated (numworks).
I'm writing a python program wich includes a function to check if an input is a number (float).
When i type a proper float number everything goes right, but when an exception is catched here is the behavior:
the except block is run properly
then the while loops restarts, ask my imput again and enter an infite loops and freezes. No time for typing my input again.
I'm not familiar with Python, I'm pretty sure it's a simple syntax thing... But I didn't manage to work it out.
Help would be appreciated!
Here is the code:
# controle de saisie d'un nombre
def inputFloat(text):
ret = ''
while ret is not float:
try:
ret = float(input(text + " (nombre)"))
except ValueError:
print("saisie incorrecte.")
return ret
# test
def test():
print(inputFloat("saisir nombre"))
# affichage du menu
while True:
print("[1] test")
print("[0] quitter")
choix = input("Choisir une fonction:")
if choix == "0":
print("au revoir.")
break
elif choix == "1":
test()
Cheers
PS: infos about the environnement : the calculator uses MicroPython 1.9.4 (source https://www.numworks.com/resources/manual/python/)
Edit
here is the clean working version of the code with all suggestions from you guys.
Pushed it to the calc: works like a charm.
# controle de saisie d'un nombre
def inputFloat(text):
while True:
try:
return float(input(text + " (nombre)"))
except ValueError:
print("saisie incorrecte.")
continue
# test
def test():
print(inputFloat("saisir nombre"))
# affichage du menu
while True:
print("[1] test")
print("[0] quitter")
choix = input("Choisir une fonction:")
if choix == "0":
print("au revoir.")
break
elif choix == "1":
test()
break

I think the simplest way is the following:
def input_float():
while True:
try:
return float(input("Give us a number: "))
except:
print("This is not a number.")
You could also use a recursive version:
def input_float():
try:
return float(input("Give us a number: "))
except:
print("This is not a number.")
return input_float()

Related

Open an image when requested

I'm trying to do a silly little program that will let me open an image given a specific number.
import os
c1= os.startfile('Cat1.PNG')
c2= os.startfile('Cat2.PNG')
c3= os.startfile('Cat3.PNG')
catlist= [c1,c2,c3]
valid= False
def cats(valid):
while not valid:
try:
answer=int(input('Choose a number between 1 and 3'))
valid= True
except ValueError:
print("This is not a number")
if answer >=1 and answer <=3:
print(catlist[answer-1])
else:
print('Wrong value')
del (answer)
cats(valid)
return
cats(valid)
My problem is that my pictures just get all open when I start the program, while I want to open them when I choose a specific number.
The problem with your code is in the part where you assign the os.startfile() function to a variable.
When Python interpreter goes through your code, as soon as it hits the c1= os.startfile('Cat1.PNG') line of code, it executes the command and opens the files immediately.
import os
valid = True
def cats(valid):
while valid:
try:
x = int(input("Enter a number here: "))
valid = False
except ValueError:
print("This is not a number!")
if x == 1:
os.startfile('1.jpg')
elif x == 2:
os.startfile('2.jpg')
elif x == 3:
os.startfile('3.jpg')
else:
print("Wrong value")
valid = True
cats(valid)
There is probably a better and more efficient way to do it, but here is a solution I came up with.

How to avoid "can be undefined" error in Python?

I am trying to make a simple code to input a positive integer in the most accurate way possible. I mention that I am very new to the language.
Here is my code :
while number != None:
try:
while True:
number = int(input("Donnez la longueur de votre liste: "))
if number > 0:
break
except TypeError:
print("Tu doit donner un nombre entier")
The warning I get is number can be Undefined I am not aware of what is the specific situation where number is undefined as the while loop breaks only when number is not None ( means defined according to me ). I’m so grateful for your help. It is a challenging time but you would make it easier.
You can sidestep any warnings with a more idiomatic loop:
while True:
number = input("Donnez la longueur de votre liste: ")
try:
number = int(number)
except ValueError:
print("Tu doit donner un nombre entier")
continue
if number > 0:
break

My variable that I created, is not working inside another function

I am dealing with a NameError at the moment. I have created multiple functions (for a project that I am working on). A variable that I've created, has to be used in multiple functions. I gave this variable as a parameter in all of the other functions and I had no problem at all. A friend of mine has written the menu function, which I have to connect with the functions I have created. I try to give "antwoorden_list" (which is created inside the function 'vragenLijst') as a parameter, because i need to use this variable inside the "menu" function.. Unfortunately I get this error message;
File "/Users/buni/Desktop/Leiden/IPOHBO/sorteerhoed/sorteerhoed menu.py", line 276, in <module>
main()
File "/Users/buni/Desktop/Leiden/IPOHBO/sorteerhoed/sorteerhoed menu.py", line 271, in main
menu(antwoorden_list)
NameError: name 'antwoorden_list' is not defined
I have no idea why this message is popping, because I have defined antwoorden_list as a parameter.
This is the part of my code which is not working;
##MAIN MENU
def menu(antwoorden_list):
color.write("\n" + "Welkom bij het ICT Sorteerhoed menu " ,"DEFINITION")
color.write(naam + "\n","KEYWORD")
infoApplicatie()
sleep(0.5)
print("_____________________________________\n")
print("1. Quiz beginnen")
print("2. Specialisaties bekijken")
print("3. Resultaten bekijken")
print("4. Programma sluiten")
print("_____________________________________\n")
sleep(0.9)
menuchoice = input("selecteer optie: ")
##SELECTION
if menuchoice == "1":
quiz(antwoorden_list)
elif menuchoice == "2":
specialisatiemenu()
elif menuchoice == "3":
resultatenmenu(antwoorden_list)
elif menuchoice == "4":
exit()
def vragenLijst(antwoorden_list):
print("De vragen worden geladen... ")
sleep(2.0)
print()
print("Goed om te weten: de vragen kunnen alleen beantwoord worden met 'ja' en 'nee', zolang je dit niet invoert, zullen de vragen verder gesteld worden.")
sleep(3.0)
print("---------------------------------------------------------------------------------------------------------------------------------------------------------")
vragen_list = open("vragenspecialisaties.txt").readlines()
vragen_list_index = list(enumerate(vragen_list, 1))
vragen_list_dict = dict(vragen_list_index)
antwoorden_list = []
while vragen_list_dict:
key = choice(list(vragen_list_dict))
antwoord = input(vragen_list_dict[key] + "(ja/nee): ")
if antwoord == "ja" or antwoord == "nee":
antwoorden_list.append((key, antwoord))
antwoorden_list.sort()
del vragen_list_dict[key]
return antwoorden_list
antwoorden_user = open("antwoorden_user.txt", "a")
antwoorden_user.write(naam + ": " + str(antwoorden_list) + "\n")
antwoorden_user.close()
def main():
menu(antwoorden_list)
infoApplicatie()
variabelen(antwoorden_list)
if __name__ == "__main__":
main()
I will appreciate all the help!
When you run your script, the main() function runs at first. So do the variable declarations inside main() before calling the functions.

Python continue indentation in While loop

I am writing a program that has multiple options to modify a dictionary in python. The user has four options, and after completing an option I want the program to bring back the user to the main menu.
So far, every option works correctly except it doesn't bring the user back to the main menu, and instead loops for ever
user_input = int(input("Faites un choix..."))
liste_epicerie = {}
while True:
if user_input == 1:
print(liste_epicerie)
if liste_epicerie == {}:
print("La liste est vide")
continue
So this code should bring back the user to user_input, but instead prints "La liste est vide" for ever.
What am I doing wrong?
You have to actually read the user input again (inside the loop):
liste_epicerie = {}
while True:
user_input = int(input("Faites un choix..."))
if user_input == 1:
# ...
elif ...:
# ...
# under some condition
break
The variable user_input does not magically remember and repeat how its value came to be.
sum=0
count=0
while True:
n=input ("enter the value :")
if n=="exit":
break
try:
float(n)
except:
print ("enter the numeric value")
continue
sum=sum+n
count=count+1
print(sum,count,sum/count)

Restarting a function in Python 3.4

I need help for my python assignment. We have to make a quiz program and I am having trouble with restarting a function.
I need something like continue, but instead runs the function again. Also, some tips on returning values from functions cant hurt! Thanks! ~Also, I just started using python 2 weeks ago, so this is pretty advanced to me. EDIT: Thanks to user: 2ps! :D
#Quiz YAY!
#
#Name Removed
#
#Version 1.0
#
score = 0;
modPassword = "200605015"
def modMode(score):
print("Entering Overide Mode");
print("Opening Overide Console")
cmd = input("Enter Command call exit{} to exit: ")
if cmd == "corr":
print("Adding one point")
score=score+1
return(score);
elif cmd== "manScoreChng":
score=int(input("What do want the score to be?"));
elif cmd == 'stop{}':
raise Exception('Quit by User')
score = modMode(score);
print(score);
To capture the return of the modMode function, just make sure you return something at the end:
score = 0;
modPassword = "200605015"
def modMode(score):
print("Entering Overide Mode")
print("Opening Overide Console")
cmd = input("Enter Command: ")
if cmd == "corr":
print("Adding one point")
score = score+1
elif cmd == "manScoreChng":
score = int(input("What do want the score to be?"))
elif cmd == 'exit':
raise Exception('Bye!')
return int(score) # MAKE SURE YOU HAVE THIS LINE HERE
To call the modScore command over and over again, use a loop.
try:
while True:
score = modMode(score) # grab the returned value from modMode by using `=`
print(score)
except Exception:
pass
This will run until the user types in exit.

Categories