How can i loop this code - python

So im very new to Python 2.7 and i was wondering how to loop my following code:
def factors(n):
results = set()
for i in xrange(1, int(n**0.5)+1):
if n % i == 0:
results.add(i)
results.add(n / i)
return results
user_input = int(raw_input("Enter an integer: "))
print(factors(user_input))
I would like to be able to enter an integer, get the results and go back to entering another one. I have tried playing with "while True:" loops but couldn't get it to work.
Could someone show me how and why to do it please?
Thanks

user_input = int(raw_input("Enter an integer: "))
while user_input:
print(factors(user_input))
user_input = int(raw_input("Enter an integer: "))
This keeps going until the user inputs 0

If you want the program to keep running until the user enters a particular number, (say k)
user_input = int(raw_input("Enter an integer: "))
while True:
if(user_input == k):
break
print(factors(user_input))
user_input = int(raw_input("Enter an integer: "))

Related

Can someone help me figure out how to run this program successfully? [duplicate]

This question already has answers here:
return statement in for loops [duplicate]
(6 answers)
Closed 1 year ago.
The goal is for the computer to guess a number given an upper and lower bound, the computer should take no as an input and run the program again until a yes is given.
This is the code I am using right now, but the loop only ever runs once dues to where the return function is. If I take that out and jump directly to print it runs continuously.
import random
num1 = int(input("enter your minumum value: "))
num2 = int(input("enter your maximum value: "))
def number_choice(num1,num2):
guess = "no"
while guess == "no":
return random.choice(range(num1,num2))
print (number_choice(num1,num2))
guess = input("is that your number, enter yes or no: ")
Try this:
import random
num1 = int(input("enter your minimum value: "))
num2 = int(input("enter your maximum value: "))
def number_choice(num1,num2):
print(random.choice(range(num1,num2)))
guess='no'
while guess.lower()=='no':
number_choice(num1,num2)
guess = input("Is that your number, enter yes or no: ")
print('Cheers!')
or you can use this too:
import random
num1 = int(input("enter your minimum value: "))
num2 = int(input("enter your maximum value: "))
def number_choice(num1,num2):
print(rnd.choice(range(num1,num2)))
guess=input('Is this your number? Type yes or no ')
if guess=='no':
number_choice(num1,num2)
else:
print('cheers!')
number_choice(num1,num2)
Hope it helps!

How to stop a while loop processing integers with a string

I'm processing integer inputs from a user and would like for the user to signal that they are done with inputs by typing in 'q' to show they are completed with their inputs.
Here's my code so far:
(Still very much a beginner so don't flame me too much)
def main():
print("Please enter some numbers. Type 'q' to quit.")
count = 0
total = 0
num=[]
num = int(input("Enter a number: "))
while num != "q":
num = int(input("Enter a number: "))
count += 1
total += num
del record[-1]
print (num)
print("The average of the numbers is", total / count)
main()
Any feedback is helpful!
You probably get a ValueError when you run that code. That's python's way of telling you that you've fed a value into a function that can't handle that type of value.
Check the Exceptions docs for more details.
In this case, you're trying to feed the letter "q" into a function that is expecting int() on line 6. Think of int() as a machine that only handles integers. You just tried to stick a letter into a machine that's not equipped to handle letters and instead of bursting into flames, it's rejecting your input and putting on the breaks.
You'll probably want to wrap your conversion from str to int in a try: statement to handle the exception.
def main():
num = None
while num != "q":
num = input("Enter number: ")
# try handles exceptions and does something with them
try:
num = int(num)
# if an exception of "ValueError" happens, print out a warning and keep going
except ValueError as e:
print(f'that was not a number: {e}')
pass
# if num looks like an integer
if isinstance (num, (int, float)):
print('got a number')
Test:
Enter number: 1
got a number
Enter number: 2
got a number
Enter number: alligator
that was not a number: invalid literal for int() with base 10: 'alligator'
Enter number: -10
got a number
Enter number: 45
got a number
Enter number: 6.0222
that was not a number: invalid literal for int() with base 10: '6.0222'
I'll leave it to you to figure out why 6.02222 "was not a number."
changing your code as little as possible, you should have...
def main():
print("Please enter some numbers. Type 'q' to quit.")
count = 0
total = 0
num=[]
num.append(input("Enter a number: "))
while num[-1] != "q":
num.append(input("Enter a number: "))
count += 1
try:
total += int(num[-1])
except ValueError as e:
print('input not an integer')
break
print (num)
print("The average of the numbers is", total / count)
main()
You may attempt it the way:
def main():
num_list = [] #list for holding in user inputs
while True:
my_num = input("Please enter some numbers. Type 'q' to quit.")
if my_num != 'q':
num_list.append(int(my_num)) #add user input as integer to holding list as long as it is not 'q'
else: #if user enters 'q'
print(f'The Average of {num_list} is {sum(num_list)/len(num_list)}') #calculate the average of entered numbers by divide the sum of all list elements by the length of list and display the result
break #terminate loop
main()

I am trying to get my program to take only integers and stop when the user presses 0

So the code before behaved properly before my "while type(number) is not int:" loop, but now when the user presses 0, instead of generating the sum of the list, it just keeps looping.
Would really appreciate some help with this! Thank you!
List = []
pro = 1
while(pro is not 0):
number = False
while type(number) is not int:
try:
number = int(input("Please enter a number: "))
List.append(number)
except ValueError:
print("Please only enter integer values.")
if(number == 0):
Sum = 0
for i in List:
Sum = i + Sum
ans = 0
print(Sum)
Actually, this should keep looping forever for all numbers the user may input, not just zero.
To fix this, you can just add this break condition after (or before, it doesnt really matter) appending:
number = int(input("Please enter a number: "))
List.append(number)
if number == 0:
break
So I got it to work, when written like this:
List = []
pro = 1
while(pro is not 0):
while True:
try:
number = int(input("Please enter a number: "))
List.append(number)
break
except ValueError:
print("Please only enter integer values.")
if(number == 0):
Sum = 0
for i in List:
Sum = i + Sum
pro = 0
print(Sum)
But I don't really understand how this is making it only take int values, any clarification would be really helpful, and otherwise thank you all for your help!
I'm guessing that you want to end while loop when user inputs 0.
List = []
pro = 1
while pro is not 0:
try:
number = int(input("Please enter a number: "))
List.append(number)
# This breaks while loop when number == 0
pro = number
except ValueError:
print("Please only enter integer values.")
Sum = 0
for i in List:
Sum += i
print(Sum)
EDIT: I have also cleaned the unnecessary code.
Put if number == 0: inside while type(number) is not int: loop like this:
List = []
while True:
try:
number = int(input("Please enter a number: "))
if number == 0:
Sum = 0
for i in List:
Sum = i + Sum
print(Sum)
break
List.append(number)
except ValueError:
print("Please only enter integer values.")

Changing While loop to a For loop

I am learning about the differences between for loops and while loops in python.
If I have a while loop like this:
num = str(input("Please enter the number one: "))
while num != "1":
print("This is not the number one")
num = str(input("Please enter the number one: "))
Is it possible to write this as a for loop?
Very clumsy. Clearly a for loop is not appropriate here
from itertools import repeat
for i in repeat(None):
num = str(input("Please enter the number one: "))
if num == "1":
break
print("This is not the number one")
If you just wanted to restrict the number of attempts, it's another story
for attempt in range(3):
num = str(input("Please enter the number one: "))
if num == "1":
break
print("This is not the number one")
else:
print("Sorry, too many attempts")
Strictly speaking not really, because while your while loop can easily run forever, a for loop has to count to something.
Although if you use an iterator, such as mentioned here, then that can be achieved.

python loops and arrays

Question: Create a program that allows the user to enter 10 different integers. If the user tries to enter
an integer that has already been entered, the program will alert the user immediately and
prompt the user to enter another integer. When 10 different integers have been entered,
the average of these 10 integers is displayed.
This is my code:
mylist = []
number = int(input("Enter value: "))
mylist.append(number)
while len(mylist) != 10:
number = int(input("Enter value: "))
if number in mylist:
number = int(input("The number is already in the list, enter another number: "))
mylist.append(number)
else:
mylist.append(number)
print(sum(mylist)/float(len(mylist)))
This kind of works but I need to create a loop that will keep on asking the user for another number if the number is in the array. Can you help?
What about:
mylist = []
number = int(input("Enter value: ")) mylist.append(number)
while len(mylist) != 10:
number = int(input("Enter value: "))
while number in mylist:
number = int(input("The number is already in the list, enter another number: "))
mylist.append(number)
print(sum(mylist)/float(len(mylist)))

Categories