Why does this if statement equal this - python

What does the following code print? I know the answer is TIME GREAT. But I don't understand why it isn't Right Cheer. When it sets the score as 10.
score = 10
if score < 10:
print ("NOW")
if score > 2:
print ("RIGHT")
elif score == 10:
print ("CHEER")
else:
print ("TIME")
print ("GREAT")

Your indentation is wrong and you need all elif's after the first if, your first if evaluates to False and the fact you have the others nested means they never get evaluated and you go straight to the else block:
score = 10
if score < 10:
print ("NOW")
elif score > 2:
print ("RIGHT")
elif score == 10:
print ("CHEER")
else:
print ("TIME")
print ("GREAT")

Because input score is 10, which fails the if condition, and will jump to else part. Hence will print, TIME GREAT

Related

My while loop never reaches the conditional stament and keeps looping

The assignment was to make a guessing game where the parameter is the answer. At the end if the person gets it right, it prints a congratulatory statement and returns the number of tries it took, if they type in quit, it displays the answer and tries == -1. other than that, it keeps looping until they get the answer correct.
def guessNumber(num):
tries = 1
while tries > 0:
guess = input("What is your guess? ")
if guess == num:
print ("Correct! It took you" + str(tries)+ "tries. ")
return tries
elif guess == "quit":
tries == -1
print ("The correct answer was " + str(num) + ".")
return tries
else:
tries += 1
When i run it, no matter what i put in it just keeps asking me for my guess.
Since you called your variable num so I'm guessing it's a integer, you were checking equality between an integer and a string so it's never True. Try changing the num to str(num) when comparing, so:
def guessNumber(num):
tries = 1
while tries > 0:
guess = input("What is your guess? ")
if guess == str(num):
print ("Correct! It took you {0} tries. ".format(tries))
return tries
elif guess == "quit":
tries = -1
print ("The correct answer was {0}.".format(num))
return tries
else:
tries += 1
Is the code properly indented?
The body of the function you are defining is determined by the level of indentation.
In the example you pastes, as the line right after the def has less indentation, the body of the function is 'empty'.
Indenting code is important in python
Additionally, for assigning one value to a variable you have to use a single '=', so the:
tries == -1
should be
tries = -1
if you want to assign the -1 value to that variable.

Python 2 Odd or Even numbers

I'm trying to fix a problem like if a number is odd print smth. if even print smth. else. My Python code is as follows ;
import sys
import math
N = int(raw_input().strip())
def dec(num):
if num % 2 == 0 and num != 0:
print 'Not Odd'
elif num == 0:
print 'Case Zero'
else:
print 'Even'
dec(N)
Why I can't compile this code ?
You have a ' within the string enclosed by 's.
Try:
print 'Zero can\'t be odd or even!'
As I see, your indent is bad as well.
Pleas align the elif and else below the if.
You also have a not syntactical problem.
"Not even" and "Odd" are the two possibilities for you which is bad.
I've corrected these errors for you:
def dec(num):
if num % 2 == 0 and num != 0:
print 'Even'
elif num == 0:
print 'Zero can\'t be odd or even!'
else:
print 'Odd'
for N in range(5):
dec(N)
One more thing is that you should think about the question about 0 wheter you really want to say that it's not even.
Ask your math teacher about this.

Why wont else condition work on Python If-else statement? [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 6 years ago.
Improve this question
The code:
#Loop to conduct program. User input required for each option.
count = 1
while count == 1:
score = input("Enter Test Score: ")
if (score >= 90) and (score <= 100):
print "A"
elif (score >= 80) and (score <= 89):
print "B"
elif (score >= 70) and (score <= 79):
print "C"
elif (score >= 60) and (score <= 69):
print "D"
elif (score <= 59):
print "F"
elif (score == quit):
print "Program Finsihed. Goodbye."
count = 0 #Count to end loop
else:
print "Please enter valid response."
All other conditions work, however, if something typed it does not meet the parameters, the code is supposed to prompt them again (which is what the while loop is for). However, an error arises whenever a string that does not match the parameters is attempted.
Don't use input. input on Python 2 tries to evaluate the input as a Python expression, so if you type something like fhqwhgads, Python thinks that's supposed to be Python code and throws an error because there's no fhqwhgads variable.
Use raw_input, which gives you the input as a string. You can then perform string operations on it, or (try to) convert it to an integer and handle the exception if the conversion fails:
while True:
user_input = raw_input("Enter Test Score: ")
if user_input == 'quit':
print "Program Finsihed. Goodbye."
break
try:
score = int(user_input)
except ValueError:
print "Please enter valid response."
continue
if 90 <= score <= 100:
print "A"
elif 80 <= score < 90:
...
Incidentally, quit is one of the few choices you could have made for your "we're done here" option that wouldn't have caused an error with your original code, because there's (usually) an actual quit object for that to resolve to when input tries to treat it as Python code.
There were many problems with your code. I think it would be much easier to see and resolve the issues if you break your code down into functional units. I made two functions: get_score deals with prompting the user for input and score_to_grade converts a number score into a letter score. Doing this makes the code much more readable and easier to refactor, debug, etc. in the future.
def get_score():
while True:
user_in = raw_input("Enter Test Score: ")
try:
return float(user_in)
except ValueError:
if user_in == "quit":
print "Program Finished. Goodbye."
raise SystemExit
print "Please enter valid response."
def score_to_grade(score):
if score >= 90:
return "A"
elif score >= 80:
return "B"
elif score >= 70:
return "C"
elif score >= 60:
return "D"
else:
return "F"
while True:
print score_to_grade(get_score())
quit needs to be in quotes, since it is a string, not a variable:
...
elif (score == "quit")
...

Difference between multiple if's and elif's?

In python, is there a difference between say:
if text == 'sometext':
print(text)
if text == 'nottext':
print("notanytext")
and
if text == 'sometext':
print(text)
elif text == 'nottext':
print("notanytext")
Just wondering if multiple ifs could cause any unwanted problems and if it would be better practice to use elifs.
Multiple if's means your code would go and check all the if conditions, where as in case of elif, if one if condition satisfies it would not check other conditions..
An other easy way to see the difference between the use of if and elif is this example here:
def analyzeAge( age ):
if age < 21:
print "You are a child"
if age >= 21: #Greater than or equal to
print "You are an adult"
else: #Handle all cases where 'age' is negative
print "The age must be a positive integer!"
analyzeAge( 18 ) #Calling the function
>You are a child
>The age must be a positive integer!
Here you can see that when 18 is used as input the answer is (surprisingly) 2 sentences. That is wrong. It should only be the first sentence.
That is because BOTH if statements are being evaluated. The computer sees them as two separate statements:
The first one is true for 18 and so "You are a child" is printed.
The second if statement is false and therefore the else part is
executed printing "The age must be a positive integer".
The elif fixes this and makes the two if statements 'stick together' as one:
def analyzeAge( age ):
if age < 21 and age > 0:
print "You are a child"
elif age >= 21:
print "You are an adult"
else: #Handle all cases where 'age' is negative
print "The age must be a positive integer!"
analyzeAge( 18 ) #Calling the function
>You are a child
Edit: corrected spelling
def multipleif(text):
if text == 'sometext':
print(text)
if text == 'nottext':
print("notanytext")
def eliftest(text):
if text == 'sometext':
print(text)
elif text == 'nottext':
print("notanytext")
text = "sometext"
timeit multipleif(text)
100000 loops, best of 3: 5.22 us per loop
timeit eliftest(text)
100000 loops, best of 3: 5.13 us per loop
You can see that elif is slightly faster. This would be more apparent if there were more ifs and more elifs.
Here's another way of thinking about this:
Let's say you have two specific conditions that an if/else catchall structure will not suffice:
Example:
I have a 3 X 3 tic-tac-toe board and I want to print the coordinates of both diagonals and not the rest of the squares.
I decide to use and if/elif structure instead...
for row in range(3):
for col in range(3):
if row == col:
print('diagonal1', '(%s, %s)' % (i, j))
elif col == 2 - row:
print('\t' * 6 + 'diagonal2', '(%s, %s)' % (i, j))
The output is:
diagonal1 (0, 0)
diagonal2 (0, 2)
diagonal1 (1, 1)
diagonal2 (2, 0)
diagonal1 (2, 2)
But wait! I wanted to include all three coordinates of diagonal2 since (1, 1) is part of diagonal 2 as well.
The 'elif' caused a dependency with the 'if' so that if the original 'if' was satisfied the 'elif' will not initiate even if the 'elif' logic satisfied the condition as well.
Let's change the second 'elif' to an 'if' instead.
for row in range(3):
for col in range(3):
if row == col:
print('diagonal1', '(%s, %s)' % (i, j))
if col == 2 - row:
print('\t' * 6 + 'diagonal2', '(%s, %s)' % (i, j))
I now get the output that I wanted because the two 'if' statements are mutually exclusive.
diagonal1 (0, 0)
diagonal2 (0, 2)
diagonal1 (1, 1)
diagonal2 (1, 1)
diagonal2 (2, 0)
diagonal1 (2, 2)
Ultimately knowing what kind or result you want to achieve will determine what type of conditional relationship/structure you code.
elifis just a fancy way of expressing else: if,
Multiple ifs execute multiple branches after testing, while the elifs are mutually exclusivly, execute acutally one branch after testing.
Take user2333594's examples
def analyzeAge( age ):
if age < 21:
print "You are a child"
elif age > 21:
print "You are an adult"
else: #Handle all cases were 'age' is negative
print "The age must be a positive integer!"
could be rephrased as:
def analyzeAge( age ):
if age < 21:
print "You are a child"
else:
if age > 21:
print "You are an adult"
else: #Handle all cases were 'age' is negative
print "The age must be a positive integer!"
The other example could be :
def analyzeAge( age ):
if age < 21:
print "You are a child"
else: pass #the if end
if age > 21:
print "You are an adult"
else: #Handle all cases were 'age' is negative
print "The age must be a positive integer!"
In your above example there are differences, because your second code has indented the elif, it would be actually inside the if block, and is a syntactically and logically incorrect in this example.
Python uses line indentions to define code blocks (most C like languages use {} to enclose a block of code, but python uses line indentions), so when you are coding, you should consider the indentions seriously.
your sample 1:
if text == 'sometext':
print(text)
elif text == 'nottext':
print("notanytext")
both if and elif are indented the same, so they are related to the same logic.
your second example:
if text == 'sometext':
print(text)
elif text == 'nottext':
print("notanytext")
elif is indented more than if, before another block encloses it, so it is considered inside the if block. and since inside the if there is no other nested if, the elif is being considered as a syntax error by Python interpreter.
When you use multiple if, your code will go back in every if statement to check the whether the expression suits your condition.
Sometimes, there are instances of sending many results for a single expression which you will not even expect.
But using elif terminates the process when the expression suits any of your condition.
Here's how I break down control flow statements:
# if: unaffected by preceding control statements
def if_example():
if True:
print('hey')
if True:
print('hi') # will execute *even* if previous statements execute
will print hey and hi
# elif: affected by preceding control statements
def elif_example():
if False:
print('hey')
elif True:
print('hi') # will execute *only* if previous statement *do not*
will print hi only because the preceding statement evaluated to False
# else: affected by preceding control statements
def else_example():
if False:
print('hey')
elif False:
print('hi')
else:
print('hello') # will execute *only* if *all* previous statements *do not*
will print hello because all preceding statements failed to execute
In the case of:
if text == 'sometext':
print(text)
if text == 'nottext':
print("notanytext")
All the if statements at the same indentation level are executed even if only the first if statement is True.
In the case of:
if text == 'sometext':
print(text)
elif text == 'nottext':
print("notanytext")
When an if statement is True, the preceding statements are omitted/ not-executed.

Creating a high and low game in python and need a lot of help!

Here is the Pseudocode
Print instructions to the user
Start with the variables high = 1000, low = 1, and tries = 1
While high is greater than low
Guess the average of high and low
Ask the user to respond to the guess
Handle the four possible outcomes:
If the guess was right, print a message that tries guesses were required and quit the program
If the guess was too high, print a message that says “I will guess lower.”
If the guess was too low, print a message that says “I will guess higher.”
If the user entered an incorrect value, print out the instructions again.
I don't even know where to begin.
Here's where you begin. Insert the specifications as documentation, then do one at a time, testing along the way.
# Print instructions to the user
### 'print "xyz"' will output the xyz text.
# Start with the variables high = 1000, low = 1, and tries = 1
### You can set a variable with 'abc = 1'.
# While high is greater than low
### Python has a while statement and you can use something like 'while x > 7:'.
### Conditions like 'x > 7', 'guess == number' can also be used in `ifs` below.
# Guess the average of high and low
### The average of two numbers is (x + y) / 2.
# Ask the user to respond to the guess
### Python (at least 2.7) has a 'raw_input' for this, NOT 'input'.
# If the guess was right, print a message that tries guesses were required
# and quit the program
### Look at the 'if' statement for this and all the ones below.
# If the guess was too high, print a message that says “I will guess lower.”
# If the guess was too low, print a message that says “I will guess higher.”
# If the user entered an incorrect value, print out the instructions again.
I've also added a small comment detailing what language elements you should look in to for each section.
You don't say if this is Python 2 or 3. The following should be good for recent versions of 2; I'm not familiar with 3, but it will probably at least get you started there too. Seeing as how this is homework, I'm just going to recommend some things for you to research.
You'll want to get the guesses and check them in a loop. I recommend looking up the while loop.
To get the user inputs, try raw_input.
To output messages, look up print.
Use if for checking the user's responses.
You begin with point one:
print "instructions to the user"
(just change the string to be more informative, that's not a programming problem!-), then continue with point two (three assignments, just like your homework assignment says), then with point three:
while high > low:
There -- that's half your work already (points 1-3 out of 6). What's giving you problems beyond that? Do you know what average means, so (say) guess = (high + low) // 2 is understandable to you, or what? That's all you need for point 4! Do you know how to ask the user a question and get their response? Look up input and raw_input... OK, I've covered the first five of the six points, surely you can at least "get started" now!-)
Ok, this isn't the answer but you need to look at the program:
Print out instructions.
Make a random number or a use your own. (For rand numbers you need to use a modulus divide trick)
Probably using a while loop: check if the number guessed is higher or lower or equal
In case of higher print higher, in case of lower print lower, in case of equal break or call exit (probably breaking will do fine).
Pseudo Code:
print "intructions"
thenumber = rand() % 1000+1
while (true)
getInput(guess);
if (guess > thenumber)
print "Guess lower"
else if (guess < thenumber)
print "Guess higher")
else
exit //or break.
Just pseudo code though.
print ("*********** Hi Lo Game ***********")
import random
x = (random.randint(1,100))
num1 = int(input("Enter your number:"))
while num1 < x:
print ("Too Low")
num1 = int(input("Enter your number:"))
while num1 > x:
print ("Too High")
num1 = int(input("Enter your number:"))
if num1 == x:
print ("Congratulations! You are Correct")
Well working Hi/Low game w/score
from random import randint
import time
print '='*20
print 'The Up / Down Game'
print 'Enter up or down !'
print 'Get 10 in a row for a reward!'
print '='*20
print "= "+'GAME START'+" ="
print '='*20
print ''
ans = ' '
score = 0
while True:
n1 = randint(2,13)
n2 = randint(2,13)
print "I have = %s" % (n1)
ans = raw_input("What do you choose: ")
if ans == 'up':
print "Your number is : "
time.sleep(0.5)
print "."
time.sleep(0.5)
print ". %s" % (n2)
time.sleep(1)
if n1 > n2:
print "Sorry you lost."
time.sleep(2)
print "Final score = %s" % (score)
time.sleep(2)
print "="*20
print "Try Again"
print "="*20
score = 0
elif n1 <= n2:
score += 1
if score > 1:
print "That's %s in a row" % (score)
elif score == 1:
print "Thats 1 point"
elif score == 10:
print "Congratz you got the reward!!!"
elif ans == 'down':
print "Your number is : "
time.sleep(0.5)
print "."
time.sleep(0.5)
print ". %s" % (n2)
time.sleep(1)
if n1 < n2:
print "Sorry you lost."
time.sleep(2)
print "Final score = %s" % (score)
time.sleep(2)
print "="*20
print "Try Again"
print "="*20
score = 0
elif n1 >= n2:
score += 1
if score > 1:
print "That's %s in a row" % (score)
elif score == 1:
print "Thats 1 point"
elif score == 10:
print "Congratz. You got the reward"
else:
tryAgain = raw_input("enter up or down only")

Categories

Resources