How to count how many tries are used in a loop - python

For a python assignment I need to ask users to input numbers until they enter a negative number. So far I have:
print("Enter a negative number to end.")
number = input("Enter a number: ")
number = int(number)
import math
while number >= 0:
numberagain = input("Enter a number: ")
numberagain = int(numberagain)
while numberagain < 0:
break
how do I add up the number of times the user entered a value

i = 0
while True:
i += 1
n = input('Enter a number: ')
if n[1:].isdigit() and n[0] == '-':
break
print(i)
The str.isdigit() function is very useful for checking if an input is a number. This can prevent errors occurring from attempting to convert, say 'foo' into an int.

import itertools
print('Enter a negative number to end.')
for i in itertools.count():
text = input('Enter a number: ')
try:
n = int(text)
except ValueError:
continue
if n < 0:
print('Negative number {} entered after {} previous attempts'.format(n, i))
break
The solution above should be robust to weird inputs such as trailing whitespace and non-numeric stuff.
Here's a quick demo:
wim#wim-desktop:~$ python /tmp/spam.py
Enter a negative number to end.
Enter a number: 1
Enter a number: 2
Enter a number: foo123
Enter a number: i am a potato
Enter a number: -7
Negative number -7 entered after 4 previous attempts
wim#wim-desktop:~$

Related

Syntax issue with my for loop and while loop keeps repeating infinitely (python)

I was working on a for loop and while loop for 2 separate programs asking for the same thing. My for loop is giving me syntax issues and won't come out as expected…
Expectations: A python program that takes a positive integer as input, adds up all of the integers from zero to the inputted number, and then prints the sum. If your user enters a negative number, it shows them a message reminding them to input only a positive number.
reality:
i1 = int(input("Please input a positive integer: "))
if i1 >= 0:
value = 0 # a default, starting value
for step in range(0, i1): # step just being the number we're currently at
value1 = value + step
print(value1)
else:
print(i1, "is negative")
And my While loop is printing "insert a number" infinitly…
Here is what my while loop looks like:
while True:
try:
print("Insert a number :")
n=int(input())
if(n<0):
print("Only positive numbers allowed")
else:
print ((n*(n+1))//2)
except ValueError:
print("Please insert an integer")
`Same expections as my for loop but as a while loop
Anyone know anyway I could fix this issue?
You have some indentation issues. This way works:
while True:
try:
print("Insert a number: ")
user_input = input()
if user_input == 'q':
exit()
n = int(user_input)
if n <= 0:
print("Only positive numbers allowed")
else:
print(n * (n+1) // 2)
except ValueError:
print("Please enter an integer")
Output sample:
Enter a number:
>>> 10
55
Enter a number:
>>> 1
1
Enter a number:
>>> -1
Only positive numbers allowed
Enter a number:
>>> asd
Please enter an integer
Enter a number:
See more about indentation in the docs.

How to change the value within function, then apply it to while loop?

So I have this function:
def check_List(listname, input_num):
if input_num in listname:
print('Duplicated Number')
input_num=0
return input_num
the purpose was to change whatever I input for input_num to become 0 if it's a duplicate in a list and it worked. However, I have a while loop statement that states if the input is less than 1 or greater than 9, it will go into a loop. When I place this fuction into the loop, it does mention that it is a duplicate, but it will keep the original value that was input.
Here's my full code:
guess=[]
while guess != rnd:
count=0
strike=0
ball=0
guess1=int(input("Input First Number: "))
while guess1>9 or guess1<1:
print('Input a number between 1-9')
guess1=int(input("Input First Number: "))
guess.append(guess1)
guess2=int(input('Input Second number: '))
check_List(guess,guess2)
print(guess2)
while guess2>9 or guess2<1:
print('Input a number between 1-9')
guess2=int(input("Input Second Number: "))
guess.append(guess2)
guess3=int(input('Input Thrid number: '))
while guess3>9 or guess3<1:
print('Input a number between 1-9')
guess3=int(input("Input Thrid Number: "))
guess.append(guess3)
guess4=int(input('Input Fourth number: '))
while guess4>9 or guess4<1:
print('Input a number between 1-9')
guess4=int(input("Input Fourth Number: "))
guess.append(guess4)
print(guess, rnd)
I thinkt the behavior you observe might be liked to the fact, that you use check_List only on one input. I propose to clean up the code a little:
counting= ['first', 'second', 'third','fourth']
guess = []
while len(guess) < 4:
c_guess = int(input(f"Input {counting[len(guess)]} Number: "))
if c_guess in guess:
print('Duplicated Number')
continue
if 9 > c_guess >= 1:
guess.append(c_guess)
continue
print('Input a number between 1-9')
You can further improve it by cathing bad(non integer) inputs:
try:
c_guess = int(input(f"Input {counting[len(guess)]} Number: "))
except:
print('Not a valid integer number.')

I'm having problems with how to print multiple outputs from user input

Im new to programming and was set a task where I had to ask the user for there name and a number. I had to print the name where each individual letter is printed on a separate line. The second part is that I had to ask the user to enter a number and that it would repeat the same output by the number given by the user
My code:
name = input("Please enter your name:")
num = input("Please enter a number:")
for index,letter in enumerate(name,1):
for num in range(0,9):
print(letter)
My desired result was this:
Please enter your name: Taki
Please enter a number: 3
T
a
k
i
T
a
k
i
T
a
k
i
the result was this:
Please enter your name: Taki
Please enter a number:3
T
T
T
T
T
T
T
T
T
a
a
a
a
a
a
a
a
a
k
k
k
k
k
k
k
k
k
i
i
i
i
i
i
i
i
i
Plz help
A brute force approach is
name = input('Enter a name: ')
num = int(input('Enter a number: '))
for i in range(num):
for j in name:
print(j)
Here, name is a string which is iterated over each character in the j-loop.
In your code, the num loop from 0 to 9 is wrong. You need to print for num times, not 9 times (0-9). So the range has to be i in range(num). This is why each character was being printed 9 times in your output.
Also, remember to type cast num variable to int while taking the input as Python treats all inputs as string by default.
You have your loops in the wrong order. And your range should be to num not 9
name = input("Please enter your name:")
num = input("Please enter a number:")
for i in range(num):
for letter in name:
print(letter)
name = input("Please enter your name:")
num = input("Please enter a number:")
result = [char for char in name] * int(num)
print('\n'.join(result))
Another way to get it done, using itertools:
import itertools
count = 0
name = input("Please enter your name:")
num = int(input("Please enter a number:"))
for i in itertools.cycle(name):
if count > num * len(name)-1:
break
else:
print(i, end = "\n")
count += 1

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

Python: Continue if variable is an 'int' and has length >= 5

I have a piece of code that does some calculations with a user input number. I need a way to check if user entry is an integer and that entered number length is equal or more than 5 digits. If either one of conditions are False, return to entry. Here is what i got so far and its not working:
while True:
stringset = raw_input("Enter number: ")
if len(stringset)>=5 and isinstance(stringset, (int, long)):
break
else:
print "Re-enter number: "
If anyone has a solution, I'd appreciate it.
Thanks
This would be my solution
while True:
stringset = raw_input("Enter a number: ")
try:
number = int(stringset)
except ValueError:
print("Not a number")
else:
if len(stringset) >= 5:
break
else:
print("Re-enter number")
something like this would work
while True:
number = input('enter your number: ')
if len(number) >= 5 and number.isdigit():
break
else:
print('re-enter number')
Use this instead of your code
while True:
stringset = raw_input("Enter number: ")
if len(stringset)>=5:
try:
val = int(userInput)
break
except ValueError:
print "Re-enter number:
else:
print "Re-enter number:
Do not use isdigit function if you want negative numbers too.
By default raw_input take string input and input take integer input.In order to get length of input number you can convert the number into string and then get length of it.
while True:
stringset = input("Enter number: ")
if len(str(stringset))>=5 and isinstance(stringset, (int, long)):
break
else:
print "Re-enter number: "

Categories

Resources