I cannot get my program to stop repeating my first statement - python

Python just keeps repeating back to me "How many random numbers do you want?" and won't move on to the next input.
I've tried most things I could think of.
do_program = True
while(do_program):
while(True):
try:
number_of_numbers = float(input("How many random numbers do you want?"))
if(number_of_numbers < 0):
print("Negative numbers are not allowed.")
continue
except ValueError:
print("The value you entered is invalid. Please enter numerial values only.")
else:
break
while(True):
try:
lowest_number = float(input("What is the lowest random number you want?"))
if(lowest_number < 0):
print("Negative numbers are not allowed.")
continue
except ValueError:
print("The value you entered is invalid. Please enter numerial values only.")
else:
break
while(True):
try:
highest_number = float(input("What is the highest random number you want?"))
if(highest < 0):
print("Negative numbers are not allowed.")
continue
except ValueError:
print("The value you entered is invalid. Please enter numerial values only.")
else:
break
import random
print("The numbers were written to randomnum.txt.")
def main():
for count in range(number_of_numbers):
number = random.randint(lowest_number, highest_number)
print(number)
main()
Right now I just want to focus on getting to my second and third input statements.

After successfully reading number_of_numbers the code breaks out of the inner while(True) loop and then resumes the outer while(do_program) loop. This causes the same code to be executed over and over. Perhaps rework your code to process the input before returning to the main loop?

Related

How to end a try loop in a dice game at the correct place?

I am trying to make a program where the player enters a number (1-6) to guess what a fair randomised dice lands on.
Then it should stimulate the dice throw, and informs the player whether it was correct or not.
It should continue to ask the player to guess by entering a number until the guess is correct.
If it is correct the game should end.
If it is not correct the game continues to ask the player to select a number.
I have tried:
from random import randint
def validateNumber():
valid = False
if 1 <= number_in <=6:
valid = True
return valid
game_1 = randint(1,6)
while True:
try:
number_in = int(input("Enter a number between 1-6: "))
is_valid = validateNumber()
if not is_valid:
number_in = int(input("Enter a number between 1-6: "))
if number_in == game_1:
print(f"The result was {game_1}. Your guess was correct!")
else:
print(f"The result was {game_1}. Your guess was NOT correct. Please try again")
except ValueError:
break
However, now it does not end when the guess is correct.
Does anyone know how to fix this?
I have tried many variants, but this is the closest I got to the wanted result, but still it is not satisfactory. Also it does not seem to truly handle the user input?
(I am quite new to Python and trying to learn the most before starting college in January:)) All help appreciated!
Your main issue is that you should break out of the while loop when the user guess the number. You have a couple of other issues:
if the user inputs an invalid number twice, you accept it the second time
it would be better to pass number_in to validateNumber as a parameter rather than relying on a global
if the user inputs something which is not an integer, the game terminates
Note also you can simplify validateNumber as follows:
def validateNumber(number):
return 1 <= number <= 6
Overall I would rewrite the code as:
from random import randint
def validateNumber(number):
return 1 <= number <= 6
game_1 = randint(1, 6)
while True:
# play game
is_valid = False
while not is_valid:
# read an input
try:
number_in = int(input("Enter a number between 1-6: "))
is_valid = validateNumber(number_in)
except ValueError:
pass
# check the input
if number_in == game_1:
print(f"The result was {game_1}. Your guess was correct!")
# all done
break
else:
print(f"The result was {game_1}. Your guess was NOT correct. Please try again")
# get another number for them to guess
game_1 = randint(1, 6)
After you get correct answer (number_in == game_1), you should break the while.
I think, this is what you want:
from random import randint
def validateNumber():
valid = False
if 1 <= number_in <= 6:
valid = True
return valid
game_1 = randint(1, 6)
guess_was_correct = False
while not guess_was_correct:
is_valid = False
while not is_valid:
try:
number_in = int(input("Enter a number between 1-6: "))
is_valid = validateNumber()
if not is_valid:
print("You entered a number outside of the 1-6 range. Please enter a number between 1 and 6!")
except ValueError:
print("You did not enter a number. Please enter a number.")
if number_in == game_1:
print(f"The result was {game_1}. Your guess was correct!")
guess_was_correct = True
else:
print(f"The result was {game_1}. Your guess was NOT correct. Please try again")
You need an inner loop to check the validity of the input, and the exception handling needs to go there too.
Checking the correctness of the guess is done in the outer loop. It's a separate thing and needs to be done only once we have a valid input.

ValueError: Name undefined in python

I am getting "Name undefined warning while compiling with try-catch block". Please give some idea about this error.
NAME UNDEFINED ERROR IMAGE
# Importing random package
import random
try:
top_range = int(input("Enter the range:"))
except ValueError:
print("Please enter he Integer Number")
# Getting the random number from system
sys_guess = random.randint(0, top_range)
print("System Guess =", sys_guess)
print("Try to GUESS the Number within 3 entries, MAXIMUM 3 guess......!")
# making for increment
guess = 0
# Guessing the number
while sys_guess >= 0:
user_input = int(input("Enter guessed number: "))
if sys_guess != user_input:
# incrementing the wrong value
guess += 1
print("Wrong Guess-->")
if guess == 2:
print("you have only one guess left")
if guess > 2:
print("Maximum number of guess tried, Failed to obtain the guess!!!!!")
break
else:
# incrementing the correct value
guess += 1
print("!HURRAY***CORRECT GUESS***!")
if sys_guess == user_input:
break
# printing the total number of guess
print("Total Guesses=", guess)
Stick the try catch block in a loop that will continue endlessly until the user enters a valid number. If there is an exception at the moment the top_range value is never defined thus the error.
while True:
try:
top_range = int(input("Enter the range:"))
break
except ValueError:
print("Please enter he Integer Number")

How to stop a while loop processing integers with a string

I'm processing integer inputs from a user and would like for the user to signal that they are done with inputs by typing in 'q' to show they are completed with their inputs.
Here's my code so far:
(Still very much a beginner so don't flame me too much)
def main():
print("Please enter some numbers. Type 'q' to quit.")
count = 0
total = 0
num=[]
num = int(input("Enter a number: "))
while num != "q":
num = int(input("Enter a number: "))
count += 1
total += num
del record[-1]
print (num)
print("The average of the numbers is", total / count)
main()
Any feedback is helpful!
You probably get a ValueError when you run that code. That's python's way of telling you that you've fed a value into a function that can't handle that type of value.
Check the Exceptions docs for more details.
In this case, you're trying to feed the letter "q" into a function that is expecting int() on line 6. Think of int() as a machine that only handles integers. You just tried to stick a letter into a machine that's not equipped to handle letters and instead of bursting into flames, it's rejecting your input and putting on the breaks.
You'll probably want to wrap your conversion from str to int in a try: statement to handle the exception.
def main():
num = None
while num != "q":
num = input("Enter number: ")
# try handles exceptions and does something with them
try:
num = int(num)
# if an exception of "ValueError" happens, print out a warning and keep going
except ValueError as e:
print(f'that was not a number: {e}')
pass
# if num looks like an integer
if isinstance (num, (int, float)):
print('got a number')
Test:
Enter number: 1
got a number
Enter number: 2
got a number
Enter number: alligator
that was not a number: invalid literal for int() with base 10: 'alligator'
Enter number: -10
got a number
Enter number: 45
got a number
Enter number: 6.0222
that was not a number: invalid literal for int() with base 10: '6.0222'
I'll leave it to you to figure out why 6.02222 "was not a number."
changing your code as little as possible, you should have...
def main():
print("Please enter some numbers. Type 'q' to quit.")
count = 0
total = 0
num=[]
num.append(input("Enter a number: "))
while num[-1] != "q":
num.append(input("Enter a number: "))
count += 1
try:
total += int(num[-1])
except ValueError as e:
print('input not an integer')
break
print (num)
print("The average of the numbers is", total / count)
main()
You may attempt it the way:
def main():
num_list = [] #list for holding in user inputs
while True:
my_num = input("Please enter some numbers. Type 'q' to quit.")
if my_num != 'q':
num_list.append(int(my_num)) #add user input as integer to holding list as long as it is not 'q'
else: #if user enters 'q'
print(f'The Average of {num_list} is {sum(num_list)/len(num_list)}') #calculate the average of entered numbers by divide the sum of all list elements by the length of list and display the result
break #terminate loop
main()

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)

Categories