[PDF] [PDF] Boolean expressions – logical operators - COMPSCI 1 1

Python syntax for an if statement In an if statement (selection statement) the code in the if block is executed only if the condition evaluates to True



Previous PDF Next PDF





[PDF] Operators, Expressions and Python Statements - NIELIT

Python programming language assumes any nonzero and nonnull values as true , and if it is either zero or null, then it is assumed as false value Control Statement



[PDF] If Statements in Python - Teaching London Computing

Programming for GCSE Topic 3 1: If Statements in Python Teaching London Result can be 'True' or 'False' Operator Meaning x > y x is greater than y x < y



[PDF] Loops and Conditionals

These operators compare the value of two General Python Syntax rules if test1: statement 1 elif test2: statement 2 else: statement 3 • Both the elif and else  



[PDF] To implement decisions using the if statement • To compare integers

25 août 2019 · An if statement may not need a 'False' (else) branch 8/25/ Some constructs in Python are compound statements The Conditional Operator



[PDF] Chapter 5 : Conditional Statements

Boolean (logical) operators can also be used In a program we make decisions with the if statement: A handout with the Python and JES commands will be



[PDF] (Python) Chapter 2: If Statement, Random Class, Introduction to

In Python, the syntax of the most basic if statement is as follows: if



[PDF] YCL Session 5 Lesson Plan - GlobalHack

ways of constructing conditional statements using new operators, and if/elif/else commands, and Break down a few examples of conditional logic, including various operators ○ Distinguish Python supports Boolean variables What are  



[PDF] Python If Statement With Two Conditions - AWS

statements look at other operators combine these conditions when the beholder Visits can learn about python if statement in this data processing use curly 



[PDF] Boolean expressions – logical operators - COMPSCI 1 1

Python syntax for an if statement In an if statement (selection statement) the code in the if block is executed only if the condition evaluates to True

[PDF] if statement practice exercises in excel

[PDF] if test pin of 8086 is placed at logic 0

[PDF] if two events are independent

[PDF] if x 1/3=k and k=3 what is the value of x

[PDF] if you are contacted by a member of the media about information you are not authorized to share

[PDF] if you go to the court of appeals you will see how many judges

[PDF] if you're writing a formal business report

[PDF] if else statement java exercises pdf

[PDF] ifc logo

[PDF] ifm maurice campus france

[PDF] ifort compiler options

[PDF] ifpi investing in music

[PDF] ifr abbreviations

[PDF] ifr approach chart legend

[PDF] ifr approach plate legend

Lecture 10 -Boolean expressions, if statementsCOMPSCI 1 1Principles of ProgrammingAt the end of this lecture, students should:•be able to evaluate a boolean expression•be familiar with the boolean values, True and False•be able to use conditional statements (if)•be able to use relational operators (>, <, <=, <= and ==)Learning outcomesCompSci 101 -Principles of Programming2Boolean expressions -conditionsA condition is an expression which evaluates to either Trueor FalseAn expression which evaluates to either Trueor Falseis called a booleanexpression.George Boole(1815-1964) invented Boolean algebra. CompSci 101 -Principles of Programming3Boolean expressions -relational operatorsIn Boolean expressions, relational operators are used to compare valuesThe relational operators are:==><>=<=!=equaltogreaterthannotequaltogreaterthanorequaltolessthanlessthanorequaltoCompSci 101 -Principles of Programming4

Boolean variablesVariables can be used to store the result of a comparison, i.e., to store a Booleanexpression.For example:12345678910defmain():exam_mark= 76age = 8points_so_far= 56passed_exam= exam_mark>= 50has_won_game= points_so_far> 70is_old_enough= age > 10is_old_enough= passed_exam!= has_won_gameprint(passed_exam, has_won_game, is_old_enough)main()True False TrueCompSci 101 -Principles of Programming5Complete the outputCompSci 101 -Principles of Programming6123456789defmain():val1 = 50val2 = 53diff = abs(val1 -val2)print("1. ", val1 != val2)print("2. ", val1 >= val2 -3)print("3. ", val2 % 2 == 0)print("4. ", diff < 3)main()1. 2. 3. 4. In all the programs written so far, the statements inside functions are executed in the order in which they are written, e.g., all the statements in the main() function are executed and they are executed sequentially.We would like to be able to control the execution of our code so that blocks of code are only executed if certain conditions are met. Control structures allow us to change the flow of statement execution in our programs. Controlling the flow of executionCompSci 101 -Principles of Programming7A selection statementA decision point in the program•achoice of doing something or not doing it, either do a block of code or not•alters the flow of controlFor example:do first taskdo second taskif time is past noondo last taskeat lunchhave a coffeego for a walkCompSci 101 -Principles of Programming8

Python syntax for an if statementIn anif statement (selection statement) the code in the if block is executed only if the condition evaluates to True. if boolean_expression:statement1statement2If the condition is trueconditional codeIf the condition is falseConditionIndentation is important in Python (indicates the structure of code).• Use either one tab or four spaces.• Be consistent with indentation: four spaces is more commonly used.CompSci 101 -Principles of Programming9if statement -example123456789101112131415import randomdefmain():num_odds= 0num1 = random.randrange(0, 100)ifnum1 % 2 == 1:num_odds= num_odds+ 1num2 = random.randrange(0, 100)ifnum2 % 2 == 1:num_odds= num_odds+ 1num3 = random.randrange(0, 100)ifnum3 % 2 == 1:num_odds= num_odds+ 1print(num1, num2, num3)print("ODD NUMBERS:", num_odds)main()40 71 41ODD NUMBERS: 2CompSci 101 -Principles of Programming10Give the outputdefmain():number = 25if number > 30:print("A")if number >= 25: print("B")number = 31if number % 6 < 2:print("C")if number // 3 != 8:print("D")main()CompSci 101 -Principles of Programming11123456789101112Complete the functionComplete the get_price() function which returns the cost of tickets. If the total number of tickets is 14 or more, a 10% discount applies.defget_price(child, adult):child_price= 10adult_price= 25discount_size= 14discount_rate= 0.9 cost= (child* child_price+ adult* adult_price) returncostdefmain():num_child= int(input("Enterthe numberof children: "))num_adult= int(input("Enterthe numberof adults: "))cost= get_price(num_child, num_adult)print("The costof yourticketsis: $" + str(cost))main()Enter the number of children: 10Enter the number of adults: 5The cost of your tickets is: $202.5CompSci 101 -Principles of Programming12Complete the function

Complete the functionMany countries have 50 years as their standard length of copyrights and when a work's copyright term ends, the work passes into the public domain. Complete the function below which which prints "Out of copyright" if the author has been dead 50 years or more.defcopyright_check( ):defmain():current_year= 2019author_death_year= input("Enteryearof author'sdeath: ")author_death_year= int(author_death_year)copyright_check(current_year, author_death_year)main()Enter year of author's death: 1960Out of copyrightCompSci 101 -Principles of Programming13Complete the functionComplete the print_message() function which has an equal chance of printing "now", "soon" and "never". Example output from the completed program is shown lower down:import randomdefprint_message():defmain():print("Life willimprove")print_message()main()Life will improvesoonCompSci101 -Principles of Programming14Life will improvenowBoolean expressions -logical operatorsAs well as the relational operators, we can use the following logical operators in Boolean expressions:The three truth tables for these logical operators are shown below:andnotorCompSci 101 -Principles of Programming15Logical operators -examplesAssume that the variable, value, has been initialised.value> 10 and value< 100Isvaluegreaterthan10andlessthan10010 < value< 100value>= 10 or value== 5Isvaluegreaterthanorequalto10oristhevalueequalto5not value> 8Isvaluenotgreaterthan8not (value> 8 or value== 1)value<= 8 and value!= 1Isvaluenotgreaterthan8andnotequalto1ororCompSci 101 -Principles of Programming16

Give the outputdefmain():a = 42b = 17c = 94 if a > b and a > c:print("You")if not (a > b and a > c):print("cannot")if a > b or a > c:print("tuna")if not(a > b or a > c):print("fish")main()CompSci 101 -Principles of Programming17Below is the priority order of operations:Operator precedenceUnary operators+, -Multiplicative arithmeticcomparisonsAdditive arithmetic*, /, %+, -<, >, <=, >=, !=, ==Logical notLogical orLogical andnotandorAssignment=, +=HIGHLOW(Done first)(Done last)CompSci 101 -Principles of Programming18Give the outputdefmain():a = 42b = 17c = 94 if a > b and a > c:print("You")if not a > b and a > c:print("can")if a < b or a > c and b < 45:print("tuna")if not(a > b and a > c):print("piano")main()CompSci 101 -Principles of Programming19Use parentheses in boolean expressionsUse parentheses to groupsections of your boolean expressions to make the program more readable, e.g., is more readable than: but do not overload your boolean expressions with unnecessary parentheses, e.g., a > b or (a > c and b < 45)((a > b) or ((a > c) and (b < 45)))a > b or a > c and b < 45overuseofunnecessaryparenthesesnotasclearCompSci 101 -Principles of Programming20

Logical operators -exercisesAssume that the variable, value, has been initialised. Write the following four booleanexpressions:CompSci 101 -Principles of Programming21a)isthevaluelessthan100orgreaterthan200b)isthevaluenotequaltoeither100or10c)isthevaluegreaterthan5butnotequalto10d)isthevaluebetween5and20orequalto50If statements -a common mistakeRemember that the equality operator is ==. What is the problem with the code below?CompSci 101 -Principles of Programming22Note: single = symbol is the assignment operator.defmain():val1 = 50val2 = 53if val1 = val2 -3:print("Unbelievable")main()Comparing float numbersFloating point numbers are stored approximately. It is dangerous to test doubles for equality using ==.Test equality of floats by accepting all values within an acceptable error limit:val1 = 0.3val2 = 0.1 * 3if val1 == val2:print("Sigh!")if val1 != val2:print("maybe yes, maybe no!")maybe yes, maybe no!val1 = 0.3val2 = 0.1 * 3error_limit= 0.00001if abs(val1 -val2)< error_limit:print("Close enough!")Close enough!CompSci 101 -Principles of Programming23SummaryIn a Python program:•be familiar with the boolean values True and False•boolean expressions evaluate to either True or False•relational operators (>, <, <=, <= and ==) are used to compare values•logical operators (not, and, or) can be used to build more complex boolean expressions•an if statement is used when a block of code is to be executed only if a particular condition is TrueCompSci 101 -Principles of Programming24

Examples of Python features used in this lectureexam = exam_mark/ 100 * 60test = test_mark/ 100 * 60passed_theory= exam + test >= 50number = 32 if number % 6 < 2:number += 1val1 = 0.3val2 = 0.1 * 3error_limit= 0.00001if abs(val1 -val2) < error_limit:print("Close enough!")CompSci 101 -Principles of Programming25

quotesdbs_dbs17.pdfusesText_23