How to count the output of a conditional statement in python? - python

i made this code and i want it to tell me how many times it used to find the number i put in, and i want to tell how many times it should repite the action of finding the "stop_at"
print 'first write the random int (lowest number first)'
imp1 = float(raw_input())
imp2 = float(raw_input())
print 'the prosess will be between', imp1, 'and', imp2, 'when do you want to stop the opperation'
stop_at = float(raw_input())
while True:
num = random.randint(imp1, imp2)
if num == stop_at:
print
print
print stop_at, "were found after", ..., 'tryes'
print ' '
break
print num

You can add a counter
imp1 = int(raw_input("Enter low guess"))
imp2 = int(raw_input("Enter high guess"))
stop_at = int(raw_input("Enter the number you want guessed"))
i = 0
while True:
i += 1
num = random.randint(imp1, imp2)
if num == stop_at:
print "\n\n{0} was found after {1} tries\n\n".format(stop_at, i)
print num

First, You can't use float values as input parameters for random.randint function. Input parameters must be of type integer.
Second, same goes for stop_at. It must be integer, since random.randint will return integer (it MIGHT be float, but only if it is in form 2.0, 11.0...).
Third, You should introduce counter and increase it in if part of the code to get number of hits. Also, You should introduce counter which will be placed right inside while loop which will tell You how many loops were there.

Introduce some count variable that you will increment with each loop pass.
cnt = 0
while True:
num = random.randint(imp1, imp2)
cnt += 1
if num == stop_at:
print
print
print stop_at, "were found after tryes {}".format(cnt)
print
break
print num

Related

Need help understanding while-loops and what it is doing

I am learning Python, and currently I am learning about sentinel loops. I have this piece of code that I need help understanding. What exactly is the while-loop doing? I did some research and I know it is looping through the if-statement (correct me if I am wrong); but is it looping through a specific equation until the user stops inputting their integers? Thank you in advanced.
(Please no hate comments I am still learning as a developer. & this is my first post Thanks)
even = 0 odd = 0
string_value = input("Please enter an int. value: ")
while string_value !="":
int_value = int(string_value)
if int_value % 2 == 0:
even += 1
else:
odd += 1
string_value = input("Please enter an int. value: ")
if even + odd == 0:
print("No values were found. Try again...") else:
print("Number of evens is: ", str(even)+".")
print("Number of odd is: ", str(odd)+".")
---Updated Code:
def main():
print("Process a series of ints enter at console \n")
count_even = 0
count_odd = 0
num_str = input("Please enter an int. value or press <Enter> to stop: ")
#Process with loop
while num_str !="":
num_int = int(num_str)
if num_int % 2 == 0:
count_even += 1
else:
count_odd += 1
num_str = input("Please enter an int. value: ")
if count_even + count_odd == 0:
print("No values were found. Try again...")
else:
print("Number of evens is: ", str(count_even)+".")
print("Number of odd is: ", str(count_odd)+".")
main()
First thing the while loop does is check if the user input is emptywhile string_value !="", if it is not empty than it will start the loop. The != means not equals and the "" is empty so not equals empty. Next it sets the variable int_value as the integer of the user input(will error if user inputs anything other than whole number). Next it checks if the variable int_value % 2(remainder of division by 2) is 0, so pretty much it checks if the number is divisible by 2, if it is divisible by two it will add 1 to the even variable. Otherwise it will add 1 to the odd variable
It will be very helpful if you go through python doc https://docs.python.org/3/tutorial/index.html
even = 0 odd = 0
The above line even and odd are variables keeping count of even number and odd number.
string_value = input("Please enter an int. value: ")
The above line prompt the user to input an integer
while string_value !="":
int_value = int(string_value)
if int_value % 2 == 0:
even += 1
else:
odd += 1
string_value = input("Please enter an int. value: ")
The above while loop check firstly, if the input is not empty, int() Return an integer object constructed from a number or string x, or return 0 if no arguments are given https://docs.python.org/3/library/functions.html#int. The if statement takes the modulus of the integer value, and then increases the counter for either odd or even.
Finally, the count of odd and even are printed.
the input() function waits until the user enters a string so unless the user enters an empty string the while loop will keep asking the user for strings in this line:
string_value = input("Please enter an int. value: ")
and check if its an empty string in this line:
while string_value !="":

Calculating average from raw_input data in a while loop

Fellow python developers. I have a task which I can't seem to crack and my tutor is MIA. I need to write a program which only makes use of while loops, if, elif and else statements to:
Constantly ask the user to enter any random positive integer using int(raw_input())
Once the user enters -1 the program needs to end
the program must then calculate the average of the numbers the user has entered (excluding the -1) and print it out.
this what I have so far:
num = -1
counter = 1
anyNumber = int(raw_input("Enter any number: "))
while anyNumber > num:
anyNumber = int(raw_input("Enter another number: "))
counter += anyNumber
answer = counter + anyNumber
print answer
print "Good bye!"
Try the following and ask any question you might have
counter = 0
total = 0
number = int(raw_input("Enter any number: "))
while number != -1:
counter += 1
total += number
number = int(raw_input("Enter another number: "))
if counter == 0:
counter = 1 # Prevent division by zero
print total / counter
You need to add calculating average at the end of your code.
To do that, have a count for how many times the while loop runs, and divide the answer at the end by that value.
Also, your code is adding one to the answer each time because of the line - answer = counter + anyNumber, which will not result in the correct average. And you are missing storing the first input number, because the code continuously takes two inputs. Here is a fixed version:
num = -1
counter = 0
answer = 0
anyNumber = int(raw_input("Enter any number: "))
while anyNumber > num:
counter += 1
answer += anyNumber
anyNumber = int(raw_input("Enter another number: "))
if (counter==0): print answer #in case the first number entered was -1
else:
print answer/counter #print average
print "Good bye!"
There's another issue I think:
anyNumber = int(raw_input("Enter any number: "))
while anyNumber > num:
anyNumber = int(raw_input("Enter another number: "))
The value of the variable anyNumber is updated before the loop and at the beginning of the loop, which means that the first value you're going to enter is never going to be taken in consideration in the average.
A different solution, using a bit more functions, but more secure.
import numpy as np
numbers = []
while True:
# try and except to avoid errors when the input is not an integer.
# Replace int by float if you want to take into account float numbers
try:
user_input = int(input("Enter any number: "))
# Condition to get out of the while loop
if user_input == -1:
break
numbers.append(user_input)
print (np.mean(numbers))
except:
print ("Enter a number.")
You don't need to save total because if the number really big you can have an overflow. Working only with avg should be enough:
STOP_NUMBER = -1
new_number = int(raw_input("Enter any number: "))
count = 1
avg = 0
while new_number != STOP_NUMBER:
avg *= (count-1)/count
avg += new_number/count
new_number = int(raw_input("Enter any number: "))
count += 1
I would suggest following.
counter = input_sum = input_value = 0
while input_value != -1:
counter += 1
input_sum += input_value
input_value = int(raw_input("Enter any number: "))
try:
print(input_sum/counter)
except ZeroDivisionError:
print(0)
You can avoid using two raw_input and use everything inside the while loop.
There is another way of doing..
nums = []
while True:
num = int(raw_input("Enter a positive number or to quit enter -1: "))
if num == -1:
if len(nums) > 0:
print "Avg of {} is {}".format(nums,sum(nums)/len(nums))
break
elif num < -1:
continue
else:
nums.append(num)
Here's my own take on what you're trying to do, although the solution provided by #nj2237 is also perfectly fine.
# Initialization
sum = 0
counter = 0
stop = False
# Process loop
while (not stop):
inputValue = int(raw_input("Enter a number: "))
if (inputValue == -1):
stop = True
else:
sum += inputValue
counter += 1 # counter++ doesn't work in python
# Output calculation and display
if (counter != 0):
mean = sum / counter
print("Mean value is " + str(mean))
print("kthxbye")

While loop is not running properly

I am trying to run a while loop in python. I can get most of it to function correctly but parts of the code are not working correctly and I have been trying different methods to solve it but I can't get it to do exactly what I want.
I am trying to write a program that which repeatedly reads numbers until the user enters “done”. Once “done” is entered, print out the total, count, and average of the numbers. If the user enters anything other than a number, detect their mistake using try and except and print an error message and skip to the next number
Here is my code:
total=0
number=None
count=0
while True:
num=raw_input('Enter a number: ')
print 'Enter a number',num
for intervar in num:
count=count+1
if num=='done':
break
else:
try:
number=int(num)
if number is int:
continue
except:
print 'bad data'
total=total+number
print 'Enter a number:',number
print 'Total is',total
print 'Count is',count
When I enter 3,4,5 The output from this code is:
Enter a number 3
Enter a number 4
Enter a number 5
Enter a number nine
bad data
Enter a number done
Enter a number: 5
Total is 5
Count is 12
The code should read
Enter a number 3
Enter a number 4
Enter a number 5
Enter a number bad data
Enter a number done
Total is 12
Count is 3
Here is your code rearranged a bit:
total=0
count=0
while True:
num=raw_input('Enter a whole number: ')
try:
# just try to convert it
number=int(num)
# success -> accumulate
total += number
count += 1
except ValueError:
# if it isn't an integer, maybe they're done
if num.lower() == 'done':
break
else:
print 'bad data'
print 'Total is',total
print 'Count is',count
And here is an alternative
# keep all the numbers in a list for use later
numbers = list()
while True:
num=raw_input('Enter a whole number: ')
try:
# just try to convert it
numbers.append(int(num))
except ValueError:
# if it isn't an integer, maybe they're done
if num.lower() == 'done':
break
else:
print 'bad data'
print 'Total is', sum(numbers)
print 'Count is', len(numbers)
You've got at least three remaining problems, here
Problem 1
for intervar in num:
count=count+1
At this point num is a string and you are iterating over the characters in that string, incrementing count. The for loop is essentially equal to
count += len(num)
Do you want to count all inputs or only the correctly entered numbers?
Problem 2
The indentation of
total=total+number
is wrong. It must be inside the while loop. Also, use += when adding to a variable.
Problem 3
The is operator compares the object identities of two objects. In this case, the comparison is true, iff number is the class int
if number is int:
continue
What you want is:
if isinstance(number, int):
[...]
However, that is redundant, since after number = int(num) number is always an int.
Use a list to track the numbers, perform calculations at the end of the input session.
numbers = []
while True:
input = raw_input('Enter a whole number: ')
try:
numbers.append(int(input))
except ValueError:
if input is not None and input.lower() == 'done':
break
else:
print 'Invalid input.'
length = len(numbers)
total = sum(numbers)
average = total/count
print 'Total is', total
print 'Count is', length
print 'Average is', average
what you want to do is fix your increment for the total count
total=0
number=None
count=0
while True:
input = raw_input('Enter a whole number: ')
try:
number=int(input)
total += number
except:
if input.lower() == 'done':
break
else:
print 'bad data'
continue
count += 1
print 'Total is',total
print 'Count is',count
print 'Average is', total/count
notice I changed your variable name from num to input since its not always a number... also your check for the type of number was incorrect so I changed that too.. you only want to increment when its a number so I put that in the try... also your count i changed to not loop over all of the characters inputted but rather just count 1 for each time they enter something
an even better way would be to write a number check function
total=0
number=None
count=0
def check_int(str):
if str[0] in ('-', '+'):
return str[1:].isdigit()
return str.isdigit()
while True:
input = raw_input('Enter a whole number: ')
if check_int(input):
total += int(input)
count += 1
elif input.lower() == 'done':
break
else:
print 'bad data'
continue
print 'Total is',total
print 'Count is',count
print 'Average is', total/count
the benefit of this drops the need for a try/except which has considerable overhead
here is the code that prints your expected output.
you had an indentation error and too many prints.
total = 0
number = None
count = 0
while True:
num = raw_input('Enter a number: ')
if num == 'done':
break
else:
try:
number = int(num)
if number is int:
continue
except:
print 'bad data'
count += 1
total += number
print 'Total is',total
average = float(total)/float(count)
print 'average for %s is %s'%(count, average)

Printing min and max function from input of a list

Every time I run the code I get "TypeError: 'int' object is not iterable".
So my question is: How do I print/use the min and max function at the end? So if someone let's say types 5,7,10, and -1. How do I let the user know that the highest score is 10 and the lowest score would be 5? (And then I guess organizing it from highest numbers to lowest.)
def fillList():
myList = []
return myList
studentNumber = 0
myList = []
testScore = int(input ("Please enter a test score "))
while testScore > -1:
# myList = fillList()
myList.append (testScore)
studentNumber += 1
testScore = int(input ("Please enter a test score "))
print ("")
print ("{:s} {:<5d}".format("Number of students", studentNumber))
print ("")
print ("{:s} ".format("Highest Score"))
print ("")
high = max(testScore)
print ("Lowest score")
print ("")
print ("Average score")
print ("")
print ("Scores, from highest to lowest")
print ("")
Your problem is that testScore is an integer. What else could it be? Each time through the list, you reassign it to the next integer.
If you want to, say, append them to a list, you have to actually do that:
testScores = []
while testScore > -1:
testScores.append(testScore)
# rest of your code
And now it's easy:
high = max(testScores)
And, in fact, you are doing that in the edited version of your code: myList has all of the testScore values in it. So, just use it:
high = max(myList)
But really, if you think about it, it's just as easy to keep a "running max" as you go along:
high = testScore
while testScore > -1:
if testScore > high:
high = testScore
# rest of your code
You will get different behavior in the case where the user never enters any test scores (the first one will raise a TypeError about asking for the max of an empty list, the second will give you -1), but either of those is easy to change once you decide what you actually want to happen.
If all your scores are in a array.
print("The max was: ",max(array))
print("The min was: ",min(array))

Loop that uses try/except for input and loops until 'done' is entered

I'm kind of new to coding in Python and I'm trying to write a loop that asks for numerical input and reads it until the user inputs "done", where it will then exit the loop and print the variables: number, count and average. (not trying to store anything in a list)
I also want it to print "invalid input" and continue the loop if the user enters anything that isn't an integer, unless its "done".
Unfortunately it returns "invalid input" and keeps looping even when I enter "done". What am I doing wrong? Could anyone point me in the right direction?
number = 0
count = 0
avg = 0
inp = 0
while True:
try:
inp = int(raw_input('Enter a number: '))
if inp is 'done':
number = number + inp
count = count + 1
avg = float(number/count)
break
except:
print 'Invalid input'
print number
print count
print float(avg)
sum = 0.0
count = 0
while True:
inp = raw_input('Enter a number: ')
if inp == 'done':
break
try:
sum += int(inp)
count += 1
except ValueError:
print 'Invalid input'
print sum
print count
if count != 0: # Avoid division by zero
print sum / count

Categories

Resources