I have ran into some problems while trying to combine while loop and ValueError.
Initially I wanted my program to add numbers together. When the sum of numbers has exceeded X, I would like my program to continue to else statement. At first I didn't focus on the fact that input could also be (for example) string.
number = 1
while number < 10:
add = int(raw_input("Enter a number to add: "))
number += add
print number
else:
print "Number is greater than 10"
I tried combining the first code with try/except and ValueError to accept integers as the only inputs. Second code will not continue to else statement when sum of numbers exceeds X. Could someone please explain why this is not working?
number = 1
while number < 10:
while True:
try:
add = int(raw_input("Enter a number: "))
number += add
print number
except ValueError:
print "Please enter a number"
else:
print "Number is greater than 10"
Thank You.
there's an extra while True: loop resulting in an infinte loop.
Remove it and your code will work fine.
Another example where while(condition) (with condition not True) leads to mistakes: you have to ensure that the loop will be entered once, sometimes by initalizing your condition artificially. I would write that instead
number = 1
while True:
try:
add = int(raw_input("Enter a number: "))
number += add
print number
if number>10:
break
except ValueError:
print "Please enter a number"
print "Number is greater than 10"
Related
as you can see down it's not giving the value of input to the if! why? and how i can make the value of input be stored to Variable (number)
number = input(f"Enter a Number? ")
if number == (1):
print("one")
if number == (2):
print("two or greater")
else:
print("negative number")
Enter a Number? 1
negative number
There are some issues, usually when you use input and expect a number to be submitted, you want to use int() before it to make sure the input is understood as a number (type int). Furthemore, when you want to state an "else-if" statement you should use elif. Finally, the parenthesis are not necessary in your if statement. The following should work:
number = int(input("Enter a Number? "))
if number == 1:
print("one")
elif number >= 2: #I've changed this syntax, because two or greater is written like this
print("two or greater")
else:
print("negative number")
Here is the output I'm trying:
Enter a Number? 3
two or greater
I've just started to learn Python (my first dabble in coding) and this is my first time posting... I hope I'm not abusing the forum by asking this question (I'm essentially asking an expert to help me learn). Please let me know if this is frowned upon in the community.
For this assignment from a Michigan open course, I've been instructed to ask a user for input until the user enters "done", at which point the code should calculate the largest, smallest, sum, and average. In all my test-runs, it's worked fine. But I feel like there's probably a much simpler way to write this code. Can anyone offer suggestions for improvement?
largest = None
smallest = None
count = 0
sum = 0
while True:
try:
num = raw_input("Enter a number: ")
if num == "done" : break
num = float(num)
count = count + 1
sum = sum + num
avg = sum/count
if largest is None:
largest = num
if smallest is None:
smallest = num
if num < smallest:
smallest = num
elif num > largest:
largest = num
continue
except: print 'Invalid input'
print "Maximum is", int(largest)
print "Minimum is", int(smallest)
print "Count:", int(count)
print "Sum:", int(sum)
print "Average:", avg
Well there are a few things here:
you can drop the continue statement since it is the end of the loop anyway;
you can compress the if statements into if largest is None or num > largest: this will shortcircuit and make the loop smaller;
you can use x += y instead of x = x + y; and
you do not have to calculate the average inside the loop; calculating it once when the loop finishes, is enough.
So:
largest = None
smallest = None
count = 0
sum = 0
while True:
try:
num = raw_input("Enter a number: ")
if num == "done" : break
num = float(num)
count += 1
sum += num
if largest is None or num > largest:
largest = num
if smallest is None or num < smallest:
smallest = num
except: print 'Invalid input'
print "Maximum is", int(largest)
print "Minimum is", int(smallest)
print "Count:", int(count)
print "Sum:", int(sum)
print "Average:", sum/count
But in terms of big oh, you cannot improve much: calculating the sum, etc. simply require O(n) and it also costs O(n) to read the input anyway.
Furthermore some software engineering advice: don't use the blanket exception, always specify the exception you expect so:
largest = None
smallest = None
count = 0
sum = 0
while True:
try:
num = raw_input("Enter a number: ")
if num == "done" : break
num = float(num)
count += 1
sum += num
if largest is None or num > largest:
largest = num
if smallest is None or num < smallest:
smallest = num
except ValueError: print 'Invalid input'
print "Maximum is", int(largest)
print "Minimum is", int(smallest)
print "Count:", int(count)
print "Sum:", int(sum)
print "Average:", sum/count
An alternative approach to accomplish this is to store all of the inputs in a list, and then use the built-ins min(),max(),len() and sum() to find values:
num=raw_input("Enter a number: ")
nums=[]
while num!="done": #check if user has finished entering inputs
try:
nums.append(int(num)) #append the input as an integer to a list
num=raw_input("Enter a number: ") #get another input
except ValueError:
print "Invalid input"
print "Maximum is",max(nums)
print "Minimum is",min(nums)
print "Count:",len(nums)
print "Sum: ",sum(nums)
print "Average: ",sum(nums)/len(nums)
Output:
Enter a number: 1
Enter a number: 2
Enter a number: 3
Enter a number: 4
Enter a number: 5
Enter a number: 6
Enter a number: done
Maximum is 6
Minimum is 1
Count: 6
Sum: 21
Average: 3.5
I am a beginner in Python and I was trying to write a small program that asks the user to enter an integer that is greater than 0. The function should keep on asking the user for the number until it is valid.
I tried something like below, however I am getting the wrong results. Can you please help me understand my error?
num = input('please enter a number: ' )
n = int(num)
while n < 0:
num = input('please enter a number: ' )
if n >= 0:
print('Valid number')
else:
print('Invalid number')
Is it possible to start the code without an input function? (like to start with num = int())
Thank You for Your Time
There's an error with the logic behind your code.
You firstly ask the user for a number and if he inputs a number which is greater than or equal to 0, the while-loop will never start (in your script: while n < 0:), which, I assume is fine, because the goal of your program is, as you said, to make "the user to enter an integer that is greater than 0".
If the user inputs a number that is smaller than or equal to 0, the while-loop will start, but will never break because inside of it, the value of variable n never changes, only does the value of num.
This is an appropriate script considering that you want to make the user input a number greater than 0, and that you want to give feedback regarding their input.
n = None
while n <= 0:
n = int(input('please enter a number: '))
if n <= 0:
print('Invalid number')
else:
pass # the loop will break at this point
# because n <= 0 is False
print('Valid number')
The code has the user stuck in a loop until they write a number that's greater than 0.
Another solution would be to, inside the loop, check whether int(num) is greater than 0 and if it is, print 'Valid number' and do break to stop the loop; if it's not, print 'Invalid number' (though then the loop doesn't need to be defined by while n < 0:; rather by while True:.
Also, what do you mean by this:
Is it possible to start the code without an input function? (like to start with num = int())
Please clarify this part.
If your problem is the code not terminating, writing Invalid number all the time it's because you are not updating the value of n. You assigned it just once. The solution to your problem is as follows:
n = -1
while n < 0:
n = int(input('please enter a number: '))
if n >= 0:
print('Valid number')
else:
print('Invalid number')
By the way you get rid of starting the code without an input function.
Edit:
As you just said - you want to keep the input reading despite passing an negative integer into the command line. This should help you accomplish this:
while True:
n = int(input('please enter a number: '))
if n >= 0:
print('Valid number')
else:
print('Invalid number')
This loop will go forever until you exit the program lets say with ctrl + C. while True: is as you see an forever ongoing loop, because the True argument will never be false.
I have just started learning python 2.7.1, and I have written a code for a Cows and Bulls game, in which you need to guess a four digit number by continuously re-entering 4 digits till you get the right number.
But for some reason by code just lasts for 3 loops max. Here is the code:-
number=raw_input("Enter the 4 digit number to be guessed:")
a=map(int,str(number))
def Guess():
yournumber=raw_input("Enter your number now:")
b=map(int,str(yournumber))
i=j=k=0
while i<=3:
if a[i]==b[i]:
j+=1
elif b[i] in a:
k+=1
i+=1
print str(j),"Bulls and "+str(k),"Cows"
return yournumber
Guess()
c=Guess()
if c==number:
print "BINGO! You have guessed the number!"
else:
Guess()
There is actually no loop to keep asking for user input.
In your implementation, there are exactly three calls for the function Guess().
Your implementation:
Guess() # first call
c=Guess() # second call
if c==number:
print "BINGO! You have guessed the number!"
else:
Guess() # third call
#end
Instead, you should loop while the user gets it wrong. Try this block instead:
c=""
while c != number:
c = Guess()
print "BINGO! You have guessed the number!"
I can't seem to get my while loop code to run inside my code. I bet it is very obvious but I cannot seem to find the answer for it. This program is supposed to let you choose how many numbers you want to have randomly chosen and the numbers it can be between. It seems that the while loop doesn't want to work. It skips the while loop and goes to the sleep(10). Thank you for the help!
import random
import time
from time import sleep
x = raw_input("Enter first number you want to be the minimum: ")
y = raw_input("Enter second number you want to be the maximum: ")
a = raw_input("Enter ammount of random numbers you want: ")
p = 1
while p >= a:
print "Your number is " + str(int(random.randint(x - 1,y + 1)))
p = p + 1
sleep(10)
raw_input returns a string. This means you are comparing a string to an integer for your while condition. A quick test shows integers are always "less than" strings.
>>> 10000 > '1'
False
>>> 10000 < '1'
True
Luckily, this behavior is changed in python3 where it throws a TypeError.