Python Programming Lesson 1 PDF
Document Details
Uploaded by ChasteJustice384
2024
Tags
Summary
This document is a Jupyter Notebook lesson plan for introductory Python programming. It covers variables, types, and basic operations. It includes examples and exercises for practicing concepts.
Full Transcript
variables_strings_print_long_version_solutions July 26, 2024 1 Lesson 1 in Python Programming. Aim of this notebook: Practice Jupyter notebooks and learn on the following topics in Python coding: > variables, type and help. 1.1 Va...
variables_strings_print_long_version_solutions July 26, 2024 1 Lesson 1 in Python Programming. Aim of this notebook: Practice Jupyter notebooks and learn on the following topics in Python coding: > variables, type and help. 1.1 Variables Variable is a named place in the memory where a programmer can store data and later retrieve the data using the variable “name”. : a = 10 It doesn’t look as if anything has happened, but when you did Shift-Enter in the cell above, the Jupyter Notebook sent the code off to be executed by Python. The code cell above takes the number 10, and puts it into a variable called a. Now, when we use the variable a, it will carry the value 10. We say that the variable a has the value 10. We often want to see the values of variables, and the Notebook makes it easy to do that. Here we display the value of the variable a: : a : 10 : # change the content of a variable. a = 12 a : 12 Our code cells can have lines that do some work, followed by a variable on its own, so we can see its value. Like this: : b = 5 b : 5 1 Warning: There are reserved words that cannot be used as variables or function names because there are already used by python to process things. The list of reserved words in python may be found here. Idea: It is better to use my_var (or my_funct) to define a variable (or a function) than var (or funct) alone, because var/funct may be used by Python or one of its library. Idea: It is good to choose a variable’s name that means something related to the aim of the variable. : guyguyg = 35 ukgvuv = 12.5 fytfyt = guyguyg * ukgvuv print(fytfyt) 437.5 : a = 35 b = 12.5 c = a * b print(c) 437.5 : # Now, with the right variables names, we understand what we are doing. hours = 35 rate = 12.5 pay = hours * rate print(pay) 437.5 For python all of the three cells above do exactly the same. However, for us, the last one is much easier to understand. Take home message: choose the name of your variables and function as explicit as you can even if the name looks long. : x = 2 # Assignement statement x = x + 2 # Assignement with expression print(x) # print statement 4 Exercises: How many seconds does it have in a non-leap year and in a leap year? (hint: construct 4 variables with the right names) : nb_of_days = 365 nb_of_hours = 24 nb_of_second = 60 total_nb_of_second = nb_of_days*nb_of_hours*nb_of_second print('The number of days in a non-leap year is:') print(total_nb_of_second) 2 nb_of_days = nb_of_days + 1 total_nb_of_second = nb_of_days*nb_of_hours*nb_of_second print('The number of days in a leap year is:') print(total_nb_of_second) The number of days in a non-leap year is: 525600 The number of days in a leap year is: 527040 Exercise: Guess the value of ‘a’ in the code: a = 2 a = a**2+a+2 print(a-2) Exercise: Guess the value of ‘a’ in the code below: a, b, c = 1, 2, 3 a, b, c = b, c, a a, b, c = c, a, b 1.2 The Notebook as a calculator To get output from the cell, we don’t actually need to have a variable on its own. We can put any expression on the last line. An expression is anything that returns a value. So b on its own returns a value, which is the value of b - in this case 5. But we can also do something like this: : (10 + 5 + 1) / 4 : 4.0 Notice, we didn’t use any variables. (10 + 5 + 1) / 4 is an expression - some code that returns a value. This means that we can use the Notebook as a simple calculator. You’ve already seen + and / and the parentheses. You also have * for multiply, and - for subtract, and ** for to-the-power-of. For example, here’s 104 : : 10 ** 4 : 10000 Order of evaluation: : # What is the result? 1 + 2**3/4*5 : 11.0 3 Exercice: Compute 6(23 )/4 (it should equal 12): : 6*(2**3)/4 : 12.0 Exercice: Compute 10242 /216 (it should be 16) : 1024**2/2**16 : 16.0 We can also use variables in our calculations. For example, we might be interested in the result of 2𝑥2 + 3𝑥 + 10. We want to calculate what answer we get for 𝑥 = 2. : # Set the variable x to 2 x = 2 #Compute the expression 2 * x ** 2 + 3 * x + 10 : 24 Now we can simply get the answer for 𝑥 = 7, or any other value of 𝑥: : x = 7 2 * x ** 2 + 3 * x + 10 : 129 Exercise: How much is 𝑥2 + 3𝑥 when 𝑥 = −11? 4 : x = -11 x**2+3*x : 88 To get the rest of an integer division (for instance to check if a number is even or odd) we use ‘%’ : 10 % 2 : 0 Exercise: Can you tell if 𝑥3 + 10𝑥2 + 𝑥 is even for 𝑥 = 13? : x = 13 y = x**3 + 10*x**2 + x y % 2 == 0 : True To get the quotient of an integer division, we use // : 10//3 : 3 1.2.1 Tab completion One of the very cool things about Jupyter notebooks is that they provide tab completion, similar to many IDEs. If you enter an expression in a cell, the Tab key will search the namespace for any vairable that match the characters you’ve typed: [ ]: the_answer_to_life_the_unverse_and_everything = 42 the_beatles = ['john', 'paul', 'george', 'ringo'] [ ]: # tab complete the_beatles ['john', 'paul', 'george', 'ringo'] 2 Comments in code cells begin with a hash (#) Idea: There are two ways to add comments in a notebook: 1. in a markdown cell 2. in a code cell using # If you want to add a ‘quick’ comment you can do it in a code cell but if you want to provide a longer explanation, it is better to use a markdown cell. : # This is a comment. It doesn't do anything. # This is another comment. It is just for your reading pleasure. 5 # The line below sets the variable c to have value 10. c = 10 # The last line is an expression, and so we see an output of this expression # after the cell. c : 10 3 Print Idea: If you want to force the display of the value of a variable, use the print function. : a = 1 a b=2 b : 2 : a = 1 print(a) b=2 b 1 : 2 Print(f’….’) is used to interpret variables in print : a = 5 print('the value of a is {a}') # variable a is just a string print(f'the value of a is {a}') # variable a is recognized as a variable with a␣ ↪value the value of a is {a} the value of a is 5 : #Use the print(f'.....') to interpret variables in a print name = 'Matthew' age = 23 print(f'Your name is {name} and your age is {age}') name, age = 'marc', 20 print(f'Your name is {name} and your age is {age}') Your name is Matthew and your age is 23 Your name is marc and your age is 20 6 Exercise: Print a sentence that gives the value of 𝑥2 + 𝑥 + 1 when 𝑥 = 1 : x = 1 y = x**2 + x + 1 print(f'The value of x**2+x*1 is {y} when x is {1}') The value of x**2+x*1 is 3 when x is 1 3.0.1 Numbers types Integers and floats work as you’d expect from other programming languages. Let’s create two variables: : some_integer = 73 some_float = 3.14159 We can print out these variables and their types as follows: : print(type(some_integer)) print(type(some_float)) What if you want to print some text and then some numbers? One way to do this is to cast the number as a string and then print it: : print('My integer was ' + str(some_integer)) #str() changes a variable into a␣ ↪string variable print('My float was ' + str(some_float)) My integer was 73 My float was 3.14159 However I often find it more convenient to use the print statement with comma separated values: : print('My integer was', some_integer) print('My float was', some_float) My integer was 73 My float was 3.14159 A natural thing to want to do with numbers is perform arithmetic. We’ve seen the + operator for addition, and the * operator for multiplication (of a sort). Python also has us covered for the rest of the basic binary operations we might be interested in: 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 7 Operator Name Description a // b Floor division Quotient of a and b, 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 : print('Sum:', some_integer + some_float) print('Multiplication:', some_integer * some_float) print('Division:', some_integer / some_float) print('Power:', 10 ** some_integer) Sum: 76.14159 Multiplication: 229.33606999999998 Division: 23.236641318567987 Power: 10000000000000000000000000000000000000000000000000000000000000000000000000 Warning! A common bug that can creep into your code is a lack of care between integer division and floor division. For example, integer division not resulting in a whole number will yield a float : 3 / 2 : 1.5 while the floor division operator drops the fractional part : 3 // 2 : 1 3.0.2 Booleans Python implements all of the usual operators for Boolean logic, but uses English words rather than symbols like &&, ||, etc that are found in other languages: : t = True f = False print(type(t), type(f)) # logical AND print(t and f) # logical OR print(t or f) # logical NOT print(not t) # logical XOR print(t != f) 8 False True False True Exercise: Guess the value of the following expression: t = True f = False not((t or f) and f) != f : not((t or f) and f) != f : True 3.0.3 Strings Python has powerful and flexible string processing capabilities. You can write string literals using either single quote ' of double quotes ": [ ]: a = 'one way of writing a string' b = "another way" type(a) We can also get the number of elements in a string sequence as follows [ ]: hello = 'hello' len(hello) 5 We can also access each character in a string and print it’s value: [ ]: for letter in hello: print(letter) h e l l o Adding two strings together concatenates them and produces a new string [ ]: world = 'world' hello + ' ' + world 'hello world' 9 String objects also come with a range of built-in functions to convert them into various forms: [ ]: hello.capitalize() 'Hello' [ ]: hello.upper() 'HELLO' [ ]: # replace all instances of one substring with another s = 'hitchhiker' s.replace('hi', 'ma') 'matchmaker' Exercise: In the string ‘one plus one equals two!’, replace ‘one’ and ‘two’ so that you get the final sentence ’two plus two equals four. Try to make it in one line. : 'one plus one equals two!'.replace('two','four').replace('one', 'two') : 'two plus two equals four!' Exercise: Guess the type of the variable ‘a’ when 1. a = 1 2. a = ‘james’ 3. a = 1.1 4. a = ‘1’ Idea: The last example show that we must be careful with variables’ type. We can force a variable to be of a certain type. : a = '1' a = int(a) type(a) : int Idea: It is possible to retreive a sub-part of a string. We can look at strings as a sequence of caracters. : third_name = "Alphonse" third_name #python enumeration starts at 0! : 'A' : third_name[0:4] : 'Alph' Exercise: Try the following list of slicings and guess what they do: 1. third_name[-1] 2. third_name[3:] 3. third_name[:5] 2. third_name[::2] 3. third_name[::-1] 4. third_name[::-2] 5. third_name[1:5:2] 10 : print(third_name[-1]) #It provides the last element print(third_name[3:]) #It provides all the elements from the 3rd one up to the␣ ↪end print(third_name[:5]) #It provides all the elements up to the 5th one print(third_name[::2]) #It provides all the elements with a step 2 print(third_name[::-1]) #It provides all the elements with a step -1, e.g. this␣ ↪inverse the word print(third_name[::-2])#It provides all the elements with a step -2 print(third_name[1:5:2]) #It provides all the elements from index 1 to index 5␣ ↪with a step 2. e honse Alpho Apos esnohplA enhl lh It is possible to break the line with ‘slash n’ or add some tabulation with ‘slash t’ : string = 'This is a string!\n(But not a very interesting one)\n\n\tEnd.' print(string) This is a string! (But not a very interesting one) End. Check if they contain certain elements like lists: : string = 'Hello! Everyone.' '!' in string : True : '?' not in string : True We can also check if a substring is present in a string: : 'very' in string : True Splitting strings: Often we need to split sentences into words or file paths into components. For this task we can use the split() function. By default a string is split wherever a whitespace is (this could be normal 11 space, a tab \t or a newline \n). : string.split() : ['Hello!', 'Everyone.'] : 'path/to/file/image.jpg'.split('/') : ['path', 'to', 'file', 'image.jpg'] Stripping strings: Sometimes strings contain leading or trailing characters that we want to get rid of, such as whites- paces or unnecessary characters. We can remove them with the strip() function. Like the split() function it removes whitespaces by default but we can set any characters we want: : '_path/to/file/image.jpg_'.strip('_') : 'path/to/file/image.jpg' : '_-_path/to/file/image.jpg,_,'.strip(',_-') : 'path/to/file/image.jpg' Joining strings Sometimes we split strings into a list of words for processing (like stemming or stop word removal) and then want to join them back to a single string. To to this we can use the join() function: [ ]: ' '.join(['this', 'is', 'a', 'list', 'of', 'words']) 'this is a list of words' [ ]: '-'.join(['this', 'is', 'a', 'list', 'of', 'words']) 'this-is-a-list-of-words' Exercise 2: Write a function that performs the following on string_1 - split the string into words - then strip the special characters /, ‘(’ and ‘)’ from each word - join the words back together with single spaces (' ') - remove the word ’ End’ - make the whole string lower-case : string_1 = 'This is a string! /(But not a very interesting one)/ End.' print(string_1) This is a string! /(But not a very interesting one)/ End. : my_list = [] for ele in string_1.split(' '): my_list.append(ele.strip('/()')) print(my_list) 12 ' '.join(my_list).replace(' End', '').lower() ['This', 'is', 'a', 'string!', 'But', 'not', 'a', 'very', 'interesting', 'one', 'End.'] : 'this is a string! but not a very interesting one.' Exercise: Count the number of time the letter ‘a’ is in the string ‘aaaabbbbaaaa’ [ ]: my_str = 'aaaabbbbaaaa' my_str.count('a') 8 Exercise: We can also use the ‘+’ for concatenation of strings. Concatenate the two strings ‘aaaaa’ and ‘babab’ and count the number of ‘a’ in the result. [ ]: my_str_1, my_str_2 = 'aaaaa', 'babab' new_str = my_str_1 + my_str_2 new_str.count('a') 7 4 Input Python can read data from the user thanks to the input command. : name_var = input('What is your name') print(f'Welcome {name_var} to the BBA python course!') Welcome Guillaume to the BBA python course! Warning: By default the type of input given to python is a string. If we expect a number we first need to convert it into a number. : age_var = int(input('What is a your age?')) dob = 2025 - age_var print(f'You are {age_var} years old. You were born in {dob}.') You are 23 years old. You were born in 2002. Exercise: Write a program that prompt the user for the number of hours and rate to compute the gross pay. : hours = int(input('How many hours have you worked?')) rate = int(input('What is the rate per hour?')) pay = hours * rate print(f'You will get {pay} euros.') You will get 552 euros. 13