number = int(raw_input("Enter a number :"))
div = range(0, number)
list = []
while div <= number:
if number % div == 0:
list.append(div)
div =+ 1
print list
this is my code which I made for this exercise :
http://www.practicepython.org/exercise/2014/02/26/04-divisors.html
I am new to programming so i dont know what is wrong with my code but its not giving any output.
I guess this answer is simple enough, and looking from the down-votes people think this too. However... one only learns by asking!
There are three essential mistakes in the code that you propose, and a number of ways to make it more Pythonic.
First, and foremost, dividing by zero is not possible! So you'd want to check numbers in the range (1-number).
Based on the indentation list is printed many times, instead of only at the end of completing the while loop.
You want to avoid using list as a variable because it is a Python keyword.
Then, to make it more Pythonic my proposition is the following:
number = int(input("Enter a number :"))
output = []
for i in range(1,number+1):
if not number%i:
output.append(i)
print(output)
Note that raw_input no longer exists in Python 3.x. Also note that this way we avoid the while loop, that from experience, can easily lead to mistakes. In stead it has been replaced by automatically looping through the entries in the list generated by range(1,number).
Finally a note on range but probably also on semantics. I consider number also to be a divisor of number. To do so I have used range(1,number+1). Because, for example range(5) returns a list up to 5: [0,1,2,3,4]. I.e. it does not include 5.
Here is the code you need:
number = int(input("Enter a number :"))
list = []
# theoretically this is the limit you should test for divisors
for div in range(2, int(number/2 + 1)):
if number % div == 0:
# adds the divisor to the list
list.append(div)
div += 1
# prints all divisors in new line
for item in list:
print(item)
If you are using python 2.7, instead of input use raw_input
Related
I've been coding for about 3 months. Could someone help me understand why my code isn't working? I could look up the answer, but I'd really like to figure out what is going wrong. It runs perfectly the first time through the code, but while it is While-Looping, x always stays as the number inserted into the function. Thanks for your help! The assignment and code is below (for an Udemy class).
Happy Numbers -
A happy number is defined by the following process. Starting with any positive integer, replace the number by the sum of the squares of its digits, and repeat the process until the number equals 1 (where it will stay), or it loops endlessly in a cycle which does not include 1. Those numbers for which this process ends in 1 are happy numbers, while those that do not end in 1 are unhappy numbers. Display an example of your output here. Find first 8 happy numbers.
def find_happy_number(x):
#we need a bunch of lists
digit_list = []
squared_list = []
result_list = []
happy_numbers = []
unhappy_numbers = []
while True:
#break our number into digits
x = str(x)
for digit in x:
digit_list.append(int(digit))
#square each digit and store in list
for digit in digit_list:
squared_digit = digit**2
squared_list.append(squared_digit)
#adds all numbers on that list
result = sum(squared_list)
print(result)
#check to see if it is a happy number
if result == 1:
print(f'{x} is a happy number!')
break
#check to see if it is an un-happy number
if result in result_list:
print(f'{x} is an UN-happy number!')
break
#if it isn't we continue the churning.
#adds result to result list to see if we are looping infinitally
x = result
result_list.append(result)
`
The PROBLEM is that you are not resetting digit_list and squared_list in every loop, so they just keep getting bigger and bigger. Move their initialization into the while loop, or use a list comprehension instead of a loop.
Consider this for your loop:
while True:
digit_list = [int(digit) for digit in str(x)]
squared_list = [digit**2 for digit in digit_list]
Now you don't need to initialize them. Or, for extra fun, combine it all into one:
while True:
result = sum(int(digit)**2 for digit in str(x))
I created a code that takes a list from the user and then asks the user to choose from printing only the odd numbers or the even numbers. But whenever the user choice is taken, the execution freezes. Using keyboard interrupt, I find that the execution stopped in either the odd or even function. Please help !!!
here is the code:
from os import lstat
def odd(lst,oddlst):
for i in range(0,n):
while(lst[i]%2!=0):
oddlst.append(lst[i])
return oddlst
def even(lst,evenlst):
for i in range (0,n):
while(lst[i]%2==0):
evenlst.append(lst[i])
return evenlst
lst = []
oddlst = []
evenlst = []
n = int(input("enter number of elements \n"))
print("\nenter the elements \n")
for i in range(0,n):
num = int(input())
lst.append(num)
print(lst)
choice = input(" Do you want to print odd elements or even elements \n (odd/even)
\n")
if(choice=="odd"):
odd(lst,oddlst)
print(oddlst)
elif(choice=="even"):
even(lst,evenlst)
print(evenlst)
else:
print("invalid choice")
Perhaps you meant to use an if instead of a while in your odd and even functions.
The reason your execution "freezes", is that you run into an infinite loop.
In either while, the i-th element gets checked, then appended to a list. But the condition, against which you are checking, doesn't change, neither does the index i.
Changing your whiles to ifs should solve your problem.
Also, for a more elegant solution to your problem, have a look at:
https://docs.python.org/3/library/functions.html#filter
How to filter a list
The purpose of this program is to find the smallest and largest values in a list. The moment the user inputs a negative number, the program should stop. Here is the code I have written so far:
user_inputs = []
number = int(input())
for i in range(number):
value = int(input())
if i >= 0:
user_inputs.append(value)
else:
break
print(min(user_inputs))
print(max(user_inputs))
As you can see, I am new to programming and still struggling to find the logic behind loops. Surely, this code is ridden with mistakes and any helpful improvements is much appreciated. Thanks in advance.
Brother one mistake that you have done is that you are using
for i in range(number):
basically by doing this you are telling compiler that repeat the code in for loop for "number" of times and obviously number would change every time user inputs a new number resulting in error
The right way to make the code do what you want is :
user_inputs = []
while True:
number = int(input('Enter a positive number : '))
if number >= 0 :
user_inputs.append(number)
else:
print(user_inputs)
print('Smallest number in list is : ',min(user_inputs))
print('Largest number in list is : ',max(user_inputs))
break
Here while loop will run continuously until a negative number has been input, so when a negative number is input the while loop woulb break .
You are checking
i
when you should be checking
value
you have to compare value
i.e. if value >= 0
you are using i which is the number of iteration
I have an assignment for Python to take 2 user inputted numbers (making sure the 1st number is smaller than the second) and to find numbers that are multiples of the first, and divisors of the second.. I'm only allowed to use a while loop (new condition my teacher added today..) I've done it with a for loop:
N_small = int(input("Enter the first number: "))
N_big = int(input("Enter the second number: "))
numbers = ""
if N_small > N_big:
print("The first number should be smaller. Their value will be swapped.")
N_small, N_big = N_big, N_small
for x in range(N_small, N_big+1, N_small):
if N_big % x == 0:
numbers += str(x) + " "
print("The numbers are: ", numbers)
I'm not asking for the answer to how to do this with a while loop - but I just need a hint or two to figure out how to start doing this... Can anyone enlighten me?
Thanks
You can convert any for loop into a while loop trivially. Here's what a for loop means:
for element in iterable:
stuff(element)
iterator = iter(iterable)
while True:
try:
element = next(iterator)
except StopIteration:
break
stuff(element)
Of course that's not what your teacher is asking for here, but think about how it works. It's iterating all of the values in range(N_small, N_big+1, N_small). You need some way to get those values—ideally without iterating them, just with basic math.
So, what are those values? They're N_small, then N_small+N_small, then N_small+N_small+N_small, and so on, up until you reach or exceed N_big+1. So, how could you generate those numbers without an iterable?
Start with this:
element = N_small
while element ???: # until you reach or exceed N_big+1
stuff(element)
element ??? # how do you increase element each time?
Just fill in the ??? parts. Then look out for where you could have an off-by-one error that makes you do one loop too many, or one too few, and how you'd write tests for that. Then write those tests. And then, assuming you passed the tests (possibly after fixing a mistake), you're done.
You don't have to iterate over all the numbers, only the multiples...
small, big = 4, 400
times = 1
while times < big / small:
num = times * small
if big % num == 0: print(num)
times += 1
i know i can use the input function in conjunction with the eval function to input a list of numbers:
numbers = eval(input("enter a list of numbers enclosed in brackets: "))
Also, given a list named items, i can get the list of all the elements of items, except the first one, with
the expression:
items[1:]
im just not sure how to go about getting the program to do what i want it to do
If you have a list and you want to know if the first value appears again later in the list, you can use:
items[0] in items[1:]
That will return True or False depending on whether the first element in items appears again later in items.
Don't use eval, ast.literal_eval is safer
import ast
numbers = ast.literal_eval(raw_input("enter a list of numbers enclosed in brackets: "))
An easier solution will be
x = l[0]
l[0] = None
print x in l
l[0] = x
The advantage is that you don't need to recreate the list
There are two parts to your problem:
get a list of numbers from the user
check if the first number is repeated in this list
There are several ways to get a list of numbers from a user. Since you seem to be new to python, I will show you the easiest way to program this:
n = raw_input("How many numbers in your list?: ")
n = int(n) # assuming the user typed in a valid integer
numbers = []
for i in range(n):
num = raw_input("enter a number: ")
num = int(num)
numbers.append(num)
# now you have a list of numbers that the user inputted. Step 1 is complete
# on to step 2
first_num = numbers[0]
for n in numbers[1:]:
if n == first_num:
print "found duplicate of the first number"
Now, there are more elegant ways to accomplish step 1. For example, you could use a list comprehension:
numbers = [int(n) for n in raw_input("Enter a bunch of space-separated numbers: ").split()]
Further, step 2 can be simplified as follows:
if numbers[0] in numbers[1:]:
print "found duplicates of the first number"
Hope this helps