I was following a lesson on for loops that told me, as an assignment, using for loops, to print out the even numbers from 1-10, and then print out how many even numbers there are. I was playing around with that and came to this solution:
number_even = 0
for i in range(1,10):
if i % 2 == 0:
print(i)
number_even += 1
if i:
print ('We have', number_even, 'even numbers')
I understand everything up until
if i:
print ('We have', number_even, 'even numbers')
I honestly was just playing around with Python, but dont understand how I get an expected output from this code. Please help.
Your code is generally fine but the last if has no sense - you can just delete that condition and leave print statement.
if some_number evaluates to True if and only if some_number is 0 (with assumption it's an integer)
But let me share one more version of this task that can help you understand python a bit more:
even_numbers = [] # This will be our list of even numbers
for i in range(1,10):
if i % 2 == 0:
even_numbers.append(i) # We add number to the list
print(even_numbers)
print ('We have', len(even_numbers), 'even numbers')
At the end of your loop, i=9, that's why it prints. If you set i=0 before if i: but after the loop, nothing prints.
if i: is equivalent to if i!=0:
I think your confusion comes from the confusing nature of Python scopes.
The variable i doesn't fall out of scope when your loop ends, like it might in other languages. So, when you reach if i, this will succeed because i == 9
Related
Have a little problem. I'm writing a simple program that takes an input of numbers (for example, 1567) and it adds the odd numbers together as well as lists them in the output. Here is my code:
import math
def oddsum(n):
y=n%10
if(y==0):
return
if(y%2!=0):
oddsum(int(n/10))
print (str(y),end="")
print (" ",end="")
else:
oddsum(int(n/10))
def main():
n=int(input("Enter a value : "))
print("The odd numbers are ",end="")
oddsum(n)
s = 0
while n!=0:
y=n%10
if(y%2!=0):
s += y
n //= 10
print("The sum would be ",end=' ')
print("=",s)
return
main()
It outputs just fine, in the example it will print 1 5 and 7 as the odd numbers. However, when it calculates the sum, it just says "7" instead of 13 like it should be. I can't really understand the logic behind what I'm doing wrong. If anyone could help me out a bit I'd appreciate it :)
I understand it's an issue with the "s += y" as it's just adding the 7 basically, but I'm not sure how to grab the 3 numbers of the output and add them together.
As #Anthony mentions, your code forever stays at 156 since it is an even num.
I would suggest you directly use the string input and loop through each element.
n = input("Enter a value : ") #'1567'
sum_of_input = sum(int(i) for i in n if int(i)%2) #1+5+7=13
[print(i, end="") for i in n if int(i)%2] #prints '157'
Note that int(i)%2 will return 1 if it is odd.
1567 % 10 will return 7. You might want to add the numbers you printed in oddsum to a list, and use the sum function on that list to return the right answer.
The immediate issue is that n only changes if the remainder is odd. eg 1,567 will correctly grab 7 and then n=156. 156 is even, so s fails to increment and n fails to divide by 10, instead sitting forever at 156.
More broadly, why aren't you taking advantage of your function? You're already looping through to figure out if a number is odd. You could add a global parameter (or just keep passing it down) to increment it.
And on a even more efficient scale, you don't need recursion to do this. You could take advantage of python's abilities to do lists. Convert your number (1567) into a string ('1567') and then loop through the string characters:
total = 0
for c in '1567':
c_int = int(c)
if c_int%2!= 0:
total += c_int
print(c)
print(total)
Please can anyone explain the continue statement, I have been trying my best to break it down to my understanding but all efforts have been futile. Here is a sample program I found in the python docs and I can't understand it.
for num in range(2, 10):
if num % 2 == 0:
print("Found an even number", num)
continue
else:
print("Found a number", num)
The continue statement causes Python to skip the rest of the current iteration of the loop, and jump to the beginning of the next iteration.
See this documentation page for Python 3. The original example on that page is:
>>> for num in range(2, 10):
... if num % 2 == 0:
... print("Found an even number", num)
... continue
... print("Found a number", num)
Found an even number 2
Found a number 3
Found an even number 4
Found a number 5
Found an even number 6
Found a number 7
Found an even number 8
Found a number 9
When continue is encountered, the print at the end of the loop is skipped, and execution goes to the for again to get the next iteration. Note how for even numbers, "Found an even number" is printed, but "Found a number" is not printed. This is because the continue skipped the rest of the loop body.
Your modification to the sample - inserting the else - makes the continue obsolete, because the print("Found a number", num) wouldn't be executed anyway (it sits in an else) branch.
This way you've discovered that continue (and also break) are often an alternative control flow mechanism to if...else. Which to use depends on the situation and style preferences.
I want to print :
1
12
123
1234
and i have tried:
num=int(input("number"))
space=int(num)
count=1
while count<num:
if count==1:
print(" "*space,count)
count=count+1
space=space-1
while count>=2:
for n in range(2,num):
print(" "*space,list(range(1,n))
space=space-1
But it doesn't work.
How can i print the designated result ?
Thanks
print(" "*space,list(range(1,n))
Count the parentheses on this line. One of them isn't closed, which it has to be to work as you intend.
Also note that your while loop will never stop running.
As a general rule of thumb, whenever you know exactly how many times you should do something, you should use a for loop instead of a while loop
Let's try to rewrite you code using a for loop:
num=int(input("number"))
output = ""
for n in range(1,num+1):
output = ''.join([output, str(n)])
space = ' ' * (num - len(output))
print(space, output, sep='')
The only real substantive change I made other than a for loop is treating the output as a string rather than a list of numbers.
I have the following code, and I am trying to find the largest prime factor of the number that is square rooted in variable a. When I do some print testing, it doesn't seem my iterator is increasing. The code just runs infinitely it seems. Any tips? Am I missing a point where this becomes an infinite loop?
import math
a = math.sqrt(600851475143)
primefactors = [0]
i=1
while i<=a:
if a%i == 0:
if i%2 != 0 and i%3 != 0 and i%4 != 0 and i%5 != 0 and i%6 != 0 and i%7 != 0 and i%8 != 0 and i%9 != 0:
primefactors.append(i)
print(primefactors)
i=i+1
edit: just realized my mistake of using a as both upper-bound and the test value. Thank you for all the answers!
a is 775146.099225, so a%i==0 is never true, so even if your iterator worked (and it is working for me), you won't get anything added to prime factors.
The first thing I would try is printing out your i variable at the end of the loop after you increment and make sure it increments.
Your programs should loop 775146 times. This could possible take some time. I would try it with a smaller number first and then see what happens.
I mostly have experience programming in visual basic, and am trying to learn python. I am trying to make a conditional loop in the form of a do until loop. I am not sure how to do it in python and i could use some help. I have a do until loop with an if statement within it. this is what i have.
number = 18
do while number = 1
if number%2==0 then
number = number/2
else number = (number*3)+1
loop
print(number)
Any help would be great. Thanks
There is no do … while loop in Python. I believe somewhere in the FAQ it explains why, and how to work around it.
But that doesn't matter because what you've written isn't a do … while loop, it's just a plain while loop. The whole point of a do … while in every language that has one is that you put the test condition after the loop body, instead of before, which guarantees that the loop will run at least once, and which allows you to avoid doing pre-loop setup that you'd have to duplicate inside the loop.
So, to translate your code to Python:
number = 18
while number == 1:
if number%2==0:
number = number/2
else:
number = (number*3)+1
print(number)
However, it's worth noting that since number = 18 before the loop, it will never be == 1 the first time through, so this is just going to skip the whole thing and print out 18.
You may have wanted while number != 1 or while number > 1, but you have to figure out what you actually want to write before anyone can write it.
There is no 'do/while' in Python. The closest is a loop that is guaranteed to loop once then get an exit test after 1 iteration.
while True: # kinda like 'do'
# do something at least once
if fail_condition(): # here is your 'while' test
break # end the loop if 'fail_condition' is True
# loop again if 'fail_condition' is not True
Roughly your code (Collatz/Hailstone?) would look like this:
number, i = 18, 0
while number>1:
i+=1
if number%2==0:
number = number/2
else:
number = (number*3)+1
print 'Reached {} after {} loops'.format(number,i)
# prints 'Reached 1 after 20 loops'
is that above code even in python? instead of do while, have it just be while. and after the if statement, dont have then. a quick reformatting would look something like this:
number = 18
while number == 18:
if number%2==0:
number = number/2
else:
number = (number*3)+1
print(number)
do while is not a usual construct in python. Simply use a while loop.
https://wiki.python.org/moin/WhileLoop
Your code could be modified as follows for instance.
number = 18
while number == 1:
if ( number % 2 ) == 0:
number = number / 2
else:
number = ( number * 3 ) + 1
print number
One of the biggest differences between these languages is that python is all about tab delimitation. You need not specify the start and end of a loop, the tabs do that for you. Additionally not the ':'s after conditional statements.
I would note however that the above code would not yield any valid answer. Perhaps you meant for the loop to run while number was not equal to 1?