Here is my code:
def chose_range():
while True:
choice = int(input("Choose the range 100 or 1000:"))
if choice == 100:
n = 100
break
elif choice == 1000:
n = 1000
break
else:
print('Error, enter the right number')
return n
I want to save result of this command into the variable.
How can I do this in python 3?
Do not return within your while-loop you break (you have one indent to much).
def chose_range():
while True:
choice = int(input("Choose the range 100 or 1000:"))
if choice == 100:
n = 100
break
elif choice == 1000:
n = 1000
break
else:
print('Error, enter the right number')
return n
x = chose_range()
Did you mean something like
res = chose_range()
If you mean "save the result of calling chose_range() into a variable (you didn't say which), then:
theVariable = chose_range()
However, note that your function does not always return a value to be saved; if it hits a break statement, it exits the loop without executing the return statement, at least in how your posted code is indented.
Related
I'm trying to make a program in python so that when I input a number from 1 to 10, a specific set of program goes on and asks for another number from 1 to 10 and runs another program, until I enter 0(zero) and the program stops.
So my guess was using a while loop but it didn't quite work out.
user_input = input()
user_input = int(user_input)
while user_input != 0:
(program)
else:
quit()
Try this:
user_input = int(input())
while user_input != 0:
(program)
user_input = int(input())
quit()
With your current code you only ask for input once so the loop won't end. This way you can input a new number after every iteration.
Your current program only asks once and then the loop keeps repeating. You need to keep asking for input inside the loop.
def program():
print("Executing Task....")
user_input = int(input())
while user_input != 0:
program()
user_input = int(input())
printf("Program Terminated")
Here it is:
def program():
pass
user_input = int(input())
while user_input:
program()
user_input = int(input())
quit(0)
A different way using iter with a sentinel:
def program(number):
if number < 0 or number > 10:
print('Invalid number:', number)
else:
print('Valid number:', number)
def quit():
print('quitting')
def get_number():
return int(input('Enter a number from 1 to 10: '))
for number in iter(get_number, 0):
program(number)
else:
quit()
not_zero = True
while not_zero:
num = int(input("Enter a number: "))
if num == 0:
not_zero = False
you can stop your loop using a boolean value.
I'm a newbie in Python3 coding and I have a problem here.
In line 14, I intended to end this program by printing "Thank you! Goodbye" at the part where you answer "n" to "try again?". However, it turned out that I would start all over again even if I've inserted "break" under it. Now, the only solution I can come up is to end the whole program with sys.exit(0), but I don't consider it an ideal solution since it just closes the whole program down.
import sys
while True:
x=int(input("Enter the coins you expected="))
f=int(input("Enter first coin="))
while f!=1 and f!=5 and f!=10 and f!=25:
print("invalid number")
f=int(input("Enter first coin="))
if x>f:
while x>f:
n=input("Enter next coin=")
if not n:
print("Sorry-you only entered",f,"cents")
again=input("Try again (y/n)?=")
if again=="y":
True
elif again=="n":
print("Thank you, goodbye!")
sys.exit(0)
break
while int(n)!=1 and int(n)!=5 and int(n)!=10 and int(n)!=25:
print("invalid number")
n=input("Enter next coin=")
f=f+int(n)
Replace your whole code with this:
import sys
Stay = True
while Stay:
x = int(input("Enter the coins you expected = "))
f = int(input("Enter first coin = "))
while f != 1 and f != 5 and f != 10 and f != 25:
f = int(input("Invalid number entered./nEnter first coin = "))
while x > f and Stay:
n = input("Enter next coin = ")
if not n:
print("Sorry, you only entered " + str(f) + " cents")
again = input("Try again (y/n)?=")
if again == "n":
print("Thank you, goodbye!")
Stay = False
if Stay:
n = int(n)
while n != 1 and n != 5 and n != 10 and n != 25:
print("Invalid number entered.")
n = int(input("Enter next coin = "))
f += n
I made your code more readable and fixed your problem by using a Boolean flag (Stay). This basically means that the program runs while Stay is True, and Stay becomes False when the user enters 'n'.
from random import randint
count = 0
Validation = False
def generateNumber():
Number = randint(1, 10)
return Number
def checkNumber(Guess):
Number = generateNumber()
if int(Guess) == Number and count < 1:
return "First time right! Genius?"
Validation = True
elif int(Guess) == Number and count == 2:
return "Correct. Second time, nice!"
Validation = True
elif int(Guess) == Number and count < 4:
return "Correct. Good job."
Validation = True
elif int(Guess) == Number and count > 3:
return "Correct. Took you long enough."
Validation = True
else:
return "Wrong! Try again "
while Validation == False:
Guess = input("Please guess a number between 1 to 10: ")
print (checkNumber(Guess))
count += 1
else:
TryAgain = input("Would you like to try again? y/n \n")
So the problem is, that when the user guesses the right number. Validation should be turned to True. So the while loop will stop looping. But the variable validation doesn't turn True when the player guesses the right number.
Global variables in Python are a bit tricky, it is not enough to declare a variable at the top of the file.
Also, keep you return the value before you set the Validation value, causing the function to terminate before setting this variable
Last issue is the while logic, see correction for using raw_input instead of input and else indentation
Read only access to global variables work as expected, yet when changing their value in a function requires one extra step, you should declare the global variable as global. In your case:
def generateNumber():
Number = randint(1, 10)
return Number
def checkNumber(Guess):
global Validation #<-- this instructs Python to use the global variable
Number = generateNumber()
if int(Guess) == Number and count < 1:
Validation = True
return "First time right! Genius?"
elif int(Guess) == Number and count == 2:
Validation = True
return "Correct. Second time, nice!"
elif int(Guess) == Number and count < 4:
Validation = True
return "Correct. Good job."
elif int(Guess) == Number and count > 3:
Validation = True
return "Correct. Took you long enough."
else:
return "Wrong! Try again "
while Validation == False:
Guess = input("Please guess a number between 1 to 10: ")
print (checkNumber(Guess))
count += 1
if (Validation):
if (raw_input("Would you like to try again? y/n \n") == "y"):
count = 0
Validation = False
else:
break
You need to set Validation to True before you return from the method, like this:
if int(Guess) == Number and count < 1:
Validation = True
return "First time right! Genius?"
Do this for all if-statements.
I spot two (and a half) problems in your code:
As pointed out by Ishay Peled, you need to make Validation global
Your "return" statements are located before you change the value of "Validation"
"while" has no "else"
Here's the updated code:
from random import randint
count = 0
Validation = False
def generateNumber():
Number = randint(1, 10)
return Number
def checkNumber(Guess):
global Validation
Number = generateNumber()
if int(Guess) == Number and count < 1:
Validation = True
return "First time right! Genius?"
elif int(Guess) == Number and count == 2:
Validation = True
return "Correct. Second time, nice!"
elif int(Guess) == Number and count < 4:
Validation = True
return "Correct. Good job."
elif int(Guess) == Number and count > 3:
Validation = True
return "Correct. Took you long enough."
else:
return "Wrong! Try again "
while Validation == False:
Guess = input("Please guess a number between 1 to 10: ")
print (checkNumber(Guess))
print "validation: %s" % str(Validation)
count += 1
TryAgain = input("Would you like to try again? y/n \n")
Besides the global variable issue, you need to make another set of fixes. All your assignments to Validation = True appear after the "return" statements. The Validation = True will never execute! It will exit the function before executing those. Set 'Validation = True' before you 'return'. You still need to have the global declaration as Ishay stated.
Im a total python noob and Im trying to figure out why my program doesn't end when I input "0". It just starts the menu over again.
def menu():
print('\n\n\n\n')
print('List Processing Program Menu')
print('0 to exit')
print('1 to view data')
print('2 to append data')
while(1):
try:
choice = -1
while(choice < 0 or choice > 2):
choice = int(input('Please enter a valid number choice '))
break
except ValueError:
print('Enter an integer number for your menu selection')
return choice
def main():
while(1):
choice = menu()
if(choice == 0):
break
main()
while(choice < 0 or choice > 2):
choice = int(input('Please enter a valid number choice '))
break
Your problem is here. The while loop is broken out of and None is always returned (there is an implicit return of None at the end of every Python function).
You can clean up your code as follows:
def menu():
print('\n\n\n\n')
print('List Processing Program Menu')
print('0 to exit')
print('1 to view data')
print('2 to append data')
choice = None
while choice not in [0, 1, 2]:
try:
choice = int(input('Please enter a valid number choice '))
except ValueError:
print('Enter an integer number for your menu selection')
return choice
No value is ever returned from menu because your return statement is inside of the while loop that you break out of before you get to it. Hence, inside of your main, choice is always None.
If you de-indent the return statement this will work as you expect.
def menu():
print('\n\n\n\n')
print('List Processing Program Menu')
print('0 to exit')
print('1 to view data')
print('2 to append data')
while(1):
try:
choice = -1
while(choice < 0 or choice > 2):
choice = int(input('Please enter a valid number choice '))
break
except ValueError:
print('Enter an integer number for your menu selection')
return choice
def main():
while(1):
choice = menu()
if(choice == 0):
break
main()
If you want to be concise, you can remove all of your try/except statements because you never actually need to execute those anyhow.
def menu():
choice = -1
while choice < 0 or choice > 2:
choice = int(input('Please enter a valid number choice'))
return choice
def main():
choice = -1
while choice != 0:
choice = menu()
Right after the while (choice < 0 or choice > 2): loop you say break, but the return choice is inside of the while(1) loop. That means that your function will by implication return None, not choice. You just need to un-indent the return choice line.
Your menu() function returns None because your return statement is inside your while loop, which you break out of when the entry is valid.
Unindent your return statement so it lines up with while, or better yet, just return from inside the loop instead of using break.
You are never returning choice, because it is inside your first while loop. When you break out of that while loop, you just return None since there is no specific return specified. You have two options here:
Move the return outside of the while loop, or do something like this:
try:
choice = -1
while(choice < 0 or choice > 2):
return int(input('Please enter a valid number choice '))
except ValueError:
print('Enter an integer number for your menu selection')
You need to indent the break when you are reading the choice, or else your menu function will always return None.
try:
choice = -1
while(choice < 0 or choice > 2):
choice = int(input('Please enter a valid number choice '))
break
except ValueError:
print('Enter an integer number for your menu selection')
I'm working on part of a program which presents a menu of 3 options to the user. I want to allow the user to enter their menu choice (1-3) after which the menu appears again and allows the user to enter another choice and repeats this process for a total of n times which the user also inputs prior to the menu.
The program is just printing the menu 3 times in a row rather than in n separate iterations but I'm not sure how to fix this.
n = int(input('Please enter the number of iterations:'))
for i in range(0,n):
print('Enter 1 for choice 1\n')
print('Enter 2 for choice 2\n')
print('Enter 3 for choice 3\n')
choice = int(input('Enter your choice:'))
if (choice == 1):
....
....
else:
print('Invalid choice')
Put your code to handle the choice inside the loop:
n = int(input('Please enter the number of iterations:'))
for i in range(0,n):
print('Enter 1 for choice 1\n')
print('Enter 2 for choice 2\n')
print('Enter 3 for choice 3\n')
choice = int(input('Enter your choice:'))
if (choice == 1):
....
....
else:
print('Invalid choice')
Indent the following piece of code, 4 spaces to the right:
if (choice == 1):
...
...
else:
print('Invalid choice')
But if I may suggest a better implementation of what you are trying to do, then define a function which can handle a non-numeric user input, and in addition, take those prints outside the for loop:
def getUserInput(msg):
while True:
print msg
try:
return int(input(msg))
except Exception,error:
print error
n = getUserInput('Please enter the number of iterations:')
print 'Enter 1 for choice 1'
print 'Enter 2 for choice 2'
print 'Enter 3 for choice 3'
while n > 0:
choice = getUserInput('Enter your choice:')
if choice == 1:
...
n -= 1
elif choice == 2:
...
n -= 1
elif choice == 3:
...
n -= 1
else:
print 'Invalid choice'
Just for fun: I've rewritten this to introduce some more advanced ideas (program structure, use of enumerate(), first-class functions, etc).
# assumes Python 3.x
from collections import namedtuple
def get_int(prompt, lo=None, hi=None):
while True:
try:
val = int(input(prompt))
if (lo is None or lo <= val) and (hi is None or val <= hi):
return val
except ValueError: # input string could not be converted to int
pass
def do_menu(options):
print("\nWhich do you want to do?")
for num,option in enumerate(options, 1):
print("{num}: {label}".format(num=num, label=option.label))
prompt = "Please enter the number of your choice (1-{max}): ".format(max=len(options))
choice = get_int(prompt, 1, len(options)) - 1
options[choice].fn() # call the requested function
def kick_goat():
print("\nBAM! The goat didn't like that.")
def kiss_duck():
print("\nOOH! The duck liked that a lot!")
def call_moose():
print("\nYour trombone sounds rusty.")
Option = namedtuple("Option", ["label", "fn"])
options = [
Option("Kick a goat", kick_goat),
Option("Kiss a duck", kiss_duck),
Option("Call a moose", call_moose)
]
def main():
num = get_int("Please enter the number of iterations: ")
for i in range(num):
do_menu(options)
if __name__=="__main__":
main()
You need to develop a python program that asks several intervals of integer numbers to the user
(negative or positive numbers). Each time, the user should have an option to either provide a new
interval or quit the program. The intervals will form lists of numbers and have a limit of -999 or 999.
An interval is defined as a continuous sequence of integer numbers. For every break in the continuity
of the integer numbers, you assume a new interval.