When I first started learning about Python, I ran across this program and in my eagerness to learn, I didn’t pay much attention to it. I’m not sure if the instructors told me how deceptively simple it was, but it was when I was first learning about for loops. It looks a little something like this.
What it’s supposed to do is go through the numbers one through ten and find all the even and odd numbers. However, if you’re a dipshit like me, you probably wrote the code somewhat like this.
Who needs all those fancy f’s and squiggly brackets anyway, right? That is until you got something like this.
Let’s go back and take a look at why that won’t work, first of all.
You probably entered just before this something like…
mylist = [ ‘1’, ‘2’, ‘3’, ‘4’ ….. etc]
mylist = [ 1, 2, 3, 4, …. etc ]
Both of those will not work with the code written above. I know that it caused me to tear my hair out in confusion. In the if num % 2 == 0: line, it’s expecting an integer. If you put in the variable mylist = [‘1’, ‘2’, ‘3’, ‘4’… etc ] you’re putting in strings. You might as well ask it to divide an apple by an orange, and seeing if its remainder is a house. It just doesn’t make sense.
Or, alternatively, if you put in the variable mylist = [ 1, 2, 3, 4, … etc], the print(‘Odd number’ + num) is expecting a string, not an integer.
So, then, let’s take a look at how we fix this mess.
Well, for the first thing, it’s going to be all in the variable that you declared. So let’s go with mylist = [‘1’, ‘2’, ‘3’, ‘4’… etc ] first.
Now, the first thing you can probably see is that I’ve added int to if int(num) % 2 == 0: This is because it will try and treat everything inside of the parenthesis as an integer. Also note that in the line print(‘Odd number’ + num), you don’t have to do anything because it already is a string. Remember what you declared your variables as. (mylist = [‘1’, ‘2’, ‘3’, ‘4’… etc ])
Alternatively if you declared your varibles as mylist = [ 1, 2, 3, 4, etc … ] your code would have to look something like this.
Here we have if num % 2 == 0:, because it already is and integer. Here, what we have to do is change it over in the print statements. If you’ll note the str(num) in both of the print statements.
This can work with tuples, too. Mess around with it and try it out. Just remember what you declared your variables as.
I dunno if this helps any of you, but I sure as hell know that it helped me.