Module 1 · Python crash course · Lesson 5 of 66

Comparisons, logic and if

Ask True-or-False questions and act on the answer.

In this lesson · about 10 minutes

  • Compare values with ==, !=, <, >, <=, >=
  • Combine conditions with and, or
  • Branch with if, elif and else

Comparison operators give True or False: 1 < 2, 1 >= 1, 'hi' == 'bye'. Note the double == for "is equal to"; a single = stores a value.

and is True only when both sides are; or is True when at least one is.

if runs an indented block only when its condition is True. elif ("else if") checks another condition, and else catches everything left. Python uses indentation (4 spaces) to know which lines belong to the block.

Exercise

Free shipping

Orders of $50 or more ship free; otherwise shipping is $7. Set shipping to 0 or 7 using if and else. Try changing order_total to test both cases.

Check your understanding0 of 2 correct

Question 1

1.What is (1 == 2) or (2 == 3) or (4 == 4)?

Question 2

2.What's wrong with if x = 5:

Quiz score: 0 of 2

Exercises solved: 0 of 1

Tip: answer every quiz question correctly first.

Noviq Academy's Data Science course is free and for learning. Python runs in your browser with Pyodide, which downloads about 20 MB the first time, plus a few more for scikit-learn. Your code and progress stay on this device. The salaries data is a sample of San Francisco's public pay records; the purchases, customers, housing, advertising and classified data are made up. The Titanic, tips, flights and iris data sets come from Seaborn's examples; the maps use public 2011 to 2014 US and world figures. The 911 data is a 20,000-call sample of Montgomery County, Pennsylvania's public 911 records; the movie ratings are the MovieLens 100K data from GroupLens Research; the reviews are a 3,000-review sample from the Yelp Dataset Challenge; the loans are public LendingClub data; the colleges are the College data from An Introduction to Statistical Learning; the bank notes, kyphosis and breast cancer data come from the UCI Machine Learning Repository. Spark and TensorFlow can't run in a browser, so those lessons use stand-ins that run here, and show the code for the real tools.