Python if, elif [closed] - python

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 4 years ago.
Improve this question
It's really basic stuff but it gets on my nerves;
Why this code doesn't work properly?
for i in range(0, 101):
if i % 3 == 0 and i != 0:
print '{} Three'.format(i)
elif i % 5 == 0 and i % 3 == 0 and i != 0:
print '{} FiveThree'.format(i)
else:
print "{}".format(i)
Is it because of conditions? So if I want to write the code in this form I must write the complicated condition first and then the simple one?

Any number that is a multiple of both 3 and 5 will make the first if condition true and will never be checked against the second if condition.
You should flip the conditions:
for i in range(0, 101):
if i % 5 == 0 and i % 3 == 0 and i != 0:
print('{} FiveThree'.format(i))
elif i % 3 == 0 and i != 0:
print('{} Three'.format(i))
else:
print("{}".format(i))
But this is wasteful. It checks i % 3 == 0 and i != 0 twice.
I'm leaving the optimization as an exercise.

Your second condition is subset of first condition, so if will never go in that block. Change the order of conditions, it will work
for i in range(0, 101):
if i % 5 == 0 and i % 3 == 0 and i != 0:
print '{} FiveThree'.format(i)
elif i % 3 == 0 and i != 0:
print '{} Three'.format(i)
else:
print "{}".format(i)

The if, elif, else clauses are mutually exclusive. One option is to put the strongest conditions first as DeepSpace suggests. Another option is to have multiple levels of conditions.
for i in range(0, 101):
if i % 3 == 0 and i != 0:
if i % 5 == 0:
print '{} FiveThree'.format(i)
else:
print '{} Three'.format(i)
else:
print "{}".format(i)

Related

Why, using "and" in a for loop and "or" in a while loop gives the same result?

I am trying to practice writing these loops, and I had an exercise which asked me to print numbers from 0 to 20 that aren't divisible by 3 or 5.
For the while loop, I wrote this code:
#solution with while
i = 0
while i < 21:
i += 1
if i % 3 == 0 or i % 5 == 0:
continue
print(i)
Whereas, for the for...in loop, I struggled because I found out that I needed to use and instead of or here.
The code is as follows:
#solution with for
for k in range(21):
if k % 3 != 0 and k % 5 != 0:
print(k)
Why did I have to change the logical operator?
In my head, the first rows of the two codes do the same thing, iterate a number from 0 to 20. So the condition, after these, should be equal for both the iterations used.
Can anyone explain to me what am I missing here?
This isn't a loop type problem, the issue is in using different equality operators in your conditions - != instead of ==.
After changing or to and, the result stays the same because you've accidentally used De Morgan's second law (negation of disjunction):
Now, let's look at the code.
In the while loop:
the program doesn't print i:
if it's divisible by 3 (but not necessarily by 5)
or
if it's divisible by 5 (but not necessarily by 3).
In other words:
the program prints i:
if it's not divisible by 3
and
if it's not divisible by 5.
Noe, let's check, what says the condition in the for...in loop:
the program prints k:
if it's not divisible by 3
and
if it's not divisible by 5.
Looks like the same condition, doesn't it?
As you noticed, in the In other words: paragraph, we've naturally used the negation of disjunction.
To sum up, both programs for i / k lower than 21 print:
0
1
2
4
7
8
11
13
14
16
17
19
If you still aren't sure, try to replace the conditions between loops:
i = 0
while i < 21:
i += 1
if i % 3 != 0 and i % 5 != 0:
print(i)
for k in range(21):
if k % 3 == 0 or k % 5 == 0:
continue
print(k)
In while loop.
if i % 3 == 0 or i % 5 == 0: # this means when i is evenly divided by 3 or 5 then don't do anything.
continue
print(i) # means only print i when i is not evenly divided by 3 and 5
And in the for loop
if k % 3 != 0 and k % 5 != 0: # here this means print i when k is not evenly divided by 3 and 5. Which same as while loop
print(k)
You just reverse order and nothing. You can use the same method in both way and you will get the same result.
While loop
i = 0
while i < 21:
i += 1
if i % 3 != 0 and i % 5 != 0:
print(i)
For Loop
for a in range(21):
if a % 3 != 0 and a % 5 != 0:
print(a)
Because you have also changed the conditions for the results in the while loop you have used ==, but in for loop you have used != if you modify the code you will get the same output by or operator in both
for k in range(21):
if k % 3 == 0 or k % 5 == 0:
continue
print(k)
The two loop types are totally equivalent. You had to use and instead of or, and != instead of ==, because you reversed the logic.
In the first case, you are saying "if the number is divisible then skip it, else print it" while in the second one_ "if the number is not divisible then print (else do nothing)"_.

Syntax Error : what I am missing from Python "for" loop with a range [closed]

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 2 years ago.
Improve this question
I get the idea of what I am supposed to do, but I believe I am missing a step here somehwere... I get a syntax error before from line 1!
range(1, 51)
For answer in range:
if answer % 3 == 0 and answer % 5 ==0
print (“Wolly Bully”)
elseif answer % 3 == 0 and answer % 5 = <0
print (“Wolly”)
elseif answer % 3 = <0 and answer % 5 == 0
print (“Bully”)
elseif answer % 3 = <0 and answer % 5 = <0
print (str(answer) + " ", end = "")
You can define a range with range(1, 51), but range is a function, so you need to do something with the range it returns.
For example:
my_range = range(1, 51)
for answer in my_range:
...
And because you don't need the range for anything else, this is a better solution:
for answer in range(1, 51):
...
There's some more issues with your code, many of them typos - here's a corrected version (not guaranteed to work correctly, but it runs):
for answer in range(1, 51):
if answer % 3 == 0 and answer % 5 == 0:
print("Wolly Bully")
elif answer % 3 == 0 and answer % 5 < 0:
print("Wolly")
elif answer % 3 < 0 and answer % 5 == 0:
print("Bully")
elif answer % 3 < 0 and answer % 5 < 0:
print(str(answer) + " ", end = "")
A couple of types of changes:
elif instead of elseif
a colon after an if or elif
correct indentation
<= instead of = <
correct quotes
no capitalisation on for
space between a function (print) and its argument list
mutually exclusive if and elif expressions (if something is does not meet if x == y, there's not point in elif x <= y and it's clearer to write elif x < y, since that's the only case for which the code will be executed.
You are probably using an unsuitable editor to write your code, given the capitalisation and strange quotes - it's highly recommended to use a programming editor or IDE, like VSCode (free), PyCharm (free Community) or many other (also free) alternatives.
There are several errors, use range with for, it's elif in Python and most comparison operators need to be corrected (<= instead of =>):
for answer in range(1, 51):
if answer % 3 == 0 and answer % 5 == 0:
print("Wolly Bully")
elif answer % 3 == 0 and answer % 5 <= 0:
print("Wolly")
elif answer % 3 <= 0 and answer % 5 == 0:
print("Bully")
elif answer % 3 <= 0 and answer % 5 <= 0:
print(str(answer) + " ", end="")
Out:
Wolly Bully
Wolly Bully
Wolly Bully

Computational complexity of modulos and FizzBuzz

So I don't want to go into whether this is the most perfect code for the FizzBuzz challenge.
For those unfamiliar with FizzBuzz, there are four rules in printing out a range of 1-100:
Print out all numbers;
If the number is divisible by 3, print "Fizz" instead;
If the number is divisible by 5, print "Buzz" instead;
If the number is
divisible by both 3 and 5, print "FizzBuzz".)
I ran two implementations, to compare their speed:
# Code A
%%timeit
for i in range(1,10001):
if i % 15 == 0:
print('FizzBuzz')
elif i % 3 == 0:
print('Fizz')
elif i % 5 == 0:
print('Buzz')
else:
print(i)
# Code B
%%timeit
for i in range(1,10001):
if i % 5 == 0 and i % 3 == 0:
print('FizzBuzz')
elif i % 3 == 0:
print('Fizz')
elif i % 5 == 0:
print('Buzz')
else:
print(i)
Despite the extra if evaluation of Code B, it consistently ran quicker than Code A. Does a larger number result in a slower modulo? What is the underlying reason for this?
The main reason I could think of is perhaps optimization.
Version B uses the same operation a few times, namely:
i mod 5
i mod 3
A reasonably intelligent compiler/interpreter might spot this, and calculate these intermediate results. By doing so, it would be able to immediately calculate the entire if-block with only 2 mod operations.
In short, I think the code that ends up being executed might look something like this:
for i in range(1,10001):
a = i % 5
b = i % 3
if a == 0 and b == 0:
print('FizzBuzz')
elif b == 0:
print('Fizz')
elif a == 0:
print('Buzz')
else:
print(i)
However, the code in block A is perhaps too complicated. By that, I mean the compiler will always be forced to execute 3 mod operations. Unless it would somehow be able to spot that 15 = 3 * 5, and use that logic to re-work the if-statement.

Python, TypeError: 'int' object is not iterable

Slight variation on FizzBuzz problem, just adding one more level.
I have read through the many answers to this Error message on SO, none of them have helped me grasp what I am missing.
So while I really appreciate the answers, what I want is to understand the WHY behind the error.
Can't this task be done using simple loop/if/elif structure, without calling a function?
TypeError: 'int' object is not iterable
def solution(N):
N = 0
for i in N:
if i % 3 == 0 and i % 5 == 0 and i % 7 == 0:
print('FizzBuzzWoof')
elif i % 3 == 0 and i % 5 == 0:
print('FizzBuzz')
elif i % 3 == 0:
print('Fizz')
else:
print(i)
N = N+1
def main():
solution(35)
main()
try this one:
def solution(ints):
for i in range(1, ints+1):
if i % 3 == 0 and i % 5 == 0 and i % 7 == 0:
print('FizzBuzzWoof')
elif i % 3 == 0 and i % 5 == 0:
print('FizzBuzz')
elif i % 3 == 0 and i % 5 == 0:
print('Fizz')
else:
print(i)
def main():
solution(35)
main()
put range(0, ints+1) if you want to start with 0 and include 35
You are trying to iterate through single number. Instead, you can create an array of ints and iterate through it. For instance:
ints = [1, 2, 3]
x.append([4, 5]) #append elements you need
print (x)
#result will be 1,2,3,4,5
And now go with this and iterate through 1 to 5:
for i in ints:
#your logic goes in here
In your code ints is a integer, 35 the provided example. Integers are not collections, thus you cannot use the as the range of a for-loop. As #AndrewLi suggests in his comment, use range(n) to get a iterator containing the elements 0 to n-1.
In your code you also overwrites ints by 0 as the fist thing in the solution function, effectively disregarding the argument parsed to the function. In the code below I have added range(arg), and renamed the argument to arg instead of ints.
def solution(arg):
ints = 0
for i in range(arg):
if i % 3 == 0 and i % 5 == 0 and i % 7 == 0:
print('FizzBuzzWoof')
elif i % 3 == 0 and i % 5 == 0:
print('FizzBuzz')
elif i % 3 == 0 and i % 5 == 0:
print('Fizz')
else:
print(i)
ints = ints+1
def main():
solution(35)
main()

Python FizzBuzz [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 1 year ago.
Improve this question
I have been given this question to do in Python:
Take in a list of numbers from the user and run FizzBuzz on that list.
When you loop through the list remember the rules:
If the number is divisible by both 3 and 5 print FizzBuzz
If it's only divisible by 3 print Fizz
If it's only divisible by 5 print Buzz
Otherwise just print the number
Also remember elif!
I have the following script created, but it gives me an error at if n%3=True
n = input()
if n % 3 = True:
print("Fizz")
else if n % 5 = True:
print("Buzz")
elif print n
Can anyone help? Thank you very much!
A few issues with your code here. The first issue is that, for comparison, you should be using ==, not =, which is for assignment.
The second issue is that you want to check that the remainder of the divisions (which is what the modulo operator calculates) is zero, not that it's true, which doesn't really make sense.
You should be using elif for "otherwise if..." and else for "otherwise." And you need to fix the formatting of your else clause.
You want:
n=input()
if n%3 == 0:
print("Fizz")
elif n%5 == 0:
print ("Buzz")
else:
print n
Finally, your code does not meet the spec:
1) If the number is divisible by both 3 and 5 print "FizzBuzz"
The above will not do this. This part I'm going to leave to you because I'm not here to solve the assignment for you :)
Based on this
FizzBuzz: For integers up to and including 100, prints FizzBuzz if the integer is divisible by 3 and 5 (15); Fizz if it's divisible by 3 (and not 5); Buzz if it's divisible by 5 (and not 3); and the integer otherwise.
def FizzBuzz():
for i in range(1,101):
print {
3 : "Fizz",
5 : "Buzz",
15 : "FizzBuzz"}.get(15*(not i%15) or
5*(not i%5 ) or
3*(not i%3 ), '{}'.format(i))
The .get() method works wonders here.
Operates as follows
For all integers from 1 to 100 (101 is NOT included),
print the value of the dictionary key that we call via get according to these rules.
"Get the first non-False item in the get call, or return the integer as a string."
When checking for a True value, thus a value we can lookup, Python evaluates 0 to False. If i mod 15 = 0, that's False, we would go to the next one.
Therefore we NOT each of the 'mods' (aka remainder), so that if the mod == 0, which == False, we get a True statement. We multiply True by the dictionary key which returns the dictionary key (i.e. 3*True == 3)
When the integer it not divisible by 3, 5 or 15, then we fall to the default clause of printing the int '{}'.format(i) just inserts i into that string - as a string.
Some of the output
Fizz
79
Buzz
Fizz
82
83
Fizz
Buzz
86
Fizz
88
89
FizzBuzz
91
92
Fizz
94
Buzz
Fizz
97
98
Fizz
Buzz
n % 3 (or n % any number) does not evaluate to True or False, it's not a Boolean expression. n % 3 == 0 on the other hand, does.
As an aside, what happens when n % 3 == 0 and n % 5 == 0 both evaluate to True?
Here's how I did it using generators.
Explanations are added as comments.
# the factors to check for, along with its
# associated text data.
FACTORS = {
3 : "Fizz",
5 : "Buzz",
}
def fizzbuzz(start, stop):
"""FizzBuzz printer"""
for i in range(start, stop+1):
string = "" # build string
# iterate through all factors
for j, dat in FACTORS.items():
# test for divisibility
if i % j == 0:
# add data to string if divisible
string += dat
if not string:
# if string's length is 0, it means,
# all the factors returned non-zero
# modulus, so return only the number
yield str(i)
else:
# factor had returned modulo as 0,
# return the string
yield string
if __name__ == "__main__":
for each in fizzbuzz(1, 100):
print(each)
This version has the advantage of not depending on any extra factor checks.
one of the shortest answers i have found is
c=1
while c<101:print((c%3<1)*'Fizz'+(c%5<1)*'Buzz'or c);c+=1
61 characters
Make it universal for any integer, positive or negative.
Also make it easily expandable to other keywords for any integer by creating a dictionary of keywords.
def checkdict(divdict, i):
out = ""
for key in divdict:
if key != 0:
if i%key==0:
out+=divdict[key]
if key == 0 and i == 0:
out+=divdict[key]
if out == "":
out = i
print(out)
if __name__ == "__main__":
mydict = {3:"Fizz",5:"Buzz"}
for i in range(-50,50):
checkdict(mydict, i)
def check(num):
finalWord = ''
for k,v in numWordDict.items():
if num % k == 0:
finalWord += v
if not finalWord:
return num
else:
return finalWord
def FizzLoop(start=0, stop=10, step=1):
for i in range(start, stop, step):
print(check(i))
numWordDict = {3:'fizz', 6:'buzz', 5:'fiver'}
FizzLoop(0, 10)
print("----------")
FizzLoop(0, 50, 5)
Numbers = [3, 5]
Labels = ["Fizz", "Buzz"]
for i in range(1, 101):
Output =""
for j in range (len(Numbers) ) :
if i % Numbers[j] == 0:
Output = Output + Labels[j]
if Output =="" :
print(i)
else:
print(Output)
Nothing fancy, using a while loop to achieve the same result:
x,xx = 1,100
xy,xz = 3,5
mylist = []
while x <= xx:
y = (x/xy).is_integer()
z = (x/xz).is_integer()
if y and z:
mylist.append("fizzbuzz")
elif y:
mylist.append("fizz")
elif z:
mylist.append("buzz")
else:
mylist.append(x)
x+=1
print(mylist)
Please find the 1 liner code (list comprehension) code below. Hope this is easy to understand . if it's not please do let me know. I will elaborate.
N = 10 #user_input
print(list(map(lambda n: "Fizz" if (n % 3 == 0) else ( "Buzz" if (n % 5 == 0) else n),[i for i in range(1,N+1)])))
def fizz_buzz(input):
if (input % 3 == 0) and (input % 5 == 0):
return "FizzBuzz"
if input % 3 == 0:
return "Fizz"
if input % 5 == 0:
return "Buzz"
return input
print(fizz_buzz(15))

Categories

Resources