CS-Python-Logic & Conditionals

Introduction to Computer Programming

Python Logic & Conditionals

Logic and conditional statements rely on Boolean values (True or False).  We have the following operations on Boolean values:

Given that x and y are boolean variables, we can complete the given truth tables for different operators

Term:  Logical Conjunction                                                                        Operator:  AND

x

y

x and y

True

True

true

True

False

false

False

True

false

False

False

true

In Python, this would look like:                                Output-Completed by Student

print True and True

print False and True

Term:  Logical Disjunction                                                                Operator:  OR

x

y

x or y

True

True

True

True

False

false

False

True

false

False

False

true

In Python, this would look like:                                Output-Completed by Student

print True or True

print False or True

Term:  Logical Negation                                                                                 Operator:  Not

x

not x

True

false

False

true

In Python, this would look like:                        Output-Completed by Student

print not True

print not False

If-Statements

Python

Scratch Equivalent

x = int(input("Please enter an integer: "))

if x < 0:

    print 'Your number is negative'

elif x == 0:

    print 'Your number is zero'

elif x == 1:

    print 'Your number is one'    

else:

    print 'Your number is greater than one'

Given the following inputs, determine the output

Input

Output-Completed by Student

0

Your number is 0

5

Your number is greater than one

You can also have nested conditional statements:

Python

Scratch Equivalent

x = int(input("Please enter an integer: "))

if x < 0:

    print 'Your number is negative'

elif x == 0:

    print 'Your number is zero'

elif x == 1:

    print 'Your number is one'    

else:

    print 'Your number is greater than one'

   

    if x%2 == 0:

        print "Your number is even"

    else:

        print "Your number is odd"

Input

Output-Completed by Student

0

Your number is zero

5

Your number is odd

Conditional Operators

Code

Operation (in words)

x < y

X less than y

x <= y

X less than or equal to y

x > y

X greater than y

x >= y

X greater than or equal to y

x != y

X not equal to y

Example Code:                                                        Output: Completed by Student

x = 4

y = 3

if x !=y:

    print "These are not equal"

else:

    print "These are equal"

Output : These are not equal

Published by Google DriveReport Abuse–Updated automatically every 5 minutes