try:
num=int(input("Enter a number:"))
def sum(num):
result=0
if num < 0:
print(num, "is not a natural number!")
else:
for i in range(1,num+1):
result=result + (i*i)
return result
print("The sum of square of first", num, "natural number is:", sum(num))
except ValueError:
print("Invalid Input")
For the given code;
How can I not execute the below statement for input less than zero?
print("The sum of square of first", num, "natural number is:", sum(num))
Putting this statement inside else block did not help!
Just add return before the else. It should work. You can simply write return, or you can actually return a value depending on your necessities
In python, you can write if-else statements in one line
Eg:
take_this if this_condition_is_True else take_this
So now if the num is negative the sum() function won't even be called
try:
num=int(input("Enter a number:"))
def sum(num):
result=0
if num < 0:
print(num, "is not a natural number!")
else:
for i in range(1,num+1):
result=result + (i*i)
return result
print(f"The sum of square of first {num} natural number is: {sum(num)}" if num>=0 else "Stop giving negative numbers")
except ValueError:
print("Invalid Input")
Related
I can't figure out how to execute a condition that check if the user inputs are equal before checking if it is a prime number. My goal is to ask a user to input two prime numbers. And in the 2nd while loop, I want to make sure that the 2nd number is not equal to the first number in order to be checked if it is a prime number
value_P=[]
value_Q=[]
def is_prime(num):
if num == 2:
return True
if num < 2 or num % 2 == 0:
return False
for n in range(3, int(num**0.5)+2, 2):
if num % n == 0:
return False
return True
while True:
try:
P = int(input("Enter a prime number(P): "))
if is_prime(P):
value_P.append(P)
print("P =", value_P)
break;
else:
print(value_P, "is not a prime number")
except ValueError:
print("Provide an integer value...")
continue
#2nd while loop
while True:
try:
Q = int(input("Enter a prime number(Q). Not the same as the number you entered above: "))
if is_prime(Q):
value_Q.append(Q)
print("Q =", Q)
break;
else:
print(value_Q, "is not a prime number")
except ValueError:
print("Provide an integer value...")
continue
You can check if the value of Q is inside the P list using an if statement in the 2nd while loop.
while True:
try:
Q = int(input("Enter a prime number(Q). Not the same as the number you entered above: "))
if is_prime(Q):
#here the code made sure it's prime, next statement checks if the "Q" input was already previously used as the "P" input. If it is, the loop breaks.
if Q in value_P:
break
else:
value_Q.append(Q)
print("Q =", Q)
break;
else:
print(value_Q, "is not a prime number")
except ValueError:
print("Provide an integer value...")
continue
This question already has answers here:
how to find the smallest integer in a list? [duplicate]
(2 answers)
Closed 1 year ago.
Need help with an assignment. I'm not sure why I'm getting the largest and smallest number wrong.
largest = None
smallest = None
while True:
num = input('Enter a number: ')
if num == 'done':
break
try:
y=float(num)
except:
print ('Invalid Input')
continue
if largest is None:
largest=num
elif num > largest:
largest=num
if smallest is None:
smallest=num
elif num < smallest:
smallest=num
print("Maximum is", largest)
print ("Minimum is", smallest)
num is a string, the type needs to be converted when comparing
You are converting float converted value and then storing it in y.
But you are comparing using num.
Try this:
largest = None
smallest = None
while True:
num = input('Enter a number: ')
try:
y=float(num)
except Exception as e:
print ('Invalid Input')
break
if not largest:
largest=y
elif y > largest:
largest=y
if not smallest:
smallest=y
elif y < smallest:
smallest=y
print("Maximum is", largest)
print ("Minimum is", smallest)
This will break from the loop once you enter anything that cannot be parsed as a number in python.
Also use this in python 3. If you're using python2.7, you need raw_input.
If you are using Python 3.x, raw_input has been renamed to input. Quoting the Python 3.0 release notes PEP3111,
raw_input() was renamed to input(). That is, the new input() function reads a line from sys.stdin and returns it with the trailing newline stripped. It raises EOFError if the input is terminated prematurely. To get the old behavior of input(), use eval(input())
You are comparing strings, You have to change your cast in the try:
try:
num=float(num)
except:
print ('Invalid Input')
In your code, line 8, you define y = float(num). Then you just need to use y instead of num, like this:
largest = None
smallest = None
while True:
num = input('Enter a number: ')
if num == 'done':
break
try:
y=float(num)
except:
print ('Invalid Input')
continue
if largest is None:
largest=y
elif y > largest: # !!!
largest=y
if smallest is None:
smallest=y
elif y < smallest: # !!!
smallest=y
print("Maximum is", largest)
print ("Minimum is", smallest)
question:
Write a program that repeatedly prompts a user for integer numbers until the user enters 'done'. Once 'done' is entered, print out the largest and smallest of the numbers. If the user enters anything other than a valid number catch it with a try/except and put out an appropriate message and ignore it.
Input:
7 ,2 , bob, 10, 4, done.
Desired output:
Invalid input
Maximum is 10
Minimum is 2
Actual output:
Invalid input
Invalid input
Maximum is 10
Minimum is 2
Code:
largest=-1
smallest=None
while True:
num =input("Enter a number: ")
try:
if num == "done" :
break
elif smallest is None:
smallest=int(num)
elif int(num)<smallest:
smallest=int(num)
elif int(num)>largest:
largest=int(num)
else:
raise ValueError()
except ValueError:
print("Invalid input")
print("Maximum is",largest)
print("Minimum is",smallest)
I think there's a more Pythonic way of doing this. Try this:
inputList = []
while True:
num = input("Enter a number:")
try:
num = int(num)
inputList.append(num)
except:
if num == "done":
break
else:
print ("Invalid input. Ignoring...")
print ("Maximum is:",max(inputList))
print ("Minimum is:",min(inputList))
Edit: This code works with Python3. For Python2, you might want to use raw_input() instead of input()
You are already capturing the ValueError in Exception,
So inside, try, you are raising ValueError there you leave the scope for this error.
When you accept input, and it accepts 4 as input, which is neither larger than largest (i.e. 10) nor smaller than the smallest (i.e. 2). So it lands in else part and raises ValueError (as per your code). Hence prints Invalid input twice in your case. So this part is unnecessary as well as makes your solution bogus.
Again, from efficiency point of view -
1 - You are checking smallest == None for every input, which takes O(1) time and is unnecessary if you take it any integer
Here is the solution you are looking for :-
largest=None
smallest=None
while True:
try:
num = input("Enter a number: ")
num = int(num)
if smallest is None:
smallest = num
if largest is None:
largest = num
if num < smallest:
smallest = num
elif num > largest:
largest = num
except ValueError:
if num == 'done':
break
else:
print("Invalid input")
continue
print("Maximum is",largest)
print("Minimum is",smallest)
I'm attempting to make a short program that will return the factorial of a number, which works fine. The only problem I am having is getting the program to end if the user inputs a non-integer value.
num = input("input your number to be factorialised here!: ")
try:
num1 = int(num)
except ValueError:
print("That's not a number!")
if num1 < 0:
print("You can't factorialise a negative number")
elif num1 == 0:
print("the factorial of 0 is 1")
else:
for i in range(1,num1+1):
ans = ans * i
print("the factorial of", num, "is", ans)
Solution
There are better ways of doing this but given your code structure you can use else. See the docs.
num = input("input your number to be factorialised here!: ")
try:
num1 = int(num)
except ValueError:
print("That's not a number!")
else:
if num1 < 0:
print("You can't factorialise a negative number")
elif num1 == 0:
print("the factorial of 0 is 1")
else:
ans = 1
for i in range(1,num1+1):
ans = ans * i
print("the factorial of", num, "is", ans)
The else clause only executes if no exceptions are thrown.
Suggestions
So as not to give away answers to your homework, here are a couple suggestions that you should take a look at to clean up your code:
Can you use range more efficiently? Hint: you can iterate over decreasing numbers by setting the step to a negative integer.
Can you find a way to get rid of the check num1 == 0?
The OP is actually asking how to terminate the current script execution prematurely. The straightforward way to implement your idea is to use sys.exit() like
try:
num1 = int(num)
except ValueError:
sys.exit()
For more details, see this thread.
I'm trying to figure out how to print the final line of code for this - whether it's a prime number or not. I can't seem to get it to print with the code I have. Any help would be appreciated. Thanks!!
number = int(input("Enter a positive number to test: "))
while number <= 0:
print ("Sorry, only positive numbers. Try again.")
number = int(input("Enter a positive number to test: "))
test = 2
number1 = number - 1
for x in range (0, number1):
trial = number % test
if trial != 0:
print (test, "is NOT a divisor of", number, "...")
break
print (number, "is a prime number!")
else:
print (test, "is a divisor of", number, "...")
break
print (number, "is not a prime number!")
test = test + 1
The break statement ends the execution of the branch. The following print statement is never reached.
To get the correct functionaility use a boolean value and perform the check at the end:
is_prime = True
for x in range (2, number):
trial = number % x
if trial != 0:
print (x, "is NOT a divisor of", number, "...")
else:
is_prime = False
print (x, "is a divisor of", number, "...")
if is_prime:
print (number, "is a prime number!")
else:
print (number, "is not a prime number!")
You also do not need to use a variable test. Use the x from your range directly.
Have a look at the Python reference for the keyword for more information.
Syntax:
if expression:
statement(s)
else:
statement(s)
It executes all statements with break so print will be never happen...