{ "cells": [ { "cell_type": "markdown", "metadata": {}, "source": [ "# Introduction to Python: Variables, Strings, and Numbers\n", "\n", "Let us try the famous \"hello world\"\n", "Note that we are using *\"**Python 3**\"*\n", "\n", "Created by John C.S. Lui, May 24, 2019. Modified on August 2, 2020.\n", "\n", "**Important note:** *If you want to use and modify this notebook file, please acknowledge the author.*" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "print (\"Hello world, this is great, my friend.\")\n", "print ('Hey dude, this is another way to express a string.')" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Let see how we can create and assign variables" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "message = \"Hello to the wonderful world of Python,\" # assign a string to the variable message\n", "\n", "print (message)\n" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "message2 = 'and welcome to CSCI2040.'\n", "print (message)\n", "print (message2)" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "print (message, message2) # try to print both messages in one line" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "# Naming rules\n", "1. Variables can only contain letters, numbers, and underscores. Variable names can start with a letter or an underscore, but can not start with a number.\n", "2. Spaces are not allowed in variable names, so we use underscores instead of spaces. For example, use student_name instead of \"student name\".\n", "3. You cannot use Python keywords as variable names.\n", "4. Variable names should be descriptive, without being too long. For example num_wheels is better than just \"wheels\", and number_of_wheels_on_a_motorycle.\n", "5. Be careful about using the lowercase letter l and the uppercase letter O in places where they could be confused with the numbers 1 and 0." ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Exercises \n", "* Create a variable, assign it with some value and print it out\n", "* Reassign the variable of some new value and print it out" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Let's learn something about \"strings\"" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "my_string1 = \"a string with a double quote\"\n", "my_string2 = 'a string with a single quote'\n", "print (\"STR1=\", my_string1)\n", "print ('STR2=', my_string2) # let's see the output" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "# what about a string which contains a quote?\n", "quote = 'Martin Luther King Jr. said, \"Free at last, free at last, thank God almighty we are free at last.\"'\n", "print (quote)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Changing cases for the string" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "first_name = 'john c.s.'\n", "\n", "print(first_name) # just print the string\n", "print(first_name.title()) # capitalize the first letter in each word\n", "print(first_name.upper()) # capitalize the whole string\n", "print(first_name)" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "last_name = \"Lui\"\n", "\n", "print(last_name.lower()) # Let's be-little John" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "String, turns out, is a data type with **MANY** built-in functions.\n", "Demonstrate in class how to look up from Python standard library, e.g., :\n", "\n", "**The Python 3 Standard Library -> 4.7. Text Sequence Type — str**\n", "\n", "Then search for, let say, 'upper'." ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## How can we combine strings? Use cancatenation." ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "print (\"John's first name is =\", first_name)\n", "print (\"John's last name is =\", last_name)\n", "\n", "full_name = first_name + last_name\n", "print (\"John's name is = \", full_name)" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "full_name1 = first_name.title() + \" \" + last_name # capaitalize the first letter, add space\n", "print (\"John's full name is = \", full_name1)" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "my_message = full_name1 + ', ' + \"is a real jerk !!!!!\"\n", "print (my_message)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Adding control characters into strings\n", "\n", "For example, how can we add *tab* or *line feed* into our strings?" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "print(\"John is\", \"a jerk\") # automatically add one space\n", "print(\"John is\\t\", \"a jerk\") # adding a tab\n", "print(\"John is\\t\\t\\t\", \"a jerk!!!!\") # adding 3 tabs\n", "print('But Mr. John C.S. Lui is even a bigger jerk !!!!!')" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "print(\"John is \\n\", \"a jerk.\") # a new line\n", "print(\"\\nJohn is\\n\", \"\\t\\treally a jerk.\") # a new line and some tabs\n", "print('So my advice is: \\t\\t\\t Immediately drop the course CSCI2040 !!!!')" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Stripping white spaces\n", "\n", "When people input something, they may inadvertently add more \"white spaces\" than they intended to. What should we do?" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "name = \" CUHK \" # a string with white spaces, before and after\n", "print(\"stripping left of the string, name=\"+ name.lstrip()+\", you see!!!\") # stripping left\n", "print(\"stripping right of the string, name=\"+ name.rstrip()+\", you see!!\") # stripping right\n", "print(\"stripping both sides of the string, name=\"+ name.strip()+\", you see!!\") # stripping both sides" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "# a better to visualize the above functions\n", "name = \" CUHK \" # a string with white spaces, before and after\n", "print(\"stripping left of the string, name=\" + \" ***\" + name.lstrip() + \"***\") # stripping left\n", "print(\"stripping right of the string, name=\" + \" ***\" + name.rstrip() + \"***\") # stripping right\n", "print(\"stripping both sides of the string, name=\" + \" ***\" + name.strip() + \"***\") # stripping both sides" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## check if each word in a string begins with a capital letter\n", "\n", "The `istitle()` function checks if each word is capitalized." ] }, { "cell_type": "code", "execution_count": 1, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "True\n", "False\n", "False\n" ] } ], "source": [ "print('The Hilton Hotel'.istitle() ) #=> True\n", "print('This dog is cute'.istitle() ) #=> False\n", "print('Sticky rice Is yummy'.istitle() ) #=> False" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## check if a string contains a specific substring\n", "\n", "The `in` operator will return `True` if a string contains a substring." ] }, { "cell_type": "code", "execution_count": 2, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "True\n", "True\n", "False\n" ] } ], "source": [ "print( 'man' in 'The worlds fastest man' ) #=> True\n", "print( 'fast' in 'The worlds fastest man' ) #=> True\n", "print( 'car' in 'The worlds fastest man' ) #=> False" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Find the index of the first occurrence of a substring in a string\n", "\n", "There are two different functions that will return the starting index, `find()` and `index()`. They have slightly different behaviour. In particular, `find()` returns -1 if the substring is not found. On the other hand, `index()` will throw a `ValueError`." ] }, { "cell_type": "code", "execution_count": 5, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "11\n", "-1\n" ] } ], "source": [ "# for find()\n", "print('The worlds fastest man'.find('man')) #=> 19\n", "print('The worlds fastest man'.find('car')) #=> -1" ] }, { "cell_type": "code", "execution_count": 8, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "19\n" ] } ], "source": [ "# index()\n", "print('The worlds fastest man'.index('man')) #=> 19\n", "\n", "#'The worlds fastest man'.index('car') #=> ValueError: substring not found" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Count the total number of characters in a string\n", "\n", "`len()` will return the length of a string." ] }, { "cell_type": "code", "execution_count": 10, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "50" ] }, "execution_count": 10, "metadata": {}, "output_type": "execute_result" } ], "source": [ "len('The first president of the organization, let\"s go.')" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Count the number of a specific character in a string\n", "\n", "`count()` will return the number of occurrences of a specific character." ] }, { "cell_type": "code", "execution_count": 11, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "3" ] }, "execution_count": 11, "metadata": {}, "output_type": "execute_result" } ], "source": [ "'The first president of the organization.'.count('o') #=> 3" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## f-string and how do you use it\n", "\n", "New in python 3.6, `f-strings` make string interpolation really easy. Using f-strings is similar to using format().\n", "F-strings are denoted by an `f` before the opening quote." ] }, { "cell_type": "code", "execution_count": 12, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "'Hello. My name is H. Weinstein and I love to eat tofu.'" ] }, "execution_count": 12, "metadata": {}, "output_type": "execute_result" } ], "source": [ "# use of f-string\n", "\n", "name = 'H. Weinstein'\n", "food = 'tofu'\n", "\n", "f'Hello. My name is {name} and I love to eat {food}.'" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Check if a string contains only numbers\n", "\n", "`isnumeric()` returns `True` if **all** characters are numeric." ] }, { "cell_type": "code", "execution_count": 13, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "True\n", "False\n" ] } ], "source": [ "print('777'.isnumeric()) \n", "\n", "print('2.0'.isnumeric()) # note that puntunation is NOT numeric" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Check if a string is composed of all lower case characters\n", "`islower()` returns `True` only if **all** characters in a string are lowercase." ] }, { "cell_type": "code", "execution_count": 14, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "True\n", "False\n" ] } ], "source": [ "print('all lower case'.islower())\n", "\n", "print('not aLL lowercase'.islower())" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Check if the first character in a string is lowercase\n", "This can be done by calling the previously mentioned function on the first index of the string." ] }, { "cell_type": "code", "execution_count": 16, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "False" ] }, "execution_count": 16, "metadata": {}, "output_type": "execute_result" } ], "source": [ "'aPPLE'[1].islower() " ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Reverse a string \n", "We can split a string into a list of characters, reverse the list, then rejoin into a single string." ] }, { "cell_type": "code", "execution_count": 23, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "dabclabcrabcoabcwabc abcoabclabclabceabch\n" ] } ], "source": [ "a='abc'.join(reversed(\"hello world\"))\n", "print(a)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Join a list of strings into a single string, delimited by hyphens (or other charcter)\n", "`join()` function can join characters in a list with a given character inserted between every element." ] }, { "cell_type": "code", "execution_count": 24, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "'abc-def-g'" ] }, "execution_count": 24, "metadata": {}, "output_type": "execute_result" } ], "source": [ "'-'.join(['abc','def','g'])" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Check if all characters in a string conform to ASCII\n", "The `isascii()` function returns True if all characters in a string are included in ASCII." ] }, { "cell_type": "code", "execution_count": 25, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "False\n", "True\n" ] } ], "source": [ "print( 'Â'.isascii() ) \n", "print( 'A'.isascii() )" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Uppercase or lowercase an entire string\n", "`upper()` and `lower()` return strings in all upper and lower cases." ] }, { "cell_type": "code", "execution_count": 26, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "HOW DO YOU FEEL ABOUT JULY 1, 2020?\n", "how do you feel about july 1, 2020?\n" ] } ], "source": [ "sentence = 'How do you feel about July 1, 2020?'\n", "print(sentence.upper()) \n", "print(sentence.lower())" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Uppercase first and last character of a string\n", "We want to target specific indices of the string. Since strings aren’t mutable in Python so we’ll build an entirely new string." ] }, { "cell_type": "code", "execution_count": 29, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "'This is my testing strinG'" ] }, "execution_count": 29, "metadata": {}, "output_type": "execute_result" } ], "source": [ "animal = 'This is my testing string'\n", "animal[0].upper() + animal[1:-1] + animal[-1].upper()" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Split line on line breaks\n", "`splitlines()` splits a string on line breaks.\n" ] }, { "cell_type": "code", "execution_count": 30, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "['I told my wife I was named after Albert Einstein',\n", " '\"But your name is John\", she said.',\n", " '\"Yeah, I know - as I said, I was named *after* Albert Einstein\"']" ] }, "execution_count": 30, "metadata": {}, "output_type": "execute_result" } ], "source": [ "sentence = 'I told my wife I was named after Albert Einstein\\n\"But your name is John\", she said.\\n\"Yeah, I know - as I said, I was named *after* Albert Einstein\"'\n", "\n", "\n", "sentence.splitlines()\n", "\n", "# this function is useful to read a file and split every lines of a file" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Convert an integer to a string\n", "Use the string constructor, `str()`." ] }, { "cell_type": "code", "execution_count": 33, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "3.1415926\n", "3.1415926\n" ] } ], "source": [ "a=str(3.1415926)\n", "print(a)\n", "b=float(a)\n", "print(b)\n" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Check if all characters in a string are alphanumeric\n", "Alphanumeric values include letters and integers." ] }, { "cell_type": "code", "execution_count": 34, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "True\n", "False\n" ] } ], "source": [ "print('Ten10'.isalnum()) \n", "\n", "print('Ten10.'.isalnum())" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Check if a string contains only characters of the alphabet\n", "`isalpha()` returns `True` if all characters are letters." ] }, { "cell_type": "code", "execution_count": 35, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "False\n", "False\n", "True\n" ] } ], "source": [ "print('One1'.isalpha())\n", "print('One123'.isalpha())\n", "print('One'.isalpha())" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Replace all instances of a substring in a string\n", "\n", "You can use the `replace()` function" ] }, { "cell_type": "code", "execution_count": 36, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "'Sasa sells mountain shells by the mountain shore.'" ] }, "execution_count": 36, "metadata": {}, "output_type": "execute_result" } ], "source": [ "sentence = 'Sasa sells sea shells by the sea shore.'\n", "sentence.replace('sea', 'mountain')" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "# arguments to methods\n", "\n", "- There are many built-in methods to strings, as well as other built-in data-types.\n", "- For each built-in method, it may take in some arguments\n", "- Let's look at the documentation for lstrip() and see what it can drop\n" ] }, { "cell_type": "code", "execution_count": 37, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "I love CUHK\n", "I hate HKU, it is the worst univeristy in HK.\n" ] } ], "source": [ "# Instead of using the default, demonstrate passing argument to the built-in method.\n", "\n", "name = 'CUHK'\n", "print (\"I love\", name)\n", "name_1 = name.lstrip('UC') # left strip the argument 'UC'\n", "\n", "name_2 = name_1 + \"U\"\n", "print ('I hate ' + name_2 + \", it is the worst univeristy in\", name_1 + '.')" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Search a specific part of a string for a substring\n", "\n", "`index()` can also be provided with optional start and end indices for searching within a larger string." ] }, { "cell_type": "code", "execution_count": 38, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "23\n", "0\n" ] } ], "source": [ "# we specify the beginning (10) and ending (44) in the search\n", "print('the happiest person in the whole wide world.'.index('the',10,44)) \n", "\n", "print('the happiest person in the whole wide world.'.index('the')) # without specifying beginning/ending" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Split a string on a specific character\n", "The `split()` function will split a string on a given character or characters." ] }, { "cell_type": "code", "execution_count": 39, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "['This', 'is', 'great']\n", "['not', 'so', 'great']\n", "['not', '', 'so', '', 'great']\n" ] } ], "source": [ "print('This is great'.split(' '))\n", "\n", "print('not--so--great'.split('--'))\n", "\n", "print('not--so--great'.split('-'))" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Check if a string begins with or ends with a specific character?\n", "`startswith()` and `endswith()` check if a string begins and ends with a specific substring." ] }, { "cell_type": "code", "execution_count": 40, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "True\n", "True\n", "False\n", "True\n" ] } ], "source": [ "city = 'Hong Kong'\n", "\n", "print(city.startswith('Hong'))\n", "print(city.startswith('Ho'))\n", "print(city.endswith('N'))\n", "print(city.endswith('g'))" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Check if all characters are whitespace characters\n", "`isspace()` only returns True if a string is **completely** made of whitespace." ] }, { "cell_type": "code", "execution_count": 41, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "False\n", "True\n", "True\n", "False\n" ] } ], "source": [ "print(''.isspace()) #=> False\n", "print(' '.isspace()) #=> True\n", "print(' '.isspace()) #=> True\n", "print(' the '.isspace()) #=> Falise" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Using the partition() function\n", "`partition()` splits a string on the first instance of a substring. A tuple of the split string is returned without the substring removed." ] }, { "cell_type": "code", "execution_count": 42, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "('Do you', ' like ', 'C. Lam ?')\n" ] } ], "source": [ "sentence = \"Do you like C. Lam ?\"\n", "print(sentence.partition(' like '))" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Using maketrans() and translate()\n", "`maketrans()` creates a mapping from characters to other characters. `translate()` then applies that mapping to translate a string." ] }, { "cell_type": "code", "execution_count": 43, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "'123 1re the first three letters, 4144y.'" ] }, "execution_count": 43, "metadata": {}, "output_type": "execute_result" } ], "source": [ "# create mapping\n", "mapping = str.maketrans(\"abcd\", \"1234\")\n", "\n", "# translate string\n", "\"abc are the first three letters, daddy.\".translate(mapping)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Remove vowels from a string\n", "One possibility is to iterate over the characters in a string via list comprehension (we will cover this lateer). If they don’t match a vowel then join them back into a string." ] }, { "cell_type": "code", "execution_count": 47, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "'Hll 1 Wrld 2'" ] }, "execution_count": 47, "metadata": {}, "output_type": "execute_result" } ], "source": [ "my_string = 'Hello 1 World 2'\n", "\n", "vowels = ('a','e','i','o','u') # define a tuple\n", "\n", "''.join([c for c in my_string if c not in vowels])\n" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Using rfind() to search for substring\n", "`rfind()` is like `find()` but it starts searching from the **right** of a string and return the first matching substring." ] }, { "cell_type": "code", "execution_count": 48, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "39" ] }, "execution_count": 48, "metadata": {}, "output_type": "execute_result" } ], "source": [ "story = 'The price is right said Bob. The price is right.'\n", "story.rfind('is')" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## How would you confirm that two strings have the same identity?\n", "The `is` operator returns `True` if two variables point to the same location in memory. This is what we’re referring to when we talk about identity.\n", "Don’t confuse `i`s with `==`, the latter which only tests equality." ] }, { "cell_type": "code", "execution_count": 49, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "True\n", "True\n", "True\n", "False\n" ] } ], "source": [ "animals = ['python','gopher']\n", "more_animals = animals\n", "\n", "print(animals == more_animals) #=> True\n", "print(animals is more_animals) #=> True\n", "\n", "even_more_animals = ['python','gopher']\n", "\n", "print(animals == even_more_animals) #=> True\n", "print(animals is even_more_animals) #=> False" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## To find the memory location of a variable\n", "The `id()` function returns the id of a memory address associated with a variable. Two objects with the same identity will return the same id." ] }, { "cell_type": "code", "execution_count": 65, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "1. memory location is: 140680946326512\n", "2. memory location is: 140680946326512\n", "3. memory location is: 140681107710640\n" ] } ], "source": [ "# The following example show two variables of the same string share the SAME MEMORY LOCAITON !!! This is\n", "# part of Python's optmization to save memory.\n", "\n", "name = 'object'\n", "print('1. memory location is:', id(name))\n", "\n", "name2 = 'object'\n", "print('2. memory location is:', id(name2))\n", "\n", "name2 = 'crazy John'\n", "print('3. memory location is:', id(name2))\n" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Exercise\n", "Create a similar output as:\n", "\n", "Oscar Wilde, an Irish poet, once said,
\n", " \"When I was young,
\n", "       I thought that money was the most important thing in life;
\n", "             now that I am old,
\n", "                   I know that it is.\"
" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Exercise\n", "* Store your first name in a variable, but include two different kinds of whitespace on each side of your name.\n", "* Print your name as it is stored.\n", "* Print your name with whitespace stripped from the left side, then from the right side, then from both sides." ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "# Numbers and numerics" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### Integers" ] }, { "cell_type": "code", "execution_count": 51, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "3\n", "1\n", "10\n", "2.0\n", "16\n" ] } ], "source": [ "print (1+2) # addition\n", "print (3-2) # subtraction\n", "print (5*2) # multiplication\n", "print (8/4) # division\n", "print (2**4) # exponentiation " ] }, { "cell_type": "code", "execution_count": 52, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "3.0\n", "1.0\n", "10.0\n", "2.0\n", "16.0\n" ] } ], "source": [ "print (1+2.) # addition\n", "print (3.-2) # subtraction\n", "print (5*2.) # multiplication\n", "print (8/4) # division\n", "print (2.0**4) # exponentiation " ] }, { "cell_type": "code", "execution_count": 53, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "14\n", "20\n" ] } ], "source": [ "# Use parenthesis to modify the standard order of operations.\n", "print (2+3*4)\n", "print ((2+3)*4)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### Floating points" ] }, { "cell_type": "code", "execution_count": 54, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "0.2\n", "0.30000000000000004\n" ] } ], "source": [ "print (0.1+0.1)\n", "print (0.1+0.2)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Division in Python 2.7 and Python 3.3\n", "\n", "- In Python 2.7; print 3/2 will give you 1\n", "- In Python 3.3, proint 3/2 will give you 1.5" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Some common operators: +, -, *, **, /, //, %\n", "\n", "Let's illustrate some common operators when they are applied to different data types" ] }, { "cell_type": "code", "execution_count": 55, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "8\n", "8.0\n", "AaaBbbbbbCCC\n" ] } ], "source": [ "print(3+5) # adding two integers\n", "print(3. + 5) # type conversion\n", "print('Aaa' + 'Bbbbbb' +'CCC') # cancatenation" ] }, { "cell_type": "code", "execution_count": 56, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "-5.2\n", "2\n", "6\n", "LuLu\n", "81\n", "81.0\n", "1.6666666666666667\n", "1.6666666666666667\n", "1\n", "1.0\n", "2\n", "2.0\n" ] } ], "source": [ "print(-5.2) # gives a negative number\n", "print(5-3)\n", "print(2*3)\n", "print('Lu'*2) # generate character strings \n", "print(3**4) # power\n", "print (3.0**4.)\n", "print(5/3)\n", "print(5/3.)\n", "print(4//3) # gives floor\n", "print(5.0//3.)\n", "print (17 % 3) # gives remainder\n", "print (17. % 3)" ] }, { "cell_type": "code", "execution_count": 59, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "stuff is of type: \n", "num1 is of type: \n", "num2 is of type: \n" ] } ], "source": [ "stuff = 'hello world'\n", "type(stuff) # see what type is this variable\n", "num1 = 12\n", "num2 = 12.\n", "print ('stuff is of type: ', type(stuff))\n", "print ('num1 is of type: ', type(num1))\n", "print ('num2 is of type: ', type(num2))" ] }, { "cell_type": "code", "execution_count": 60, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "['__add__',\n", " '__class__',\n", " '__contains__',\n", " '__delattr__',\n", " '__dir__',\n", " '__doc__',\n", " '__eq__',\n", " '__format__',\n", " '__ge__',\n", " '__getattribute__',\n", " '__getitem__',\n", " '__getnewargs__',\n", " '__gt__',\n", " '__hash__',\n", " '__init__',\n", " '__init_subclass__',\n", " '__iter__',\n", " '__le__',\n", " '__len__',\n", " '__lt__',\n", " '__mod__',\n", " '__mul__',\n", " '__ne__',\n", " '__new__',\n", " '__reduce__',\n", " '__reduce_ex__',\n", " '__repr__',\n", " '__rmod__',\n", " '__rmul__',\n", " '__setattr__',\n", " '__sizeof__',\n", " '__str__',\n", " '__subclasshook__',\n", " 'capitalize',\n", " 'casefold',\n", " 'center',\n", " 'count',\n", " 'encode',\n", " 'endswith',\n", " 'expandtabs',\n", " 'find',\n", " 'format',\n", " 'format_map',\n", " 'index',\n", " 'isalnum',\n", " 'isalpha',\n", " 'isascii',\n", " 'isdecimal',\n", " 'isdigit',\n", " 'isidentifier',\n", " 'islower',\n", " 'isnumeric',\n", " 'isprintable',\n", " 'isspace',\n", " 'istitle',\n", " 'isupper',\n", " 'join',\n", " 'ljust',\n", " 'lower',\n", " 'lstrip',\n", " 'maketrans',\n", " 'partition',\n", " 'replace',\n", " 'rfind',\n", " 'rindex',\n", " 'rjust',\n", " 'rpartition',\n", " 'rsplit',\n", " 'rstrip',\n", " 'split',\n", " 'splitlines',\n", " 'startswith',\n", " 'strip',\n", " 'swapcase',\n", " 'title',\n", " 'translate',\n", " 'upper',\n", " 'zfill']" ] }, "execution_count": 60, "metadata": {}, "output_type": "execute_result" } ], "source": [ "dir(stuff) # show all built-in functions of tyis type" ] }, { "cell_type": "code", "execution_count": 61, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Help on built-in function capitalize:\n", "\n", "capitalize() method of builtins.str instance\n", " Return a capitalized version of the string.\n", " \n", " More specifically, make the first character have upper case and the rest lower\n", " case.\n", "\n" ] } ], "source": [ "help(stuff.capitalize) # show the meaning of the capitalize function" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "# Comments\n", "\n", "\\# This line is a comment.
\n", "Note that # can also be put after a computational statement

\n", "\n", "## Good pratices for comments\n", "* It is short and to the point, but a complete thought.\n", "* It explains your thinking, so that when you return to the code later you will understand how you were approaching the problem.\n", "* It explains your thinking, so that others who work with your code will understand your overall approach.\n", "* It explains particularly difficult sections of code in detail." ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "# The Zen of Python, by Tim Peters\n", "\n", "\n", "Beautiful is better than ugly.
\n", "Explicit is better than implicit.
\n", "Simple is better than complex.
\n", "Complex is better than complicated.
\n", "Flat is better than nested.
\n", "Sparse is better than dense.
\n", "Readability counts.
\n", "Special cases aren't special enough to break the rules.
\n", "Although practicality beats purity.
\n", "Errors should never pass silently.
\n", "Unless explicitly silenced.
\n", "In the face of ambiguity, refuse the temptation to guess.
\n", "There should be one-- and preferably only one --obvious way to do it.
\n", "Although that way may not be obvious at first unless you're Dutch.
\n", "Now is better than never.
\n", "Although never is often better than *right* now.
\n", "If the implementation is hard to explain, it's a bad idea.
\n", "If the implementation is easy to explain, it may be a good idea.
\n", "Namespaces are one honking great idea -- let's do more of those!" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [] } ], "metadata": { "kernelspec": { "display_name": "Python 3", "language": "python", "name": "python3" }, "language_info": { "codemirror_mode": { "name": "ipython", "version": 3 }, "file_extension": ".py", "mimetype": "text/x-python", "name": "python", "nbconvert_exporter": "python", "pygments_lexer": "ipython3", "version": "3.8.3" } }, "nbformat": 4, "nbformat_minor": 2 }