t_l = []
n = int(input("Enter your number : "))
t_l.append(n)
while n > 0 :
num = int(input("Enter your number:"))
t_l.append(num)
When the code is ran I can put unlimited inputs in it and each time. The form of inputs is like this:
Enter your number:5
Enter your number:7
Enter your number:61
Enter your number:92
Enter your number:76
But I want better a input form like this:
Enter your number #1:5
Enter your number #2:7
Enter your number #3:61
Enter your number #4:92
Enter your number #5:76
What should I do?
Can use len() with f-string
t_l = []
n = int(input(f"Enter your number #{len(t_l)+1}: "))
t_l.append(n)
while n > 0 :
num = int(input(f"Enter your number #{len(t_l)+1}: "))
t_l.append(num)
You may this piece and it has limit on looping & formatted input as per your need.
t_l = []
n = int(input("Enter your number : "))
t_l.append(n)
index = 1
while n > 0:
num = int(input("Enter your number: #"+str(index)+":"))
t_l.append(num)
if num > n-1 :
break
index = index + 1
Infinite loop is handled and input modified
t_l = []
n = int(input("Enter your number #{}:".format(len(t_l)+1)))
t_l.append(n)
while n - 1 > 0 :
num = int(input("Enter your number #{}:".format(len(t_l)+1)))
t_l.append(num)
n = n-1
Related
I am trying to get the checksum of a seven-digit number input through the keyboard. The input would be restricted to exactly 7 digits. I already have this code below but can't get to restrict it to only 7 digits.
n = int(input("Enter number"))
total = 0
while n > 0:
newNum = n % 10
total = total + newNum
n = n // 10
print(total)
If I enter 4 digits, the code will still run. I just want to restrict it to only 7 digits.
Instead of instantly converting the input to an integer, keep it as a string, so you can make a condition for the length of the input.
something like:
n = input("Enter number ")
m = int(n)
total = 0
while m > 0 and len(n)==7:
newNum = m%10
total = total + newNum
m = m//10
print(total)
You could keep the input number as a string, so that you have an easy way to count and sum over the digits:
s = ''
while len(s) != 7:
s = input("Enter a 7-digit number")
total = sum(int(char) for char in s)
print(total)
num = str(input("Enter a seven-digit number: "))
if len(num) !=7:
print("Please Enter a seven-digit number!")
else:
sumNum = 0
m = int(num)
while m>0:
newnum = m%10
sumNum = sumNum + newnum
m = m//10
print("The sum of its digits is: ",sumNum)
Check the length of the input before turning it into a int.
Since strings can be iterated over, like list, their length can be checked in the same way as lists with the len() function. as so:
if len(n) != 7:
print("input must be seven digits long")
n = input("Enter number")
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")
I find my prog's if-else does not loop, why does this happen and how can I fix it for checking?
my prog supposed that store user's inputs which must between 10 and 100, then delete duplicated inputs.
examples: num=[11,11,22,33,44,55,66,77,88,99]
result: `[22,33,44,55,66,77,88,99]
inList=[]
for x in range(1,11):
num = int(input("Please enter number "+str(x)+" [10 - 100]: "))
if num >= 10 and num <= 100:
inList.append(num)
else:
num = int(input("Please enter a valid number: "))
print(inList)
I found that the if-else only did once, so when I enter invalid num for the 2nd time, the prog still brings me to the next input procedure. What happen occurs?
Please enter number 1 [10 - 100]: 1
Please enter a valid number: 1
Please enter number 2 [10 - 100]:
Additionally, may I ask how can I check the inList for duplicated num, and then remove both of the num in the list?
I'd also suggest a while loop. However the while loop should only be entered if the first prompt is erraneous:
Consider this example:
inList = []
for x in range(1,11):
num = int(input("Please enter number "+str(x)+" [10 - 100]: "))
while not (num >= 10 and num <= 100):
num = int(input("Please enter a valid number [10 - 100]: "))
inList.append(num)
print(inList)
However, may I suggest something else:
This code creates a list of valid inputs ["10","11"...."100"] and if the input which by default is a string is not inside that list we ask for new input. Lastly we return the int of that string. This way we make sure typing "ashashah" doesn't throw an error. Try it out:
inList = []
valid = list(map(str,range(10,101)))
for x in range(1,11):
num = input("Please enter number {} [10 - 100]: ".format(x))
while num not in valid:
num = input("Please enter a valid number [10 - 100]: ")
inList.append(int(num))
print(inList)
I'm no python expert, and I don't have an environment setup to test this, but I can see where your problem comes from.
Basically, inside your for loop you are saying
if num is valid then
add to array
else
prompt user for num
end loop
There's nothing happening with that second prompt, it's just prompt > end loop. You need to use another loop inside your for loop to get num and make sure it's valid. The following code is a stab at what should work, but as said above, not an expert and no test environment so it may have syntax errors.
for x in range(1,11):
i = int(0)
num = int(0)
while num < 10 or num > 100:
if i == 0:
num = int(input("Please enter number "+str(x)+" [10 - 100]: "))
else:
num = int(input("Please enter a valid number: "))
i += 1
inList.append(num)
print(inList)
I spent all day on this code. It failed.
def output (n):
n = int(input('Enter a number: ')
while n != 0:
if n % 5 == 0:
print(n, 'Yes')
n = int(input('Enter a number: ')
if n == 0
output = range(1, int(input('Enter a number: '))+1)
print (output)
output (n)
Question is:
let user enter integers to determine if multiple of 5.
If it is then keep count that will keep a sum of all numbers that are multiples of 5.
Task done using a loop in a function and the loop will terminate when a value of 0 is entered.
when the loop terminates, return the count of how many numbers that were multiple of 5s.
After complete, NEXT:
pass the variable sum_multiple_five to another function called print_result() and still
print the same message but now the print will be done in its own function.
def test(n):
if not n%5:
print (n,'Yes')
return n
else:
print (n,'No')
return 0
total = 0
while True:
n = int(input('Enter a number: '))
if not n:
break
total+=test(n)
print(total)
def sum_multiple_five(n):
count = 0
if n == 0: #initial check if the first input is 0 if it is return count as 0
return count
while n != 0: # not leaving this while loop until n is 0
if n % 5 == 0: #if divisible by 5 increment count by 1 otherwise get new input
count = count + 1
n = int(input('Enter a number: ')) # Update n's value from user input. This is important because n is what the while loop is checking.
return count #when the while loop exit as user input 0 we return count
def print_result(answer):
# print(answer)
print( str(answer) + " numbers were multiple of 5s")
def init():
n = int(input('Enter a number: ')) #get user input and store it in variable n
print_result(sum_multiple_five(n)) #call sum_multiple_five() function and use n as an input. then give the returned int to print_result function
init() #call the function init()
result:
Enter a number: 10
Enter a number: 10
Enter a number: 100
Enter a number: 50
Enter a number: 5
Enter a number: 9
Enter a number: 7
Enter a number: 10
Enter a number: 4
Enter a number: 15
Enter a number: 5
Enter a number: 8
Enter a number: 2
Enter a number: 0
8 numbers were multiple of 5s
I'm writing for creating a list of number from input and get the average of the list. The requirement is: when the user enters a number, the number will be appended to the list; when the user press Enter, the input section will stop and conduct and calculation section.
Here is my code:
n = (input("please input a number"))
numlist = []
while n != '':
numlist.append(float(n))
n = float(input("please input a number"))
N = 0
Sum = 0
for c in numlist:
N = N+1
Sum = Sum+c
Ave = Sum/N
print("there are",N,"numbers","the average is",Ave)
if I enter numbers, everything works fine. But when I press Enter, it shows ValueError. I know the problem is with float(). How can I solve this?
You don't need the float() around the input() function inside your loop because you call float() when you append n to numlist.
this should solve ur prob ,by adding a try,catch block around ur print statement
n = (input("please input a number"))
numlist = []
while True :
numlist.append(float(n))
#####cath the exception and break out of
try :
n = float(input("please input a number"))
except ValueError :
break
N = 0
Sum = 0
for c in numlist:
N = N+1
Sum = Sum+c
Ave = Sum/N
print("there are",N,"numbers","the average is",Ave)