0% found this document useful (0 votes)
10 views

Lab2 4a ConditionalStructure

This document discusses conditional structures in programming, including simple choice (if statements), double choice (if-else statements), nested conditions, and multiple choice (if-elif-else statements). It provides examples of Python code that use each type of conditional structure to check conditions and execute different code blocks depending on the results. The examples include programs that check if a number is even or odd, determine the largest of three numbers, and assign a letter grade based on a test score. The document is intended to teach fundamental programming concepts related to conditional logic.

Uploaded by

ana.anacalderon
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
10 views

Lab2 4a ConditionalStructure

This document discusses conditional structures in programming, including simple choice (if statements), double choice (if-else statements), nested conditions, and multiple choice (if-elif-else statements). It provides examples of Python code that use each type of conditional structure to check conditions and execute different code blocks depending on the results. The examples include programs that check if a number is even or odd, determine the largest of three numbers, and assign a letter grade based on a test score. The document is intended to teach fundamental programming concepts related to conditional logic.

Uploaded by

ana.anacalderon
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 7

COMPUTER SCIENCE

FUNDAMENTALS

INTRODUCTION TO PROGRAMMING

Conditional structure

Department of Computer Science


University of Oviedo
Department of Computer Science Computer Science Fundamentals
University of Oviedo Introduction to programming

TABLE OF CONTENTS
1 SIMPLE CHOICE..........................................................................................................................3
2 DOUBLE CHOICE ........................................................................................................................4
3 NESTED CONDITIONS ...............................................................................................................5
4 MULTIPLE CHOICE STRUCTURE ..........................................................................................5
5 EXERCISES ...................................................................................................................................6

Conditional structure Page 2 of 7


Department of Computer Science Computer Science Fundamentals
University of Oviedo Introduction to programming

1 Simple choice
The simple choice structure (if) provides a condition and a sentence (or a block of sentences). If the
condition (cond) is true, then the sentence is executed (sent1); otherwise, no sentence is executed.

In the following example (example1.py), we can see that the condition "number% 2 == 0" is a Boolean
expression whose result is True or False. The line where the condition is written must end with colon (:).
The sentences to be executed if the condition is true, that is, 'print' NUMBER% d IS EVEN '% number
"should be indented.
Run example1.py and check what happens when the condition number% 2 == 0 is true, and when it is
false.
1 # LEARNING OUTCOME: Use the simple choice structure (if)
2 # IMPLEMENTATION: if cond:
3 # sent
4 # DESCRIPTION: This program reads an integer number and shows a
5 # message if it is an even number.
6 # If the number is odd, no message is printed.
7
8 number = int(input("Type an integer number: "))
9 if number % 2 == 0:
10 print ("The number %d is even" %number)

In case a composite sentence must be executed, instead of a single one, all the instructions in the block will
be indented with the same number of blanks. In the following code (example2.py), if the condition is true,
two sentences will be executed (lines 11 and 12).
Run example2.py and check what happens when the condition “number % 2 == 0” is true, and when it is
false.

1 # LEARNING OUTCOME: Use the simple choice (if)


2 # IMPLEMENTATION: if cond:
3 # sent
4 # DESCRIPTION: This program reads an integer number and shows a message
5 # if it is an even number. In addition, another message
6 # appears showing the next number.
7 # If the number is odd, no message is printed.
8
9 number = int(input("Type an integer number: "))
10 if number % 2 == 0:
11 print("The number %d is even," %number)
12 print("and next number is %d" %(number+1))

Note that in example3.py, line 12 has not been indented. Check what happens when you run example3.py,
both if you enter an even and an odd number

1 # LEARNING OUTCOME: Use the simple choice estructure (if)


2 # IMPLEMENTATION: if cond:
3 # sent
4 # DESCRIPTION: This program reads an integer number and shows a message
5 # if it is an even number. Whether the number is even or
6 # odd, it will show us the next number.
7
8 number = int(input("Type an integer number: "))
9 if number % 2 == 0:
10 print("The number %d is even," %number)
11 print("and next number is %d" %(number+1))

Conditional structure Page 3 of 7


Department of Computer Science Computer Science Fundamentals
University of Oviedo Introduction to programming

2 Double choice
In the double choice structure (if-else) two possible sentences are provided to choose one of them,
depending on the result of the condition. If the condition (cond) is true, then the first sentence runs (sent1),
otherwise the second sentence is run (sent2).

The sentence to run if the condition is True (sent1) should be indented; in the case of a composite sentence,
instead of a single one, all the instructions in the block will be indented. The same can be said in case the
condition is False (sent2).

Run the following programs (example4.y and example5.py), and check what happens when the provided
value makes the condition true and false.

1 # LEARNING OUTCOME: Using double choice structure (if-else)


2 # IMPLEMENTATION: if cond:
3 # sent1
4 # else:
5 # sent2
6 # DESCRIPTION: This program reads an integer number and print a message
7 # indicating if this number is even or odd.
8
9 number = int(input("Type an integer number: "))
10 if number % 2 == 0:
11 print("The number %d is even" %number)
12 else:
13 print("The number %d is odd" %number)

1 # LEARNING OUTCOME: Using double choice structure (if-else)


2 # IMPLEMENTATION: if cond:
3 # sent1
4 # else:
5 # sent2
6 # DESCRIPTION: This program reads a mark (FLOAT) and determines if the
7 # student passes (>=5) or fails (<5)
8
9 mark = float(input("Type your mark: "))
10 if mark >= 5.0:
11 print ("PASS")
12 else:
13 print ("FAIL")

Conditional structure Page 4 of 7


Department of Computer Science Computer Science Fundamentals
University of Oviedo Introduction to programming

3 Nested conditions
Alternative structures can be nested; that is, where "sent" appeared in the previous examples, we can write
another choice. As shown in example6.py, the implementation in Python makes visible the nesting of these
structures by the level of indentation of the lines. The lines that use the same indentation are at the same
level of nesting. It is important that each "else" corresponds, in the indentation level, with the appropriate
"if".

The file example6.py corresponds to a program that, after reading three numbers, determines the largest
one of them. To do this, we first check if the first number (number1) is greater than the second (number2).
If it is true, then it checks another condition: if number1 is greater than number3 ("number1> number3").
If this condition is also true, the greatest of the three numbers is number1, so "max = number1".
If the condition is false "number 1> number 3", then the greatest is number3.
The lines of code 24-28 consider the possibility that the condition 'number 1> number 2' is false.

Run example6.py and introduce different combinations of three numbers to check its correct operation.

1 # LEARNING OUTCOME: Using nested conditions


2 # IMPLEMENTATION: if c1:
3 # if c2:
4 # s1
5 # else:
6 # s2
7 # else:
8 # if c3:
9 # s3
10 # else:
11 # s4
12 # DESCRIPTION: This program reads three integer numbers and chooses the
13 # largest one among them.
14
15 number1 = int(input("Type the first number: "))
16 number2 = int(input("Type the second number: "))
17 number3 = int(input("Type the third number: "))
18
19 if number1 > number2:
20 if number1 > number3:
21 max = number1;
22 else:
23 max = number3;
24 else:
25 if number2 > number3:
26 max = number2
27 else:
28 max = number3
29
30 print("The largest of %d, %d, %d is: %d"%(number1,number2,number3,max))

4 Multiple choice structure


Finally, Python provides a multiple choice structure (if-elif-else), that lets you choose among some
alternatives as the result of different Boolean expressions. In fact, it can be implemented through a series
of nested if-else in "cascade", but the syntax if-elif-else is more readable by reducing nesting. The general
idea would be read as "if cond1 is true, then do sent1 else, if cond2 is true, then do sent2 else, if cond3 is
true do cond3, … if any cond is true, do sentF. "

The program example7.py reads a real number and, by means of a multiple choice sentence, determines
the alphabetical label corresponding to the mark. Note that at most one of the conditions is true. If none is,
then the instruction in line 25 of the code will be run.

Conditional structure Page 5 of 7


Department of Computer Science Computer Science Fundamentals
University of Oviedo Introduction to programming

Run the program example7.py several times and write different marks in each execution so you can
check if it works properly.

1 # LEARNING OUTCOME: Use multiple choice structure


2 # IMPLEMENTATION: if cond1:
3 # sent1
4 # elif cond2:
5 # sent2
6 # …
7 # elif condN:
8 # sentN
9 # else:
10 # sentF
11 # DESCRIPTION: This program reads a decimal number representing the
12 # mark of a student in a test, and determines the
13 # alphabetical label associated with that mark. If you
14 # enter a number outside the range [0-10], the mark is
15 # invalid and the program warns you.
16
17 n = float(input("Type your mark: "))
18 if 0 <= n < 5:
19 print("FAIL")
20 elif 5 <= n < 7:
21 print("PASS")
22 elif 7 <= n < 9:
23 print("GOOD")
24 elif 9 <= n <= 10:
25 print("VERY GOOD")
26 else:
27 print("INVALID MARK ")

5 Exercises
Exercise 1. Given the following pieces of code:
x = 0 x = 0
if x >= 0: if x >= 0:
x=x+1 x=x+1
elif x >= 1: if x >= 1:
x=x+2 x=x+2
print("x=%d" %x) print("x=%d" %x)

What is the final value of x in each case?

Exercise 2. Write a program that asks the user to enter three integer numbers and writes a message if they
are in ascending order.

Exercise 3. Write a program that asks the user to enter five integer numbers and choose the largest one.

Exercise 4. Write a program to solve any first-degree equation: ax+b=0, where x is the unknown quantity,
and a and b are two real numbers entered by the user. Consider the case a = 0.

Exercise 5. Write a program that reads an integer number and prints a menu with the following three
options: “a. Calculate the square of the number”, “b. Calculate the cube of the number”, and “c.
Calculate the double of the number”. Note that each option has a letter, thus the user enters a letter
and, depending on it, the program will do the appropriate operation, showing the result to the user.

Exercise 6. Write a program that asks the user to enter 4 integer numbers in the range [0-100], representing
the marks of a student in different tests, and calculate the average mark. Finally, the program will

Conditional structure Page 6 of 7


Department of Computer Science Computer Science Fundamentals
University of Oviedo Introduction to programming

write the average mark and the alphanumeric code associated with it, according with the following
table:
[90,100] A
[80,90) B
[70,80) C
[60,70) D
[0,60) E

Exercise 7. Write a program that asks the user to enter a year (integer number) and determines if this year
is a leap year or not. Review “Lab 2.2: Variables” for more information about leap years.

Examples:
1984 is a leap year because is divisible by 4 and not divisible by 100.
2000 is a leap year because is divisible by 4, by 100 and by 400.
1800 is not a leap year because is divisible by 4 and by 100 but not by 400.
2011 is not a leap year because is not divisible by 4.

Exercise 8. Modify the previous program in such a way that it also reads the number of a month (from 1 to
12) and shows the number of days in that month depending on the month and year introduced.

Conditional structure Page 7 of 7

You might also like