Types, Expressions, and Variables in Python

From Sustainability Methods

Types, Expressions, and Variables in Python THIS ARTICLE IS STILL IN EDITING MODE

Introduction

Welcome to this tutorial on how to use Python! In this tutorial, we will explore and learn about some basics needed to get along in Python. This includes different data types, what you can do with them and how to store them. By the end of the tutorial, you will be able to: make comments in Python, know the different data types, use expressions, characters and strings, and select elements of strings.

Hello World

When learning a new programming language, normally we start with a simple “hello world” example. This one line of code will ensure that the environment is set up correctly, and we know how to print a string.

print(’hello, world!”)

After executing the line above, you should see the Python prints hello, world! Yay!

Note: the “print ()” above is a function, and you passed the argument ‘hello, world!’ inside the print function to tell Python what to print. You just learned new keywords: function ("print()", argument("hello, world"), and statement (the whole line).

Comments

Besides writing code, it is always recommended to put a comment on your line of code. Not only that it helps other people to understand your code better, but more importantly it acts as a reminder for you of what you have written! Trust me, even experienced programmers will forget their lines of code after a few weeks.

To write comments in Python, use the hashtag symbol # before writing your comment. When you run your code, Python will ignore everything past the # on that particular line.

#Practice writing a comment
print (’hello, Eren’) #this prints my name
#print (’asdf’)

Data Types

Data types are how Python understand the types of each data and therefore how to handle them. In many situations, it seems intuitive to humans which data type we are dealing with. However, it is not for Python. Because some commands only work with some data types, it is important to always know which data types are involved in your analysis to use Python.

Popular data types in Python are:

Type name Example Short explanation
int (integer) 123 simple numbers (including negative)
float 1.23 numbers between integers
boolean True/False Can only be True or False (capital T and F)
str (string) "hello" text
datetime 2022-04-12 14:05:59.420606 date and time

Type “casting” is where a variable can be forced to change to the type that we want. Of course, we want to be careful when doing that, because there could be some information loss in the process.

Example: if we want to know just the integer from a float.

int(1.6) 
##result will be 1

Expressions and Variables

Expressions are operations that Python performs.

Example: 1+2+3 → the operations here are addition. Popular math operators are: addition (+), subtraction (-), multiplication (*), division (/), and power (**)

Variables are used to store values.

Example:

my_number = 1

In the code above, we store the value 1 to the variable “my_number”. It is also possible to update the value of the variable by re-assigning it. Example: I failed a math test the first time and I got a perfect score after I retake the exam.

my_math_score = 30 #old value

my_math_score = 100 #new value

Now, we can combine both what we have learned from expression and variables into one.

Example: I have a height of 180 cm, and my brother’s height is 20 cm less than my height. How would this in code look like?

my_height = 180

brothers_height = my_height - 20


And to combine what we have learned about data types and variables, we can also check a type of a certain variable using the function type.

type(my_height)


As we can choose any name for a variable, it is recommended to have a meaningful name for a variable name. A good programmer can take up to two minutes to stop and think about a perfect variable name before programming a complex algorithm.

Strings

Texts, stored as string in Python, are not as simple as it seems. In Python (and others programming languages) it has unique properties that we can take advantage of.

To define string in Python, use quotation marks, or single quotation.

“Stephen”

‘Stephen’

A string can be a combination of spaces, digits, and most of symbols / special characters.

‘1 2 3 4 5 !’

We can print out string directly using print statement:

print(”Hello World!”)

We can bind or assign a string to a variable:

name = “Stephen Kurniawan”
print(name)


One unique property of a string is that it is a sequence of characters.

Imagine the word: “CAT”, it is made by 3 characters: C, A, and T.

Each character in a string can be called by using its “**index**”.

**Char** **C** **A** **T**
**index** **0** **1** **2**

The index of “C”, “A”, and “T” is 0,1,2 respectively. This is called "zero indexing" and important to consider whenever you want to analyze data in Python. This works not only for strings but all other data types.

There is a special way to get the character that we want using an index.

Example: I want to get the “A” from “CAT” using the index [].

pet = “CAT”
print(pet[1]) # use square brackets [ ] to specify index.

And if we want a sub-string or a set of characters from the string, we can use the slice operator “:”.

Example: I want to get the “AT” from “CAT”

pet = “CAT”
print( pet[1:3] )

Here again, you learn how Python counts. When using the slice operator, the lower bound (in this case 1) is included and the upper bound (in this case three) is not. In words this means: From the variable "pet", print all indexes from the index 1 (second element) to three (fourth element), excluding three.

Quiz

1. my_minutes = 200 my_hours = my_minutes / 60 what will be the result of my_hours? 2. Use the type function to check the type of the variable: my_minutes 3. What happens when you put “-1” when you index a string? Example:

pet[-1]

4. What happens when you add 2 strings together? Example:

pet_1 = “cat”
pet_2 = “dog”
pet_3 = pet_1 + pet_2

5. Kim has three apple trees. From each tree, they can harvest 20 apples. They plant a new tree every year but can only harvest apples one year after it has been planted. Kim has 5 housemates who each want two apples every year and three family members who want 3 apples a year. To pay her rent they need to sell 53 apples a year. Are the apple trees enough to pay the rent and give their friends the apples? If no, when is this the case?

The author of this entry is XX. Edited by Milan Maushart