ending a program early, not in a loop? - python

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.

Related

Finding the sum of square of first n natural numbers

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")

how should i write this program on python?

can you please tell me why do i get error for this?
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 the number. Enter 7, 2, bob, 10, and 4 and match the output below.
largest = None
smallest = None
while True:
try:
num=input("Enter a number: ")
if num == 'done':
break
num=int(num)
if largest == None or largest<num:
largest = num
elif smallest == None or smallest > num:
smallest = num
except ValueError:
print ("Invalid input")
break
print ("Maximum number is", int(largest))
print ("Minimum number is", int(smallest))
You may be using Python 2 instead of Python 3 - please check this. If you are using Python 2, you should be using raw_input() instead of input().
Change elif to if:
if largest == None or largest<num:
largest = num
if smallest == None or smallest > num:
smallest = num
That will guarantee both largest and smallest are both integers (unless the first input is done or another invalid value).
You need to check if largest or smallest is None.
Append the user input to a list inside the while loop, and then slice it in the final print statements:
largest = None
smallest = None
nums = []
while True:
try:
num = input("Enter a number: ")
if num == 'done':
break
num = int(num)
nums.append(num)
except ValueError:
print("Invalid input")
break
print("Maximum number is", max(nums))
print("Minimum number is", min(nums))
Example run:
Enter a number: 22
Enter a number: 2
Enter a number: done
Maximum number is 22
Minimum number is 2
Posting the output and/or the error would be very helpful to help you.
You have to change elif into if and remove the break clause inside the except in order to keep asking for numbers even after an invalid input.
largest = None
smallest = None
while True:
try:
num = input("Enter a number: ")
if num == 'done':
break
num=int(num)
if largest == None or largest < num:
largest = num
if smallest == None or smallest > num:
smallest = num
except ValueError:
print ("Invalid input")
print ("Maximum number is", int(largest))
print ("Minimum number is", int(smallest))

question include exception handling with finding of largest and smallest no. this is a assignment problem of coursera platform

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)

Python Coursera Assignement

I am trying to learn Python through a course on Courser, and so far having a feeling I am not going to be able to.
I don't want an answer to the assignment, I want someone to push me in the right direction. Because Im stuck and the online tutors there are not being any help just repeating the obvious that is already stated in the assignment. The assignment is very simple, but I cant understand what I am missing.
Here is the assignment:
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 the number. Enter the numbers from the book for problem 5.1 and Match the desired output as shown.
Here is my code, i tried using the example codes we where show for getting the minimum and maximum, but the problem is in the examples we had they had lists, here I was told I dont need a list. But everytime the value of num changes with ever new input, how can i get the program to choose from certain numbers if they are not storing...or do you think i can enter lists in the raw_input?
while True:
inpt = raw_input("Enter a number: ")
if inpt == "done" : break
try:
num = int(inpt)
except:
print "Invalid input"
continue
largest = None
if largest is None:
largest = num
elif num > largest:
largest = num
smallest = None
if smallest is None:
smallest = num
elif num < smallest:
smallest = num
print "Maximum is", largest
print "Minimum is", smallest
The numbers from the book are 4, 5, 7 and a word
Thank you everyone for your support, I understand what I have to do, not sure if I understand how I will get there, but Im going to sit and keep trying. Meanwhile I am getting issues with indentation
let's say I rewrote the code like this and want to add an if statement into the while loop
largest = None
smallest = None
while True:
inpt = raw_input("Enter a number: ")
if inpt == "done" : break
try:
num = int(inpt)
except:
print "Invalid input"
continue
should the if statement start with the same indent as the continue and then the inside of the if indented again?? Because Im getting errors when I do that
largest = None
smallest = None
while True:
inp = input("Enter a number: ")
if inp == "done" : break
try:
num = float(inp)
except:
print ("Invalid input")
continue
if smallest is None:
smallest=num
if num > largest :
largest=num
elif num < smallest :
smallest=num
def done(largest,smallest):
print("Maximum is", int(largest))
print("Minimum is", int(smallest))
done(largest,smallest)
this will surly work.
You're on the right track with your current implementation, but there is some issues in the order of your operations, and where the operations are taking place. Trace through your program step by step, and try to see why your None assignment may be causing some issues, among other small things.
You are being asked to keep a running max and running min, the same way you could keep a running total. You just update the running <whatever> inside the loop, then discard the user's most recent input. In the case of running total, the code would look like tot = tot + newinput and you could then discard newinput (or, more likely, reuse it) without recording it in a list or any other data structure.
Not every problem permits a "running" solution. For instance, if you wanted to give the user an undo feature, letting them back out some of the numbers they entered earlier, you would have to keep an exact history of all the numbers. But here, you can get by without keeping that data.
You should check for the largest and smallest numbers inside the loop. First check if its a number - if yes, carry on and see if it is bigger than your current largest variable value (start with 0). If yes, replace it. See, if its smaller than your smallest value (start with the first number that comes in, if you start with 0 or just a random number, you might not get lower that that. If you start with the first number, then it'll definitely be the smallest (after all the loops)), etc, etc. All of that should be done inside the loop and after the loop should be just the printing. And yes, you don't need to use lists.
Let me give you a hint here, every time your while loop takes in a input, it sets the values of largest and smallest to None. Where should you initialize them?
I sense that your confusion partly stems from how the user is expected to give the input. One could interpret the instructions in two ways.
The user writes 4 5 7 randomword [ENTER]
The user writes 4 [ENTER] 5 [ENTER] 7 [ENTER] randomword [ENTER]
If it was the first variant, then you might be expected to process the whole thing as a list and determine its parts
However, the fact that they told you "you will not need lists for this exercise" implies that they expect the second scenario. Which means you should design your while loop such that at each iteration it expects to receive a single input from the user, and do something with it (i.e. check if it's bigger / smaller than the last). Whereas the loop you have now, will simply always keep the last input entered, until "done" is encountered.
Once you're out of the while loop, all you need to do is present the variables that you've so carefully collected and kept updating inside the loop, and that's it.
I figured it out I think, and the thing that was killing my code was the continue statement if I am not wrong
here is what i got, and please leave comments if I got it wrong
largest = None
smallest = None
while True:
inpt = raw_input("Enter a number: ")
if inpt == "done" : break
try:
num = int(inpt)
except:
print "Invalid input"
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
largest = None
smallest = None
while True:
inp = input("Enter a number: ")
if inp == "done" : break
try:
num = float(inp)
except:
print ("Invalid input")
continue
if smallest is None:
smallest=num
if num > largest :
largest=num
elif num < smallest :
smallest=num
def done(largest,smallest):
print("Maximum is", int(largest))
print("Minimum is", int(smallest))
done(largest,smallest)
maximum = -1
minimum = None
while True:
num = input('Enter the num: ')
if num == 'done':
break
try:
num1 = int(num)
except:
print('Invalid input')
continue
if minimum is None:
minimum = num1
if num1 > maximum:
maximum = num1
elif num1 < minimum:
minimum = num1
print('Maximum is', maximum)
print('Minimum is', minimum)
largest = None
smallest = None
while True:
num = input("Enter a number: ")
if num == "done" :
break
try:
n=int(num)
except:
print("Invalid input")
continue
if largest is None:
largest=n
if n > largest:
largest=n
if smallest is None:
smallest=n
elif n < smallest:
smallest =n
print("Maximum is", largest)
print("Minimum is" , smallest)

Counting the number of loops python

I am learning python, and one of the exercises is to make a simple multiplication game, that carries on every time you answer correctly. Although I have made the game work, I would like to be able to count the number of tries so that when I've answered correctly a few times the loop/function should end. My problem is that at the end of the code, the function is called again, the number of tries goes back to what I originally set it, obviously. How could I go about this, so that I can count each loop, and end at a specified number of tries?:
def multiplication_game():
num1 = random.randrange(1,12)
num2 = random.randrange(1,12)
answer = num1 * num2
print('how much is %d times %d?' %(num1,num2))
attempt = int(input(": "))
while attempt != answer:
print("not correct")
attempt = int(input("try again: "))
if attempt == answer:
print("Correct!")
multiplication_game()
You could surround your call of multiplication_game() at the end with a loop. For example:
for i in range(5):
multiplication_game()
would allow you to play the game 5 times before the program ends. If you want to actually count which round you're on, you could create a variable to keep track, and increment that variable each time the game ends (you would put this inside the function definition).
I would use a for loop and break out of it:
attempt = int(input(": "))
for count in range(3):
if attempt == answer:
print("correct")
break
print("not correct")
attempt = int(input("try again: "))
else:
print("you did not guess the number")
Here's some documentation on else clauses for for loops if you want more details on how it works.
NB_MAX = 10 #Your max try
def multiplication_game():
num1 = random.randrange(1,12)
num2 = random.randrange(1,12)
answer = num1 * num2
i = 0
while i < NB_MAX:
print('how much is %d times %d?' %(num1,num2))
attempt = int(input(": "))
while attempt != answer:
print("not correct")
attempt = int(input("try again: "))
if attempt == answer:
print("Correct!")
i += 1
multiplication_game()

Categories