You are on page 1of 6

Week 7 Unit 3 (User Inputs, If, else, elif statements)

OVERVIEW

UNIT 3
First Part:
 Working with user input, error handling using try and except.

User Inputs and  How to use “if” statements to make decisions?


 How to use “elif” statements to make multiple decisions?
Exception Handling  How to use “else” statements to make decisions no matter what?
Second Part:
(User inputs and conditionals; If,
 Understanding list data types
Elif, Else; Lists and Loops)  How and why to use for loops?
 How and why to use while loops?
 Understanding how to work with lists
ECE 106 – COMPUTER PROGRAMMING Prepared by: ENGR. JEANNE M. IMBUIDO
2 By: JMI

USER INPUTS

 Python provides us with two built-in functions to read the input from the
keyboard and this are:
 raw_input ( prompt )

User Inputs
This function works in older version (like Python 2.x). This function takes exactly what is typed from
the keyboard, convert it to string and then return it to the variable in which we want to store.
sample code:

Handling Errors x = raw_input("Enter your name : ")


print x

 input ( prompt )
This function first takes the input from the user and then evaluates the expression, which means
Python automatically identifies whether user entered a string or a number or list. If the input
provided is not correct then either syntax error or exception is raised by python.
sample code:
y = input("Enter your value: ")
print(y)
3 4 By: JMI

ECE 106 - Computer Programming


Prepared by: Engr. Jeanne M. Imbuido 1
Week 7 Unit 3 (User Inputs, If, else, elif statements)

USER INPUTS USER INPUTS


 Typing of data for the input() function is terminated by enter key.  Integer value will be converted to  To correct this, we modify the code by
 We can use input() to enter numeric data also. string in the version 2.x version and specifying its data type at the user input
up: line:
 Prompting for a value
sample code:
name = input('What’s your name?') sample code: sample code:
print (' Hello,' + name + '!') num = input ("Enter number :") num =int((input ("Enter number :")))
print(num) print(num)
print (f'Hello {name} ') # another way using format
name1 = input("Enter name : ") name1 = str(input("Enter name : "))
 Prompting for Numerical Input print(name1) print(name1)
sample code:
#int # Printing type of input value # Printing type of input value
age = input(“How old are you?”) print ("type of number:", type(num)) print ("type of number:", type(num))
age = int(age) print ("type of name:", type(name1)) print ("type of name:", type(name1))
#float
pi = input(“What’s the value of pi?”)
pi = float(pi)
5 By: JMI 6 By: JMI

Converting USER INPUTS HANDLING ERRORS


 Python gives us the ability to type convert easily from one type to another Try and Except
simply by wrapping the type around the variable.  Try and except are used to catch errors.
 converting a variable from one data type to another (str to int)
 It works by trying to run what is inside the try block; if it doesn’t produce an error,
sample code:
num = "9“
then it continues without hitting the except block; however, if an error occurs, then
num = int(num) # re-declaring num to store an integer the code in the except block runs.
print( type(num) ) # checking type to make sure conversion worked before using it to any  using the try and except blocks, use tab to indent where necessary
#calculations
sample code:

 working with user input to perform calculations try:


sample code: ans = float(input("Type a number to add: "))
ans = input("Type a number to add: ") print(type(ans))
print( type(ans) ) # default type is string, must convert print(f"100 + {ans} = {100+ans}")
result = 100 + int(ans) except:
print( f“result = 100 + {ans} = {result}") print("You did not put in a valid number!")
print (type(result)) # without try/except print statement would not get hit if error occurs
print("This program end!")
7 By: JMI 8 By: JMI

ECE 106 - Computer Programming


Prepared by: Engr. Jeanne M. Imbuido 2
Week 7 Unit 3 (User Inputs, If, else, elif statements)

IF STATEMENTS

 In Python, If Statement is used for decision making. It will run the body of
code only when IF statement is true.
 In programming, if statement is known as branching statements

CONDITIONALS
Statement Description
if statements An if statement consists of a boolean expression followed
by one or more statements.
if...else An if statement can be followed by an optional else
statements statement, which executes when the boolean expression is
FALSE.

nested if You can use one if or else if statement inside another if or


statements else if statement(s).

9 10 By: JMI

IF STATEMENTS IF STATEMENTS
Syntax 1:
CLARIFICATIONS:
if expression:
if code/statement(s)
 When you want to justify one condition while the other condition is not true, then you use else:
"if statement". An "if statement" is written by using the if keyword. else code/statement(s)
 An else statement can be combined with an if statement. An else statement contains the Syntax 2:
block of code that executes if the conditional expression in the if statement results to 0 or
if expression1:
a FALSE value. The else statement is an optional statement and there could be at most
if code/statement(s)
only one else statement following if.
elif expression2:
 The elif statement allows you to check multiple expressions for TRUE and execute a
elif code/statement(s)
block of code as soon as one of the conditions evaluates to TRUE.
elif expression3:
*Similar to the else, the elif statement is optional. However, unlike else, for which
elif code/statement(s)
there can be at most one statement, there can be an arbitrary number of elif statements
else:
following an if.
else code/statement(s)
11 By: JMI 12 By: JMI

ECE 106 - Computer Programming


Prepared by: Engr. Jeanne M. Imbuido 3
Week 7 Unit 3 (User Inputs, If, else, elif statements)

IF STATEMENTS IF STATEMENTS
PYTHON CONDITIONS
 using an if statement to only run code if the condition is met
 If statements are used to test for particular conditions and respond appropriately. sample code:
Python supports the usual logical conditions from mathematics: x, y = 5, 10
if x < y:
print("x is less than y")

 A great use for our newly learned conditional statement is for checking user input.
sample code:
ans = int(input("What is 5 + 5? "))
if ans == 10:
print("You got it right!")
else:
print("Your answer is incorrect :(")
 These conditions can be used in several ways, most commonly in "if statements" and
loops.
13 By: JMI 14 By: JMI

IF STATEMENTS IF STATEMENTS

 using an if , elif, else statements:  One line if else statement:  checking more than one or multiple “elif” conditional statement:
sample code: sample code:
sample code:
a = int(input("Enter your 1st number: ")) a = int(input("Enter your 1st number: ")) x = int(input("Enter your 1st number: "))
b = int(input("Enter your 2nd number: ")) b = int(input("Enter your 2nd number: ")) y = int(input("Enter your 2nd number: "))
print (f"a={a} and b={b}") print (f"a={a} and b={b}") print (f"x={x} and y={y}")
print("b is greater than a") if b > a else print ("b less than
if b > a: a") if x > y:
print("b is greater than a") print("x is greater")
elif a == b:  Multiple else statement on the same line: elif (x + 10) < y: # checking if (x+10) is less than y
print ("a equals b") sample code: print("x is less")
else: elif (x + 5) == y: # checking if (x+5) is equal to y
print(“b is less than a") a = int(input("Enter your 1st number: ")) print("equal")
b = int(input("Enter your 2nd number: ")) else:
print (f"a={a} and b={b}") print("conditions are FALSE")
print("A") if a > b else print("=") if a == b else print("B")
15 By: JMI 16 By: JMI

ECE 106 - Computer Programming


Prepared by: Engr. Jeanne M. Imbuido 4
Week 7 Unit 3 (User Inputs, If, else, elif statements)

IF STATEMENTS IF STATEMENTS

 Conditionals Within Conditionals:  If Statements vs. Elif Statements:


writing multiple conditionals within each other - multiple block levels
sample code:
sample code: #1. testing output of two if statements in a row that are both true:
x, y, z = 5, 10, 5 x, y, z = 5, 10, 5
if x > y: if x < y:
print("greater") print("x is less")
elif x <= y: if x == z:
if x == z: print("x is equal")
print("x is equal to z") # resulting output #2. testing output of an if and elif statement that are both true:
elif x != z: x, y, z = 5, 10, 5
print("x is not equal to z") # won't get hit if x < y:
print("x is less")
elif x == z:
print("x is equal to z")

17 By: JMI 18 By: JMI

IF STATEMENTS LOGICAL OPERATORS

 Complete Conditional Statement: Logical Operator “AND”

sample code:
 The “and” logical operator is to ensure that, when you check multiple
#writing a full conditional statement with if, elif, else conditions, both sides of the condition are True. This means that if either the
condition to the left or right of the “and” is False, then the code will not run the
name = "Jeanne" block of code.
if name[0] == "A":
print(f"The Name {name} starts with an A!")  using the keyword 'and' in an 'if statement'
elif name[0] == "B":
print(f"The Name {name} starts with a B!") sample code:
elif name[0] == "J": x, y, z = 5, 10, 5
print(f"The Name {name} starts with a J!") print (f"x={x}, y={y}, z={z}")
else: # covers all other possibilities print ("\n")
print(f"The Name {name} starts with a {name[0]}") if x < y and x == z:
print("Both statements were true")

19 By: JMI 20 By: JMI

ECE 106 - Computer Programming


Prepared by: Engr. Jeanne M. Imbuido 5
Week 7 Unit 3 (User Inputs, If, else, elif statements)

LOGICAL OPERATORS LOGICAL OPERATORS


Logical Operator “OR” Membership Operator “IN”
 The “or” logical operator is used to check for one or both conditions to be  When you want to check if a given object has a value appear in it, you use the
true. Such that if the condition to the left is False and the condition to the right “in” operator.
is True, the block of code will still run because at least one condition was True.  using the keyword 'in' within an 'if statement'
 The only time an “if block” will not run using an “or” operator is when both
sample code:
conditions are False. word = "Volleyball"
 using the keyword ‘or' in an 'if statement' if "b" in word:
print(f"{word} contains the character b")
sample code: print("\n")
x, y, z = 5, 10, 5 word = "Jeanne Imbuido"
print (f"x={x}, y={y}, z={z}") if "r" in word:
print ("\n") print(f"{word} contains the character r")
if x < y or x != z: else:
print("One or both conditions were true") print(f"{word} does not contain the character r")
21 By: JMI 22 By: JMI

LOGICAL OPERATORS
Membership Operator “Not IN”

 if you want to check to see if an object doesn’t include a specific value, you
would use the “not in” operator.
 This is essentially just checking the opposite of the “in” operator.

 using the keyword 'in' within an 'if statement'

sample code:
word = "Jeanne Imbuido"
if "b" in word:
print(f"{word} contains the character b")
if "r" not in word:
print(f"{word} does not contain the character r")

23 By: JMI

ECE 106 - Computer Programming


Prepared by: Engr. Jeanne M. Imbuido 6

You might also like