Python Lab 1: Math, Data Types, Variables

Python Lab 1: Math, Data Types, Variables

The classic “Hello World” in Python.

You can use both the Python console or create a file on your machine and then use the python filename.py command to run the file and see the output.

print("Hello World!")

Numbers and Math

There are two main types of numbers in Python. They are Integers and Floating-point numbers.

Integers, commonly referred to as simply Ints are whole numbers, can be positive or negative, but without decimals and can have an unlimited length. Example are simple whole numbers, like 1, 54, -145, 8892 etc.

Floating-points numbers, commonly referred to as Floats are real numbers, that can be positive or negative and have decimal values. Examples are 1.2, 35.322, 3.141519, -9.3 etc.

Math Operations

You can use a range of built-in operators to do all sorts of mathematical operations on numbers. Below are the list of all the common Math operators.

SymbolOperation
+Addition
-Subtraction
*Multiplication
/Division (result is always a float)
**Exponentiation
%Modulo (remainder operator)
//Integer Division (result is always in int and not a float)

When performing complex math, i.e. doing several operations together, don’t forget the PEMDAS rule. Hence to avoid problems, always group operations using parenthesis. Example below is that of code directly executed in the Python console.

>>> 2 + 2
4
>>> 2.234 * 334
746.156
>>> 10 / 5
2.0
>>> 23 // 6
3
>>> 50 % 2
0
>>> 1122 - 334
788
>>> 3 ** 4
81
>>> 3 + 4 - 10 / 2 * 4
-13.0
>>> ((3 + 4) - (10 / 2)) * 4
8.0
>>>

Comments

Comments are just a way for us to write little notes inside our code that won’t actually run. Comments help yourself and other developers/team members understand whats happening in your code. Comments are written simply by adding a pound/hash symbol – #, before anything that you want to comment.

Adding the # symbol to a line, will make Python, ignore that line. If you want to comment out multiple lines, add # to the start of all those line.

# This is a comment
# Never forget the PEMDAS rule 

print((2 + 4) * 3.2 + (10 / 2.5))

# Division always returns floats, even when dividing ints

print(1/3) # comment here ----> 0.3333333333333333

Variables

Variables are like containers. They store some data which can be pulled out later. They can hold different types of data like numbers, booleans, and strings and others.

Variables are always assigned with the variable name on the left and the value on the right of the equal sign. Variables must be assigned before they can be used.

x = 50
current_year = 2020
average_salary_of_a_python_developer = 50000

pi = 3.14159
radius = 10
# you can do complex math and even assign them to other variables
circumference = 2 * pi * radius 

Variables can be:

  • Assigned to other variables
  • Reassigned at any time
  • Assigned at the same time as other variables
new_score = 4520
highest_score = new_score
new_score = 5000
x, y, z = 20, 40, 100 # Not recommended. It can get confusing to read. Hence avoid it.

Variable Naming Restrictions

  • Variables must start with a letter or underscore. So _users is ok, but 10users is not.
  • The rest of the name must consist of letters, numbers, or underscores. Ex. subscribers10, subscribers@paid
  • Names are case-sensitive. USERS, Users and users are all different.
  • Based on Python’s community convention, most variables should be snake_case
  • Should be all lowercased with few exceptions, like constant variables use CAPITAL_SNAKE_CASE and class names use PascalCase. You will learn about them later.
  • Variables that start and end with two underscores (“dunder”) are supposed to be private or left alone. Ex. __init__

Data Types

In any assignment, the assigned value must always be a valid data type.

Data TypeDescription
boolTrue or False values
intan integer, ex. 1, 3, 55, 1000
str(string) a sequence of Unicode characters, ex. "RST Forum" or "こんにちは世界"
listan ordered sequence of values of other data types, ex. [1,2,3] or ["x", "y"]
dicta collection of key:value pairs {"firstName": "John", "last_name": "Doe"}
There are more, which you will learn in later lectures

Dynamic Typing

Python allows reassigning variables to different types:

Other languages, like C++, Rust etc. are statically-typed and variables are stuck with their originally-assigned type:

logged_in_user = True
print(logged_in_user) # True

logged_in_user = "John Doe"
print(logged_in_user) # John Doe

logged_in_user = None
print(logged_in_user) # None

logged_in_user = 10 / 5
print(logged_in_user) # 2.0

None

None represents the idea of nothingness. It’s similar to null from some other languages.

twitter_handle = None
type(twitter_handle) # <class 'NoneType'>

Strings

String Declaration

String literals can be declared with either single or double quotes

full_name = 'jane doe'
position = "machine learning engineer"

You can have quotes inside your strings, but make sure they are different

linus_torvalds = 'Linus at FOSSConf, "Talk is cheap. Show me the code."'
alan_turing = "'Machines' take me by surprise with great frequency"

String Escape Sequences

Python supports a range of “escape characters”, which get interpreted by Python to do something special.

Below are some of the most commonly used escape sequences. You can see the full in the official Python documentation here – https://docs.python.org/3/reference/lexical_analysis.html#string-and-bytes-literals

SequenceMeaning
\nEnter / Return
\tHorizontal Tab
\vVertical Tab
\\Backslash
\'Single quote
\"Double quote

String Concatenation

Concatenation is combining multiple strings together. We do this using the "+" operator.

message = "Welcome to RST Forum"
user = "Guido"
greeting = message + ", " + user    # 'Welcome to RST Forum, Guido'

You can also use the "+=" operator to do in-place assignments. (in-place operators)

name = "Guido"
name += "van Rossum"
print(name) # 'Guido van Rossum'

Formatting Strings

There are several ways to format strings in Python to interpolate variables.
The new and the recommended way is using, F-Strings (Python 3.6+)

items_in_cart = 8
message = f"You have {items_in_cart} items in your shopping cart."

print(message) # You have 8 items in your shopping cart.

net_amount = 100
GST_rate = 12
GST_amount = (GST_rate / 100) * net_amount
msg = f"Your total is only ₹{net_amount + GST_amount}"

Older way of formatting strings using the .format() method

items_in_cart = 8
msg = "You have {} items in your shopping cart.".format(items_in_cart)

String Indexes

Every individual character in a string can be accessed using numeric values, basically accessing the string’s indexes.
String indexing is zero-based.

"hello"
"hello"[0]  # 'h'

name = "RST Forum"
name[4] # 'F'
name[6] # 'r'

Converting Data Types

In string interpolation, data types are implicitly converted into string form.

You can also explicitly convert variables by using the name of the builtin type as a function. For ex. int(), str() etc.

decimal = 3.141592653589793238
integer = int(decimal)  # 3

python_list = [1, 2, 3]
python_list_as_strings = str(python_list)   # '[1, 2, 3]'

# Don't worry about functions, lists, etc. You will learn about them in great detail in future lectures.