Python is a programming language. Like other languages, it gives us a way to communicate ideas. In the case of a programming language, these ideas are "commands" that people use to communicate with a computer!
Google Colab is a great platform to experiment with your code and build your own Data Analysis projects in a simple way. Hence, we will use Google Colab as a playground to practice the concepts, as well as a platform to exercise.
We convey our commands to the computer by writing them in a text file using a programming language. These files are called programs. Running a program means telling a computer to read the text file, translate it to the set of operations that it understands, and perform those actions.
print("Hello and welcome to CoderSchool!")Comments help other people reading the code understand it faster, or let you ignore a line of code and see how a program will run without it. You can make a comment by putting # in front of the line, or using the shortcut Cmd/Ctrl + /.
# Check whether a number is Even or Odd
i = 10
if i % 2 == 0:
print("This is an EVEN number")
else:
print("This is an ODD number")
a = 2
a = a * 2
print(a)
# This is a comment in Python
# You can make it simply by putting # in front of the lineA variable is used to store a value that will be used by the program. In Python, we assign variables by using the equals sign (=).
message_string = "Hello CoderSchool"
print(message_string)
print(message_string)
print(message_string)It's no coincidence we call these creatures "variables". If the context of a program changes, we can update a variable but perform the same logical process on it.
# Greeting
message_string = "Hey!"
print(message_string)
# Farewell
message_string = "See you!"
print(message_string)Now, let's try to update the variable meal to reflect each meal of the day before we print it.
# We've defined the variable "meal" here to the name of the food we ate for breakfast!
meal = "Bánh mì"
print("Breakfast:", meal, "!!!")
# Now update "meal" to be lunch!
meal = "Cơm tấm"
print("Lunch:", meal)
# Now update "meal" to be dinner
meal = "Hủ tiếu"
print("Dinner:", meal)❓ Questions
print() be used for strings only?Mini exercise 🏃🏻♂️
3.14 to variable aa (note that the variable exists everywhere after assigning)"Hello" to variable b3 and 4 to variables c and dcat_fur and assign it with the value 'black'# Variable name is case sensitive
cat_fur = "black"
CAT_fur = "white"
print(cat_fur) # prints "black"
print(CAT_fur) # prints "white"
# Reassigning an existing variable (try to guess before running this cell)
a = 1
a = 2
a = 3
print(a) # 3a = True
type(a)
a = 1 > 100
print(a)
type(a)Compare a and b. Notice the order of operation.
a = 10
b = 11
c = a <= b
d = a > b
e = a == b
print(c, d, e)== compares 2 values; = assigns new value to variable.
print(a == b)
a = b
print(a)Boolean operators:
# Inverting boolean using "not"
a = True
print(not (a))
# AND vs. OR
a = True
b = False
print(a and b)
print(a or b)
# Order of evaluation
a = True
b = True
c = False
d = True
print(a and b and c and d)
print(a or b or c or d)Order of evaluation: NOT > AND > OR. Check Operator precedence for a full list.
a = True
b = True
c = False
# print(a or b and c) # NOT recommended
print((a or b) and c) # RECOMMENDED - use parentheses for claritytype(0) # Integer
type(3.14) # Float
type(1 + 2j) # Complex[Extra] Floating-point numbers can behave in some unexpected ways due to how computers store them. For more information, read Python's documentation on floating-point limitations.
What if we want to convert int to float and vice versa? Yes we can!
a = 3
print(a, type(a))
a = float(a) # type casting
print(a, type(a))
# Convert float to int
b = 5.01
print(b, type(b))
b = int(b)
print(b, type(b))
# Rounding floats to nearest integer
c = 0.6
c = round(c)
print(c, type(c))
d = 1.789
d = round(d, 2)
print(d, type(d))Computer programmers refer to blocks of text as strings. In Python a string is either surrounded by double quotes ("CoderSchool") or single quotes ('CoderSchool'). It doesn't matter which kind you use, just be consistent.
print("Hello World!")
print('Hello "old" World!')
print("Hello 'new' World!")
print("""He"ll"o 'W'orld""")Multi-line strings:
lyric = """Hello darkness my old friend
I've come to talk with you again
"""
type(lyric)Concatenate two strings:
text = "CODER" + "SCHOOL"
print(text)If you want to concatenate a string with a number you will need to convert the number to a string first, using the str() function.
birthday_string = "I am "
age = 25
birthday_string_2 = " years old today!"
# Concatenating an integer with strings - turn the integer into a string first
full_birthday_string = birthday_string + str(age) + birthday_string_2
print(full_birthday_string)
# Option 2: print can take multiple arguments
print(birthday_string, age, birthday_string_2)Mini Exercise 🏃🏻♂️
Fill in your name and concatenate all the strings below to make a complete sentence.
string1 = "My name is "
string2 = "" # FILL IN YOUR NAME HERE
string3 = "I am "
string4 = 37
string5 = " years old. "
string6 = "I learn DS at CoderSchool because "
string7 = "I love CS!"
# YOUR CODE HERE
message = ""
print(message)coffee_price = 1.50
number_of_coffees = 4
print(coffee_price * number_of_coffees)
# Updating the price
coffee_price = 2.00
print(coffee_price * number_of_coffees)⭐️ Trick: swap values of two variables in one line
a = 1
b = 2
a, b = b, a
print(a, b)
# Traditional way:
a = 1
b = 2
temp = a
a = b
b = temp
print(a, b)# First we have a variable that stores the total running distance
running_distance = 10
# Let's say we run another 2 km today
running_distance = running_distance + 2
print(running_distance)Plus Equals
Python offers a shorthand for updating variables. When you have a number saved in a variable and want to add to the current value, you can use the += (plus-equals) operator.
running_distance = 10
running_distance = running_distance + 2
# Or: running_distance += 2
print(running_distance)The plus-equals operator can also be used for string concatenation:
status = "Learning Python at CoderSchool is fun!"
# Add the hashtags!
status += " #weekend"
status += " #coding"
print(status)Mini Exercise 🏃🏻♂️
Similar shorthand operators: +=, -=, *=, /=. Example: A += B or A += C + D + E + F.
total_price = 0
new_shoes = 50.00
total_price += new_shoes
nice_shirt = 39.00
fun_book = 20.00
# Update total_price here
total_price += nice_shirt + fun_book
print("The total price is", total_price)Computers absolutely excel at performing calculations. Python performs addition, subtraction, multiplication, and division with +, -, *, and /. If you want more, here it is:
| Operator | Name | Description |
|---|---|---|
a + b | Addition | Sum of a and b |
a - b | Subtraction | Difference of a and b |
a * b | Multiplication | Product of a and b |
a / b | True division | Quotient of a and b |
a // b | Floor division | Quotient, removing fractional parts |
a % b | Modulus | Integer remainder after division of a by b |
a ** b | Exponentiation | a raised to the power of b |
-a | Negation | The negative of a |
# Prints "501"
print(573 - 73 + 1)
# Prints "50"
print(25 * 2)
# Prints "2.0"
print(10 / 5)When we perform division, the result has a decimal place. Python converts all integers to floats before performing division. Division by zero raises ZeroDivisionError.
# Assign the value 5 to the variable named score
score = 5
score += 1
print(score)
score -= 3
print(score)
score *= 8
print(score)
# Note the implicit type casting
score /= 4
print(score, type(score))
# Power (**)
print(2**3)
# Floor division (//)
print(15 // 2)
# Modulo (%)
print(15 % 2)
# Absolute value (abs())
print(abs(5 - 7))Example
Given an integer number: print False if that number is even, print True if it is odd.
x = 15
print(x % 2 != 0)Mini Exercise 🏃🏻♂️
Given 10 cards and you need to divide them among 4 players. Print the number of cards remaining.
no_cards = 10
no_players = 4
# YOUR CODE HERE
print("Cards remained: ")🔥 CHALLENGE
Given a three-digit number, find the sum of its digits.
Example input: 123 → Example output: 6
a = 1
b = "Hello world!"
print(a)
print(b)
number_of_students = 30
place = "my class"
# Option 1
print("There are", number_of_students, "students in", place)
# Option 2: f-string
print(f"There are {number_of_students} students in {place}")Use formatted strings to control the number of decimal places:
pi = 3.1415926535897
print(f"The result is {pi:.3f}")So far we've covered how to assign variables directly. Often we want the user to enter new information. While we output with print(), we get input with input(). The input() function takes a prompt message that is shown before the user types.
name = input("What's your name? ") # input() by default returns a string
print(name, type(name))
age = int(input("How old are you? ")) # Convert input string to integer
print(age, type(age))🔥 CHALLENGE
Write a program that takes three integer numbers separately and prints their sum in the format: "The sum of three numbers is ___"
# YOUR CODE HERE