Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...

Transcript

Variables, expressions and arithmetics Tobias Andersson Gidlund Foundations of Programming 1 Agenda ➤ About Programming ➤ Three fundamental concepts ➤ Sequence ➤ Style ➤ Errors...

Variables, expressions and arithmetics Tobias Andersson Gidlund Foundations of Programming 1 Agenda ➤ About Programming ➤ Three fundamental concepts ➤ Sequence ➤ Style ➤ Errors ➤ Variables ➤ Data types ➤ Reading input ➤ Arithmetic Expressions ➤ Type conversion Foundations of Programming 2 Fundamental Concepts Foundations of Programming 4 Three Concepts ➤ Imperative programming (as we teach Python) consists of three fundamental concepts: ➤ Sequence ➤ Selection ➤ Iteration ➤ In addition to that, a way of storing data is also needed ➤ And some way of doing calculations (hence the name computer) ➤ With this, most programming tasks can be solved Foundations of Programming 5 More? ➤ Even though it is possible to only use the previously mentioned concepts, it is seldom easy to do it ➤ Most programming languages have additional concepts to make life a lot easier ➤ Python is such a language ➤ It can be fairly simple things to things that will transform the language itself ➤ Examples can be functions or data structures like lists and trees ➤ More extensive concept can be to add object-orientation to the language Foundations of Programming 6 Sequence ➤ This lecture will focus on the sequence concept ➤ Later will cover the other fundamental and several additional concepts ➤ In Python, and most other programming languages, code is executed in sequence ➤ One after another ➤ The exception is concurrent programming, but that is outside the scope of this course ➤ It is possible to “jump” between different parts of a program, but this is also done in sequence ➤ When calling functions, more on that later Foundations of Programming 7 Instructions ➤ The program executes instructions ➤ These can be statements or expressions ➤ Expressions are for example mathematical calculations ➤ Statements are instructions that actually performs some action ➤ Like print() ➤ These can, and will be, combined in many different ways to create a program ➤ The instructions are what is executed in sequence when running the program Foundations of Programming 8 Running in sequence ➤ Here is a program that is running in sequence, one printout after the other print('May the Force be with You!') print('Please listen to Pink Floyd') print('The meaning of life, the universe and everything is 42') May the Force be with You! Please listen to Pink Floyd The meaning of life, the universe and everything is 42 Foundations of Programming 9 The print() instruction ➤ In Python, print() is a powerful and important instruction ➤ It is a statement ➤ It is also a function ➤ Python has many built-in functions that are available from the start ➤ About 150 built-in functions ➤ They all have the same basic structure: ➤ A name starting with a lower letter ➤ Parenthesis in-between which data can be sent Foundations of Programming 10 Sending text ➤ In the example, a piece of text has been sent to the print statement ➤ This text is also called a string (more later) ➤ In Python, a string is enclosed in single or double quotation marks ➤ Prefer the single quote as it is easier to type and looks more “Python” ➤ This string is sent (in other words, given as input) to the print() function which in turns prints it out ➤ To what is set as standard for Jupyter ➤ It could also be used to “print” to a file Foundations of Programming 11 In Jupyter Foundations of Programming 12 Making calculations ➤ Calculations will be discussed later in the lecture ➤ The print() function, however, can be used to print out calculations print(32 + 10) print(2 * 6 + 4 - 1 * 4) print(10.5 + 2 * 3 / 45 - 3.5) print((10.5 + 2 * 3) / (45 - 3.5)) 42 12 7.133333333333333 0.39759036144578314 Foundations of Programming 13 Combining output ➤ Later, when discussing strings, different ways of printing will be shown in detail ➤ For now, it is important to know a few things on how to combine text and calculations ➤ Or text and text or text and variables (later) ➤ The output can be merged using , ➤ A space will be inserted between the text and the number when they are printed ➤ It is possible to do this merging anywhere and several times in an output Foundations of Programming 14 Example output print('A number', 42) print(2, 'is larger than', 1) print(2 + 5, '*', 5 - 2, '=', (2 + 5) * (5 - 2)) A number 42 2 is larger than 1 7 * 3 = 21 Foundations of Programming 15 Programming in style ➤ There are a lot of rules defining how to code, but there are also guidelines for what the code should look like ➤ These guidelines are not enforced by the programming language itself and are, in a sense, arbitrary ➤ One of these guidelines is to have space around number and operators: print(5 + 2 / 6) ➤ The program will work just as well without these spaces: print(5+2/6) Foundations of Programming 16 Python Coding Style Guidelines ➤ This has been an important part of the development of Python ➤ Code is read a lot more than it is written ➤ So much that it is part of the discussion of the Python Enhancement Proposal (PEP) ➤ A process for proposing new features but also documenting design decisions ➤ These documents handle everything from technical features to how to think in Python ➤ PEP 8 is called Style Guide for Python Code Foundations of Programming 17 Part of PEP 8 ➤ To fully understand PEP 8, a programmer needs to understand all of Python ➤ There are, however, a number of guidelines that you will be able to understand fairly quickly ➤ Indentation is made up of spaces, not tabs ➤ Indentation should be four spaces wide ➤ There should be space around literals and mathematical symbols ➤ Rules for how to name things in Python Foundations of Programming 18 Enforcing the Guidelines ➤ As there is nothing in the language that enforces the guidelines, they are not mandatory ➤ It is a strong recommendation to adhere to the guidelines as everyone expects that ➤ During the tutoring sessions and when correcting the assignments we will look at how well you follow the guidelines! ➤ Other development platforms than Jupyter will have support for the guidelines ➤ All guidelines can be seen at The PEP 8 webpage Foundations of Programming 19 Errors ➤ Yes, when programming, there will be errors… ➤ Loads of them ➤ Programming is very often a cycle of writing code → running/crashing → read error messages → write code ➤ Understanding errors and error messages is a vital part of being a programmer ➤ The quality of error messages is something that differentiate programming languages ➤ Rust is a language with very good messages, while C is considered to have worse messages Foundations of Programming 20 Python Errors ➤ Python is considered to have fairly good error messages ➤ Verbose enough and pointing to the correct place in code ➤ Notice that error messages are not given for all types of errors ➤ There are three categories of errors: ➤ Syntax ➤ Logic (with no error messages) ➤ Runtime Foundations of Programming 21 Syntax Errors ➤ When the rules of the language are not followed, Python will issue a syntax error print('Hello world' ➤ Executing the code in Jupyter will give the following error message: SyntaxError: incomplete input ➤ This class of errors are often fairly easy to understand ➤ It is also common that the development environment can help in detecting these kinds of errors even before the program is run Foundations of Programming 22 Showing Error in Jupyter ➤ Below is an image of what Jupyter shows when a syntax error occurs: ➤ Jupyter is not as well equipped as an editor to help you with all the errors as for example VS Code ➤ Read the book and search the internet for finding information that can help you solve the error Foundations of Programming 23 Runtime Error ➤ This kind of error occurs when the code is executing ➤ Can be the result of a user inputting the correct thing ➤ The important thing is that the syntax is correct which means that the error cannot be caught when compiling ➤ The classic example is dividing with zero print(42 / 0) ➤ Output ZeroDivisionError Traceback (most recent call last) Cell In, line 1 ----> 1 print(42 / 0) ZeroDivisionError: division by zero Foundations of Programming 24 Logic Errors 😇 ➤ The most difficult to find as it is because you have made errors in thinking ➤ The error is only noticed at runtime and when testing ➤ This is why it is so important to do testing ➤ One recommendation is to not try to solve a task all at once, but rather to have it divided into smaller parts ➤ Also, run often to check your running code Foundations of Programming 25 Storing data Foundations of Programming 27 The Need for Storing ➤ So far, we have only printed text and calculations to the terminal with Python ➤ A computer program also needs to be able to read and calculate ➤ We have also seen that it can do some calculation in the print ➤ To be able to do that, the program needs a way to store data ➤ This is done, just as in math, using variables ➤ Letters, or combinations of letters, representing something that can hold a value Foundations of Programming 28 Triangle ➤ The area of a triangle can be calculated using the following formula: b⋅h area = 2 ➤ Where area will hold the calculated area, b is the base of the triangle and h the height ➤ If b is 5 and h is 10, then area will be calculated to 25 ➤ If b is 34 and h is 55, then area will be calculated to 935 Foundations of Programming 29 In Python ➤ This can of course be done in Python as well: b = 5 h = 10 area = b * h / 2 print(area) b = 34 h = 55 area = b * h / 2 print(area) 25.0 935.0 Foundations of Programming 30 More on Variables ➤ b, h and area are all variables in Python in the previous program ➤ The variables are assigned values, that is, we put a value for them to store ➤ The symbol = is called an assignment operator in Python ➤ Equality is using the symbol == instead ➤ In this case, we are storing numbers in the variables ➤ print is used to output the value put in the variable area Foundations of Programming 31 What are Variables? ➤ In technical terms, a variable is a named space in the primary memory where data of a specific kind is stored ➤ The primary memory of a computer can be seen as a sequence of memory cells, where each memory cell holds on byte ➤ A combination of eight ones or zeros ➤ To know how much space to allocated for a variable, Python needs to know what data type (kind) it is ➤ Different data types allocate different amounts of space in the primary memory ➤ The variable is then used to either get the value in primary memory or to set it Foundations of Programming 32 Allocating Memory ➤ In Python, the kind of data we put in a variable will decided how much memory to use ➤ An integer (a whole number) takes 4 bytes while a float (real number, decimal) takes 8 bytes ➤ Python is dynamically typed, which means that the data type is decided at runtime ➤ Statically typed languages, like Java or C++, forces the programmer to decided the data type when programming ➤ Being dynamically typed, Python also allows for variables to change data type ➤ This should be avoided as it can make the code difficult to maintain Foundations of Programming 33 Checking the Type ➤ Using the built-in function type() it is possible to see the type of a variable a = 42 print(type(a)) a = 3.14159 print(type(a)) ➤ Again, avoid changing the data type of a variable! Foundations of Programming 34 Identifier ➤ The name of the variable is called the identifier ➤ There are rules for the identifier: ➤ It is a sequence of letters, digits and underscores ➤ It cannot start with a digit ➤ Cannot be a keyword ➤ Different case mean different variable (Area and area are different variables) ➤ Can actually be of any length Foundations of Programming 35 Good Practice ➤ When naming variables, it is a good idea to follow some good practices ➤ The name of a variable should reflect the content ➤ area is a good variable name while a is not as good for an area ➤ Avoid single letter variable names ➤ Can be used for some specific use cases, but generally not ➤ Names consisting of several words should use underscore ➤ Use student_average rather than studentAverage ➤ Begin names with a lower letter character Foundations of Programming 36 Scope of a Variable ➤ Imperative programming, like in Python, works in sequence ➤ This means that a variable has to be declared before it can be used ➤ If it has also been given a value, it is said to be initialised ➤ If a variable is accessed before it has been declared, Python will throw an NameError ➤ As variables are declared when given a value, it is possible to unintentionally create variables ➤ For example by misspelling an already created variable ➤ Scope will become more important when discussing if and iterator statements as well as functions Foundations of Programming 37 Assignment ➤ Assignment is done using the assignment operator (=) ➤ This operator has the lowest priority of all the operators ➤ Meaning that is will always be performed last in a statement ➤ Whatever is on the right side of it will be performed before the assignment itself ➤ This means that the variable itself can be used on both sides (overwritten by the assignment operator as the last step) steps = 12 steps = steps + 4 print(steps) 16 Foundations of Programming 38 Reading Input ➤ A good use of variables is to ask the user for input ➤ This can be done using the input() function ➤ Important: input() will always return text to the variable ➤ Therefore, the value needs to be type cast into the correct type ➤ If we expect an integer, we use int() to cast it to an integer ➤ Between the () a prompt for the user can be set (just as with print()) Foundations of Programming 39 Asking for Input ➤ The variable is set to the left of the input() function and assigned a value print('What is the answer to the question about life, the universe and everything? ') answer = input() answer = int(answer) print('The answer is', answer) ➤ Below is an execution of the program where the user writes 42 on the keyboard and hits enter What is the answer to the question about life, the universe and everything? 42 The answer is 42 Foundations of Programming 40 Somewhat Terser ➤ The code can be created a bit more compact by having the prompt as well as the conversion all in the same statement answer = int(input('What is the answer to the question about life, the universe and everything? ')) print('The answer is', answer) ➤ The output will be the same as before, except that the user will now be able to write the answer on the same line as the question What is the answer to the question about life, the universe and everything? 42 The answer is 42 Foundations of Programming 41 Constants? ➤ Many programming languages include syntax for creating variables with a constant value ➤ A value that never changes ➤ An example would be a value for pi, like 3.14159 ➤ In Python, however, no such keyword exists and Python instead relies on code convention ➤ Any variable with a constant value should be named in all caps ➤ For example PI = 3.14159 ➤ Notice that there is no mechanism in Python to stop a programmer from changing the value of PI Foundations of Programming 42 Arithmetics Foundations of Programming 44 Calculating ➤ As all programming languages, Python can do calculating ➤ This was one of the basic ideas of computers (hence the name) ➤ Two different data types for numerical values are available in Python ➤ Integers for whole numbers ➤ Floats for numbers with a decimal point ➤ Values of these kinds as well as variables are used together with mathematical operators to create expressions Foundations of Programming 45 Mathematical Operators ➤ Python has seven operators ➤ The usual +, -, * and / ➤ For addition, subtraction, multiplication and division ➤ Additional operators: ➤ // for integer division ➤ ** for exponentiation ➤ % for the remainder after division Foundations of Programming 46 The Four Arithmetic Operators ➤ Addition, subtraction, multiplication and division work as expected ➤ All are available as binary operators, while + and - are also available as unary operators ➤ For example for representing negative values (like -12.5) ➤ Python follows the priority rules of mathematics ➤ Multiplication has a higher priority than addition, for example ➤ Using parenthesis, Python can force some part of the expression to be evaluated before its priority ➤ Again, just as in mathematics Foundations of Programming 47 Some calculations first = 12 second = 52 sum = first + second print(sum) print(first - second) print(first * second) print(first / second) 64 -40 624 0.23076923076923078 ➤ Notice how the division returns a floating number Foundations of Programming 48 More calculations ➤ Notice the parenthesis in the first expression calculate_one = (3 + 4) * 4 calculate_two = 3 + 4 * 4 print(calculate_one) print(calculate_two) answer = 6 / 5 print(answer, type(answer)) 28 19 1.2 Foundations of Programming 49 Division ➤ The division shown on the previous slide is called true division as it results in a floating-point number ➤ In Python, it is also possible to do an integer division using // as the operator print(13 / 7) print(13 // 7) 1.8571428571428572 1 ➤ The result is truncated, the fractional part is just removed ➤ The effect of this is that integer division will give the number of times the divisor (right side) fit in the dividend (left side) Foundations of Programming 50 Power ➤ To calculate exponentiation the ** operator is used ➤ Below 216 is calculated answer = 2 ** 16 print(answer) 65536 ➤ As usual, any literal number can be substituted by a variable a = 2 b = 8 print(a ** b) 256 Foundations of Programming 51 Modulo ➤ The % operator (called modulo) gives the remainder after a division ➤ This can be useful to find out if a number is odd or even ➤ An even number will result in 0 for the modulo operator ➤ Notice how integer division will result in how many times a number fits in another, while modulo will result in what is left (if anything) print('14 is even', 14 % 2) print('13 is odd', 13 % 2, 'since 13//2 =', 13 // 2) print('and 2 times 6 is 12 (one missing)') 14 is even 0 13 is odd 1 since 13//2 = 6 and 2 times 6 is 12 (one missing) Foundations of Programming 52 Shortcut Assignment Operators ➤ All the operators can be combined with the assignment operator ➤ This makes it easier and faster to do common operations like increasing a variable by one ➤ The shortcut operator first has the mathematical operator and then the assignment symbol (=) ➤ Unlike several other languages, Python does not have an assignment operator to just add on (or subtract one) from a variable Foundations of Programming 53 Some examples ➤ Adding one to a variable called counter and also subtracting 2 counter = 1 counter += 1 print(counter) counter = 1 counter = counter + 1 print(counter) counter -= 2 # same as counter = counter - 2 print(counter) 2 2 0 Foundations of Programming 54 Examples of Other Assignment Operators number = 10 number /= 2 # same as number = number / 2 print(number) number *= 2 # same as number = number * 2 print(number) number **= 2 # same as number = number ** 2 print(number) 5.0 10.0 100.0 Foundations of Programming 55 Type Conversion ➤ Even though Python does not seem like a typed language, it does work a lot with the data types ➤ When making a calculation with two different data types an automatic type conversion is done to the data type with larger precision ➤ For example, if an integer is multiplied with a float, the integer is converted into a float ➤ This also makes the result into the data type with the larger precision print(5 * 2.33) print(type(5 * 2.33)) 11.65 Foundations of Programming 56 Explicit Type Conversion ➤ Sometimes it is desirable to make an explicit type conversion ➤ To convert a variable that is a float into an integer, use the int() function pi = 3.14159 print(int(pi)) number = 2.8 print(int(number)) 3 2 ➤ Notice that the value is truncated, not rounded to the correct value Foundations of Programming 57 Rounding ➤ Rounding will be dealt with more in-depth later ➤ To round a value, it is possible to use the round() function number = 2.8 print(round(number)) print(number) 3 2.8 ➤ The value is never changed by the function, as seen above Foundations of Programming 58 Summary Foundations of Programming 60 Summary ➤ This has been an introduction to the sequence concept ➤ Statements ➤ Expressions ➤ Input and output ➤ Variables and data types 💻 ➤ All of this is fundamental to understand the rest of programming Foundations of Programming 61

Use Quizgecko on...
Browser
Browser