When running this code, I keep having an error. I would like to know what is wrong. The code has to be able to read words and integers and repeat the prompt(Please enter an integer >= 2: ') until it is greater or equal to 2. Thanks in advance.
def prime_number():
prime_num = input('Please enter an integer >= 2: ')
while not(prime_num.isdigit() and int(prime_num)<1):
prime_num = input('Please enter an integer >= 2: ')
for i in range(2,int(prime_num)+1):
for x in range(2,i):
if i%x == 0:
break
else:
print (i)
You need to enter the function. This is typically done in python with:
def prime_number():
prime_num = input('Please enter an integer >= 2: ')
while not(prime_num.isdigit() and int(prime_num)<1):
prime_num = input('Please enter an integer >= 2: ')
for i in range(2,int(prime_num)+1):
for x in range(2,i):
if i%x == 0:
break
else:
print (i)
if __name__ == "__main__":
prime_number()
Just some advice in general. I would separate the input logic from the prime number calculation logic.
As mentioned by #rpattiso, you are not invoking the method and
You while condition is buggy
This should work:
def prime_number():
prime_num = input('Please enter an integer >= 2: ')
while not (prime_num.isdigit() and not int(prime_num)<1):
prime_num = input('Please enter an integer >= 2: ')
for i in range(2,int(prime_num)+1):
for x in range(2,i):
if i%x == 0:
break
else:
print (i)
prime_number()
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 just created a simple calculator program using python language, but there is a little problem here, when I end the program by inputting number 1, there is always the text none.
The question is how do I get rid of the text none in the program that I created? Because to be honest it is very annoying and will damage the image of the program that I created.
def pilihan():
i = 0
while i == 0:
print('\n\tWelcome to the Simple Calculator Program')
print("\nPlease Select Existing Operations", "\n1. subtraction", "\n2. increase", "\n3. division", "\n4. multiplication")
pilihan2 = int(input('Enter your choice (1/2/3/4): '))
if pilihan2 == 1:
angka1 = int(input('Enter the First Number: '))
angka2 = int(input('Enter the Second Number: '))
print(angka1, "-", angka2, "=", angka1 - angka2)
elif pilihan2 == 2:
angka1 = int(input('Enter the First Number: '))
angka2 = int(input('Enter the Second Number: '))
print(angka1, "+", angka2, "=", angka1 + angka2)
elif pilihan2 == 3:
angka1 = int(input('Enter the First Number: '))
angka2 = int(input('Enter the Second Number: '))
print(angka1, ":", angka2, "=", angka1 / angka2)
elif pilihan2 == 4:
angka1 = int(input('Enter the First Number: '))
angka2 = int(input('Enter the Second Number: '))
print(angka1, "x", angka2, "=", angka1 * angka2)
else:
print('Error option, please try again')
continue
print('Program finished, want to restart?')
y = 0
while y == 0:
ulang = int(input('Type 0 for YES and 1 for NO = '))
if ulang == 0:
y += 1
break
elif ulang == 1:
y += 2
break
else:
print('\nThe command you entered is an error, please try again')
continue
if y == 1:
continue
else:
break
print(pilihan())
Change the print(pilihan()) to pilihan(), the return value of pilihan() is None :)
I am a newbie in python and trying to make a calculator but no getting how to make it
I am making a Calculator which will take input from the user until the user enters 0 and then do the operations
but I am stuck here
if anyone can help me doing this work I will be very thankful to him/her.
num = None
# Asking Users for the Specific Operations
print(("1. For Addition \n 2. For Subtraction. \n 3. For Multiplication. \n 4. For Division \n 5.For Exit"))
options = int(input("Enter Your Choice: "))
# For Addition or Option 1
if options == 1:
total = 0
while(num != 0):
try:
num = float(input("(Enter \'0'\ When Complete.) Enter Number "))
except:
print("Error, Enter Valid Number")
continue
total = total + num
print("Your Calculated Number is: {} ".format(total))
# For Subtraction or Option 2
elif options == 2:
total = 0
while (num != 0):
try:
num = float(input("(Enter \'0'\ When Complete.) Enter Number "))
except:
print("Error, Enter Valid Number")
continue
total = total - num
print("Your Calculated Value is: {}".format(total))
# Multiplication for Option 3
elif options == 3:
total = 1
while (num != 0):
try:
num = float(input("(Enter \'0'\ When Complete.) Enter Number "))
except:
print("Error, Enter Valid Number")
continue
total = total * num
print("Your Calculated Value is: {}".format(total))
# Division for Option 4
elif options == 4:
total = 1
while (num != 0):
try:
num = float(input("(Enter \'0'\ When Complete.) Enter Number "))
except:
print("Error, Enter Valid Number")
continue
total = total / num
print("Your Calculated Value is: {}".format(total))
# When User Wants to Exit
else:
print("Thank You for Using the Calculator")
Here is a better approach using itertools.reduce. Instead of repeating the same code for inputting a number multiple times, put it into a function. This will also help avoid the errors in your code and clarify the logic. A second generator function can be used to get the series of values until the user enters zero.
from functools import reduce
import operator
def input_number():
while True:
try:
return float(input("(Enter '0' When Complete.) Enter Number "))
except:
print("Error, Enter Valid Number")
def input_series():
while True:
n = input_number()
if n == 0:
return
yield n
operations = {
1: operator.add,
2: operator.sub,
3: operator.mul,
4: operator.truediv
}
# Asking Users for the Specific Operations
print(("1. For Addition \n 2. For Subtraction. \n 3. For Multiplication. \n 4. For Division \n 5.For Exit"))
option = int(input("Enter Your Choice: "))
# For Addition or Option 1
if option == 5:
print("Thank You for Using the Calculator")
else:
total = reduce(operations[option], input_series())
print("Your Calculated Value is: {}".format(total))
Instead of
elif options == 2:
total = 0
while (num != 0):
try:
num = float(input("(Enter \'0'\ When Complete.) Enter Number "))
except:
print("Error, Enter Valid Number")
continue
total = total - num
use (the changes are only in the 2nd line and in the last one)
elif options == 2:
total = None
while (num != 0):
try:
num = float(input("(Enter \'0'\ When Complete.) Enter Number "))
except:
print("Error, Enter Valid Number")
continue
total = total - num if total is not None else num
The same method you may use for the elif options == 4: branch.
The problem with subtraction is that the variable total is not initialized.
The problem with multiplication and division is that when the user inputs "0", the variable total is multiplied or divided by zero before it is checked in the while statement. what I would normally do is this:
elif options == 3:
total = 1
while True:
try:
num = float(input("(Enter '0' When Complete.) Enter Number ")) # No need to escape single quotes when your string uses double quotes
if num == 0:
break
except ValueError:
print("Error, Enter Valid Number")
continue
total = total * num
print("Your Calculated Value is: {}".format(total))
However, if you wanted a quick fix, you can have the user input 1 instead of 0 for multiplication and division:
elif options == 4:
total = 1
while (num != 1):
try:
num = float(input("(Enter '1' When Complete.) Enter Number "))
except:
print("Error, Enter Valid Number")
continue
total = total / num
print("Your Calculated Value is: {}".format(total))
Edit: If you want division to work the way you specified, you could do something like this:
elif options == 2:
total = 1
try:
first_number = float(input("(Enter '0' When Complete.) Enter Number "))
if first_number == 0:
print("Your Calculated Value is: 0")
exit()
except ValueError:
print("Error, Enter Valid Number")
continue
total = 1
while True:
try:
num = float(input("(Enter '0' When Complete.) Enter Number "))
if num == 0:
break
except ValueError:
print("Error, Enter Valid Number")
continue
total = total * num
print("Your Calculated Value is: {}".format(total + first_number))
This question already has answers here:
Asking the user for input until they give a valid response
(22 answers)
Closed 2 years ago.
My goal is creating a factorial program in python that asks infinite user input to find factorial of the number user type, until I would like to quit the program. But there is probably discrepancy between the lines of the code to works for exit the program and integer numbers below it.
1) I tried to solve this to not write int(input) I wrote just
input('Enter a number. Type exit to stop:> ')
both above or below the while True statement but it didn't work.
2) I also want to use lower() function to quit the program but when I use it, the discrepancy happens again because I ask user input for an integer but when I turn it to a normal input and type it the above while True statement, problem occurs.
3) Also I want to user input as a number with using that isdigit() function tried to use like this but it didn't work well:
factorial = 1
user_input = input('Enter a number: ')
while user_input.lower() != 'exit':
while not user_input.isdigit():
print('This is not a number. Please try again:> ')
user_input = int(input('Try again:> '))
user_input = int(input('Enter a new number: '))
.
.
.
and this, too didn't work
My actual code is this:
while True:
factorial = 1
user_input = int(input('Enter a number. Type exit to stop:> '))
if user_input == 'exit':
print('You are quitting the program')
break
elif user_input < 0:
print("Sorry, factorial does not exist for negative numbers")
elif user_input == 0:
print("The factorial of 0 is 1")
else:
for i in range(1, user_input + 1):
factorial = factorial * i
print("The factorial of", user_input, "is", factorial)
The program works like this:
Enter a number. Type exit to stop:> 4
The factorial of 4 is 24
Enter a number. Type exit to stop:> 5
The factorial of 5 is 120
Enter a number. Type exit to stop:> 6
The factorial of 6 is 720
and when I type 'exit' to quit from program I am receiving this kind of error:
Traceback (most recent call last):
File "E:/Kodlar/Python/Taslak projeler/taslak177.py", line 5, in <module>
user_input = int(input('Enter a number. Type exit to stop:> '))
ValueError: invalid literal for int() with base 10: 'exit'
As you can see, code blocks work instead of quitting the program with user input. How can I fix this?
Can anyone help? Thanks already!
Edit: I reorganized the code and it works perfectly fine. Thanks for your all responses!
while True:
user_input = input("Enter a number:> ")
if user_input == "exit":
print('You are quitting the program...')
break
else:
try:
factorial = 1
user_input = int(user_input)
if user_input < 0:
print("Sorry, factorial does not exist for negative numbers")
elif user_input == 0:
print("The factorial of 0 is 1")
else:
for i in range(1, user_input + 1):
factorial = factorial * i
print(f'The factorial of {user_input} is {factorial}')
except ValueError:
print("Please provide a valid number")
You should check if the input is exit before converting it to int and if so, break the loop.
Try this instead:
while True:
user_input = input("Enter a number:")
if user_input == "exit":
print('You are quitting the program')
break
else:
try:
user_number = int(user_input)
if user_number < 0:
print("Sorry, factorial does not exist for negative numbers")
elif user_number == 0:
print("The factorial of 0 is 1")
else:
# calc factorial here
except ValueError:
print("Please provide a valid number")
Your program get int inputs,
user_input = int(input('Enter a new number: '))
try this instead, get string input
user_input = input('Enter a new number: ')
and convert it into int later
user_input = int(user_input)
Because you are casting the user's response (a string) into an int in both cases.
user_input = int(input('Enter a new number: '))
and later
user_input = int(input('Enter a number. Type exit to stop:> '))
Perhaps try a little tweak:
while True:
factorial = 1
user_input = input('Enter a number. Type exit to stop:> ')
if user_input.lower().strip() == 'exit':
print('You are quitting the program')
break
elif user_input.isnumeric() and user_input < 0:
print("Sorry, factorial does not exist for negative numbers")
elif user_input.isnumeric() and user_input == 0:
print("The factorial of 0 is 1")
elif user_input.isnumeric():
for i in range(1, user_input + 1):
factorial = factorial * i
print("The factorial of", user_input, "is", factorial)
else:
print("Please enter an integer or 'exit'")
You could also wrap another if so you don't duplicate the isnumeric() tests
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'.