Cool Computer Science Thing of the Day
Reading Questions
Quiz
Nested Conditionals
- Just like with loops, we can put any code we want inside a conditional statment block, including more conditionals
- Putting a condition inside of another is equivalent to using the - andoperator- if x > 0: if x < 10: print('x is greater than 0 and less than 10)
Chained Conditionals
- An elseblock is executed if the previous if statement is not true
- It can not have any condition
- An elif, a combination of else and if, is a chimera of anifand anelse.
- It has a condition like an - if, but the condition is only checked if the previous condition was not true- if x < 0: print('x is negative') elif x < 10: print('x is not negative but is less than 10') else: print('x is greater than or equal to 10')
- Each condition in a chain of elifs is only tested if all of the previous were not true
- taking advantage of this, it is sometimes possible to reduce the number of logical operators used
- For example, the following more verbose code is functionally equivalent to the above code - if x < 0: print('x is negative') if x > = 0 and x < 10: print('x is not negative but is less than 10') if x >= 10: print('x is greater than or equal to 10')
Example - Higher or Lower
- Create a game that plays the higher lower guessing game - MIN_NUM = 1 MAX_NUM = 10 NUM_GUESSES = 5 number = random.randrange(MIN_NUM, MAX_NUM) print("I'm thining a of a number between 1 and 10.") for i in range(NUM_GUESSES): guess = int(input("Enter a number: ")) if guess < number: print("Too low.") if guess > number: print("Too high.")
- Want to add an else statement that applies to both if statements
- An else only applies to the one above
- Using an elif the else applies to the two above - if guess < number: print("Too low.") elif guess > number: print("Too high.") else: print("Got it!")
- Also, it keeps asking for input even after correct
- Can use nested conditional, to stop it from asking more - if guess == number: guess = int(input("Enter a number: ")) if guess < number: print("Too low.") elif guess > number: print("Too high.") else: print("Got it!")