why the if-else does not loop - python

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)

Related

Final outputs aren't printing after inputting values

I'm new to lists in python and trying to write a code where one inputs 10 numbers using a list and the following is performed:
Copy the number which is even to a new list named "EvenList" and
output that new list.
Output the average of the numbers stored in the new list.
Here is my code:
List=[]
EvenList=[]
totalnum=0
count=0
for i in range(10):
List.append(int(input("Enter a number: ")))
while List[i]%2==0:
EvenList.append(List[i])
totalnum=totalnum+List[i]
count=count+1
print(EvenList)
average=totalnum/count
print("Average: ", average)
Whenever I run this module, after inputting my values my outputs (both the EvenList and average) aren't printed. Here's the output I get:
Example 1:
Enter a number: 1
Enter a number: 2
Example 2:
Enter a number: 1
Enter a number: 1
Enter a number: 1
Enter a number: 1
Enter a number: 1
Enter a number: 1
Enter a number: 1
Enter a number: 1
Enter a number: 1
Enter a number: 2
By further analysis, I realized whenever an even number was inputted, that's when the code gave an empty output. So I'm speculating my error lies in line 8 - 11 (there may be even more).
I so far changed my inital code:
List[i]=int(input("Enter a number: ")) and EvenList[index]=(List[i])
to
List.append(int(input("Enter a number: "))) and EvenList.append(List[i]) respectively - which I'm still confused as to why the intial code isn't considered to be correct since I thought they did the exact same thing [if someone could explain, it'd be very appreciated] - but that didn't fix this error.
It's because in while loop condition, if the number is even it gets stuck in infinite loop, instead of while add if:
List=[]
EvenList=[]
totalnum=0
count=0
for i in range(10):
List.append(int(input("Enter a number: ")))
if List[i]%2==0:
EvenList.append(List[i])
totalnum=totalnum+List[i]
count=count+1
print(EvenList)
average=totalnum/count
print("Average: ", average)
Here's alternative using list comprehension, sum(), and len() as substitutes of creating EvenList, totalnum, count, and average :
List = [int(input("Enter a number: ")) for i in range(10)]
EvenList = [i for i in List if i % 2 == 0]
average = sum(EvenList)/len(EvenList)
print(EvenList); print("Average: ", average)
Or list comprehension in list comprehension:
EvenList = [i for i in [int(input("Enter a number: ")) for i in range(10)] if i % 2 == 0]
average = sum(EvenList)/len(EvenList)
print(EvenList); print("Average: ", average)

how to print sum of numbers between any given numbers using loop python

how can i print the sum of all the numbers between any two given numbers in python.
i am not allowed to use functions like sum(). i can only use while or for loop.
i have a code which does the job but the problem is it also prints result every time after adding two numbers but i only want it to print final sum of all the numbers.
Here's the code:
...
a = int(input("Please enter a number"))
b = int(input("Please enter a number"))
n = 0
for x in range(a+1,b):
n+=x
print(n)
...
thanks
There is an Indentation Error just check the line below the for loop and give the proper indentation. You can refer to my code
a = int(input("Please enter a number: "))
b = int(input("Please enter a number: "))
n = 0
for x in range(a+1,b):
n+=x
print(n)

Beginner: Creating a list with divisors

I just started learning Python and am stuck with an exercise.
The program should ask the user for a number and then print out a list including all of the number's divisors.
myList = []
usernumber = int(input("Please enter a number: "))
a = int(1)
for a in range(1, usernumber):
while usernumber % a == 0:
divisor = usernumber / a
myList.append(divisor)
a += 1
print(*myList)
This seems to work for everything except 1, but I can't figure out what I have to change to make it work for an input of 1. Any ideas?
Try this:
myList = []
usernumber = int(input("Please enter a number: "))
#No need to declare a as an integer, for loop does that for you.
for a in range(1, usernumber+1):
#usernumber+1 as range() does not include upper bound.
#For each number leading up to the inputted number, if the
#remainder of division is 0, then add to myList.
if usernumber % a == 0:
myList.append(a)
print(myList)

Programming challenge while loops and for loops

I have been asked to make a piece of code including a for loop and a while loop. I was asked to:
Get the user to input a number
Output the times table for that number
Starts again every time it finishes
I was able to do the for loop like so:
num= int(input ("Please enter a number."))
for x in range (1,13):
print (num,"x",x,"=",num*x)
But I cannot figure out how to make it repeat, any ideas?
Just put your code inside a while loop.
while True:
num = int(input("Please enter a number: "))
for x in range(1,13):
print("{} x {} = {}".format(num, x, num*x))
I think it would be nice for you to handle errors.
If a user decides to enter a non digit character it will throw an error.
while True:
num = input('please enter a number')
if num ==0:
break
elif not num.isdigit():
print('please enter a digit')
else:
for x in range(1, 13):
mult = int(num)
print('%d x %d = %d' %(mult, x, mult*x))

How to count how many tries are used in a loop

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:~$

Categories

Resources