Python if statement using Modulo - python

I made a list called 'l' then I created a for loop with an if statement inside. The if statement is suppose to check if num is even (equal to 0) if it is then it will print the num if not it will print "Odd number".
Why does the first one print incorrectly ( 2 4 Odd number! )
and the second one prints correctly ( Odd number 2 Odd number 4 Odd number )
I already tried changing the spacing on the first one but I kept getting statement exceptions.
l = [1, 2, 3, 4, 5]
# First
for num in l:
if num % 2 == 0:
print num
else:
print 'Odd number!'
print
print
#Second
for num in l:
if num % 2 == 0:
print num
else:
print 'Odd number!'
Output:
First
2
4
Odd number!
Second
Odd number!
2
Odd number!
4
Odd number!

Indentation. Python uses indentation to figure out scopes in your code, so for your first for loop, it doesn't do anything. Reformat it like this:
for num in l:
if num % 2 == 0:
print num
else:
print 'Odd number!'
The second piece of code was properly indented, that's why it worked.

Python cares about how much whitespace is at the start of a line. This line:
if num % 2 == 0:
is not being considered as part of the for loop.

Related

Program must ask the user for an even integer max six times, if not it ends

The program ask the user for an even integer. If he asks for it 6 times, the program ends. If the number is even, it returns it. My code so far:
i = 0
for i in range(6):
num = int(input("Num: "))
if num % 2 == 0:
print(num)
else:
num = int(input("Num: "))
i+=1
if i == 6:
break
My program doesn't end after user gives 6 not even numbers, how can i fix this?
You don't need to check for i == 6 yourself, this is done automatically by the for loop.
But you need to break out of the loop when an even number is entered.
for i in range(6):
num = int(input("Num: "))
if num % 2 == 0:
print("Success!")
break
else:
print("Failure")
The else: block of a loop is executed if the loop reaches its normal conclusion instead of exiting due to break.
for i in range(6):
num = int(input("Num: "))
if num % 2 == 0:
print(liczba)
break
This will do what you want, without all the extra lines you had.

Python Problem Take input N from the user Print 'EVEN' for every even number Print 'ODD' for every odd number, from 1 to N

enter image description hereEven Numbers!
Take input N from the user and print EVEN for every even number and ODD for every odd number between 1 and N.
Sample Input 1:
4
Sample Output 1:
ODD
EVEN
ODD
EVEN
You need to use the modulus opperator which is % in python to check if the number is odd or even.
N = int(input("Enter a number: "))
i = 1
while(i <= N):
if (i % 2) == 0:
print('EVEN')
else:
print('ODD')
i += 1
N = int(input())
for i in range(1,N+1):
if i%2 == 0:
print("EVEN".format(i))
else:
print("ODD".format(i))

Trouble in designing a game of guessing a list of numbers in python

Today I want to design a game to guess a list of number set by me. The player should print all the 5 numbers to win the game. And it is not allowed to print the repeated number. The code is as followed:
def guess():
print "Please input a number smaller than 10, let's see if it is in my plan."
print "You should figure out all the 5 numbers."
n = int(raw_input('>'))
my_list = [1, 3, 5, 7, 9]
your_list = []
count = 0
while count < 5:
if n in my_list:
if n not in your_list:
your_list.append(n)
count = count + 1
print "Good job! You have got %d numbers!" % count
n = int(raw_input('>'))
else:
print "You have already typed that. Input again!"
n = int(raw_input('>'))
else:
print "That is not what I want."
n = int(raw_input('>'))
print "Here you can see my plan:", my_list
print "You are so smart to guess out, you win!"
guess()
when I tried to run it, I was very confused to see the result:
Please input a number smaller than 10, let's see if it is in my plan
You should figure out all the 5 numbers
>1
Good job! You have got 1 numbers
>2
That is not what I want
>3
Good job! You have got 2 numbers
>5
Good job! You have got 3 numbers
>7
Good job! You have got 4 numbers
>4
Here you can see my plan: [1, 3, 5, 7, 9]
You are so smart to guess out, you win!
When I type 4, it should print "That is not what I want" instead of indicating “win”. Why did it go wrong?
On my side, it was working. Only point not working, I needed to input a 6th element before breaking out of the while loop. I'm just going to provide you with an overview of possible improvement and different implementations.
Moreover, you are using python 2. You should consider moving to python 3 especially if you just started to learn it.
Improvements:
while count < 5: could simply become while sorted(my_list) != sorted(your_list):.
The nested statements can be simplified.
A check on the input would be nice.
Implementation:
def guess_2():
print ("Please input a number smaller than 10, let's see if it is in my plan.")
print ("You should figure out all the 5 numbers.")
# Parameters
my_list = [1, 3, 5, 7, 9]
your_list = []
count = 0
while sorted(my_list) != (sorted(your_list)):
# Input:
not_valid = True
while not_valid:
try:
n = int(input('>'))
not_valid = False
except:
print ("Please input a number.")
if n in my_list and not n in your_list:
your_list.append(n)
count = count + 1
print ("Good job! You have got %d numbers!" % count)
elif n in my_list and n in your_list:
print ("You have already typed that. Input again!")
else:
print ("That is not what I want.")
print ("Here you can see my plan:", my_list)
print ("You are so smart to guess out, you win!")
You just had some logic error in your order of raw_input.
You had one extra one at the very beginning of the code.
And you had a raw_input at the end of each condition. It's better to just have one raw_input at the beginning of the while loop, and display a message based on that input.
With your logic, even after you found all 5 guesses, there was still an input waiting, and no matter what that input would be it would display the win message. So even when you typed 4 at the very end you would get the end message because the count<5 condition was completed but the positioning of the raw_input meant it would still request an input even though you had won.
def guess():
print "Please input a number smaller than 10, let's see if it is in my plan."
print "You should figure out all the 5 numbers."
my_list = [1, 3, 5, 7, 9]
your_list = []
count = 0
while count < 5:
n = int(raw_input('>'))
if n in my_list:
if n not in your_list:
your_list.append(n)
count = count + 1
print "Good job! You have got %d numbers!" % count
else:
print "You have already typed that. Input again!"
else:
print "That is not what I want."
print "Here you can see my plan:", my_list
print "You are so smart to guess out, you win!"
guess()
Here is an example output with my fixed code:
Please input a number smaller than 10, let's see if it is in my plan.
You should figure out all the 5 numbers.
>1
Good job! You have got 1 numbers!
>2
That is not what I want.
>3
Good job! You have got 2 numbers!
>5
Good job! You have got 3 numbers!
>7
Good job! You have got 4 numbers!
>4
That is not what I want.
>9
Good job! You have got 5 numbers!
Here you can see my plan: [1, 3, 5, 7, 9]
You are so smart to guess out, you win!
As of 24th July 2018, the code in question gives indentation errors. Lines 3, 5, 7 and 8 are indented by 3 spaces rather than 4.
When that is corrected the code runs (in Python 2.7), but the "raw_input()" is in the wrong place. In your code:
while count < 5:
# do some stuff
# If previous guess correct, increment count
n = int(raw_input('>')) # This prompts the user again after the 5th success
The raw_input() should be once only:
while count < 5:
n = int(raw_input('>'))
# If previous guess correct, increment count
As Mathieu wrote, user input should always be validated. In this case, if a non-numeric character is entered, the program crashes out with a ValueError exception. This could be caught easily with the Try: Except: idiom:
guess = raw_input('>')
try:
value = int(guess)
except ValueError:
# Handle the error
Another problem is that if "my_list" has one or more duplicate numbers, it is impossible for the game to complete.
One possible solution would be; rather than building a second list for "your_list", you could simply remove elements from "my_list" until there are no elements left:
def guess():
print "Please input a number smaller than 10, let's see if it is in my plan."
print "You should figure out all the 5 numbers."
my_list = [1, 3, 5, 3, 9]
my_plan = str(my_list)
while len(my_list) > 0:
guess = int(raw_input('>'))
try:
int(guess)
except ValueError:
print "'%s' is not a number." % str(guess)
continue
if guess < 0 or guess > 9:
print "ONE digit 0 to 9 please."
else:
if guess in my_list:
my_list.remove(guess) # Remove ONE instance of 'guess'
# or remove ALL instances of 'guess'
# my_list = [num for num in my_list if num != guess]
print "Good job! You have got %d numbers!" % (5 - len(my_list))
else:
print "That is not what I want."
print "Here you can see my plan:", my_plan
print "You are so smart to guess out, you win!"
guess()
(Python 2.x is legacy, Python 3.x is the present and future of the language)

I have an assignment to write odd number

I wanted to print odd numbers as many as input.
Example: input=7
Output: 1,3,5,7,9,11,13
This is what i wrote
a=int(input("input how many odd numbers to print: "))
for i in range(a):
if(i%2==1):
print(i)
Yes, the output is obviously
1
3
5
And i tried this too
a=int(input("input ho many odd numbers to print: "))
i=1
while(i<=a):
if(i%2==1):
print(i)
The output is infinite loop printing the input number
a=int(input("input how many odd numbers to print: "))
for i in range(1,a*2,2):
print(i)
If you really want to use a while loop
i = 1
counter = 0
while counter < a:
if i % 2 == 1:
print(i)
counter += 1
i += 1
In the while-loop, the variable i never changes, so you're just reprinting the same number over and over again. Try this:
while(i<=a):
if(i%2==1):
print(i)
i += 1

What is wrong with my program? it doesnt show up

I am supposed to modify a program so that the loop stops after 3 iterations. It was a non terminating loop before, but I changed it and now it doesn't show up at all. can you see what I did wrong?
i = 1
while_iterations = 1
while (i <= 3):
print("Starting while iteration number", while_iterations)
for number in range(5, 10):
if (number % 2 == 1):
print("Found an odd number: ", number)
else:
print(number, "is not an odd number")
print("End of for loop.")
print()
while_iterations = while_iterations + 1
i=i+1
Your loop doesn't run because i = 1 and the condition is while( i > 3 ) which means it evaluates to false and skips the entire loop.
EDIT:
while_iterations = 1
while (while_iterations <= 3):
print("Starting while iteration number", while_iterations)
for number in range(5, 10):
if (number % 2 == 1):
print("Found an odd number: ", number)
else:
print(number, "is not an odd number")
print("End of for loop.")
print()
while_iterations = while_iterations + 1
There, this loop terminates. You don't need two index variables, while_iterations was enough.
It is stuck in an infinite loop because the condition while (i <= 3): is always True because you never modify i after initially setting it to 1. Try changing the condition to:
while (while_iterations <= 3):
Or you can remove while_iterations and replace all references to it with i.

Categories

Resources