Foundations of Programing Python Practical Session 1 1

  • Slides: 43
Download presentation
Foundations of Programing Python Practical Session #1 1

Foundations of Programing Python Practical Session #1 1

Plan • Administration: • Course site • Homework submission guidelines • Background on programming

Plan • Administration: • Course site • Homework submission guidelines • Background on programming • Python: • • • Working environment Editor vs. shell Variables Conditional Statements (if/else) Class Exercise • Discuss Homework 1 2

Hanan Zaichyk • Office hours: Tuesday 16 -18. (verify in advance) • Mail: zaichyk@post.

Hanan Zaichyk • Office hours: Tuesday 16 -18. (verify in advance) • Mail: [email protected]. bgu. ac. il Tom Yaacov • Office hours: Tuesday 10 -12. (verify in advance) • Mail: [email protected] bgu. ac. il • Personal request – by mail • Questions about class material – Course website. 3

Administration: Course Site - Moodle http: //www. cs. bgu. ac. il/~ipp 191 • All

Administration: Course Site - Moodle http: //www. cs. bgu. ac. il/~ipp 191 • All course material. • Lectures, practical Sessions, homework, solutions, code examples, details of course staff. • Announcements • Instructions (e. g. how to install stuff at home) • Automatic homework submission, (manual) grades. • Public Forum. • Ask freely – but read others’ too – questions repeat themselves. 4

Administration: Homework • Very important when learning to program! Where can I work? •

Administration: Homework • Very important when learning to program! Where can I work? • CSE Computer labs • Your personal Desktop/Laptop 5

Administration: Submission Guidelines • Submission in singles! • Strict submission dates. • Must work

Administration: Submission Guidelines • Submission in singles! • Strict submission dates. • Must work on Python 3. 6 • No cheating! 6

Programming languages 7

Programming languages 7

Python • Widely used general-purpose, high-level programming language. • Simpler than C, Java, C++

Python • Widely used general-purpose, high-level programming language. • Simpler than C, Java, C++ and similar languages • Fast coding • Readability • Used by many organizations • Google, NASA, Red Hat, Yahoo, academic researches, … 8

http: //fossbytes. com/programming-language-most-important-2016 -ieee/

http: //fossbytes. com/programming-language-most-important-2016 -ieee/

Working Environment We will work with Python. 36 Install Python (at home): • •

Working Environment We will work with Python. 36 Install Python (at home): • • https: //www. python. org/downloads/release/python-364/ Download Python for your operating system. The installation is quick and quite simple. Install Py. Charm (at home): • • https: //www. jetbrains. com/pycharm/download/#section=windows Download Community Py. Charm for your operating system. The installation is quick and quite simple. 10

IDLE Shell • The Python shell is convenient for testing: • Individual statements. •

IDLE Shell • The Python shell is convenient for testing: • Individual statements. • Short code snippets. • The shell isn’t meant for writing complete programs. • Built in Console in Py. Charm – “Python Console” 12

Py. Charm - Python Editor We want to save a sequence of commands and

Py. Charm - Python Editor We want to save a sequence of commands and run it later in a new Python session. The Editor: - Write Python commands - Execute them in one key-press. Open Py. Charm from the start menu: • Create New Project • Name your project and locate it. • Use Existing Interpreter – Python 3. 6 13

Py. Charm – Cont. In the new window: Right click on project name New

Py. Charm – Cont. In the new window: Right click on project name New Python File Choose a name. The suffix ‘. py’ will be added to the end of the name. 14

Py. Charm – Cont. Run Python: Right click on project name Run name The

Py. Charm – Cont. Run Python: Right click on project name Run name The output appears in the Run window (Below). 15

What are Variables ? A value in the computer’s memory. A variable: - has

What are Variables ? A value in the computer’s memory. A variable: - has a name (for program access) - refers a block in memory that holds some value - has a type – according to its value This is how data is handled In Program: some_variable In Program, Interpretation by Type: int 01000001 1094861636 01000010 01000011 str In Memory: flo 'ABCD' 0100 at 12. 141422 16

Numbers and their Types >>> a = 4 >>> type(a) <class 'int'> # integers

Numbers and their Types >>> a = 4 >>> type(a) <class 'int'> # integers type >>> b = 3. 14159 >>> type(b) <class 'float'> # floating point ("reals") type • Arithmetic operations: + - * / % (modulo) ** (power) 17

Variables and Assignments n >>> n = 10 >>> m_2012 = (10+4)*5 m_2012 70

Variables and Assignments n >>> n = 10 >>> m_2012 = (10+4)*5 m_2012 70 10 The left hand side is a variable. The right hand side is an expression. The interpreter: • First evaluates the expression • Then assigns the value to the variable The variable's name is a sequence of letters, digits and underscores (‘_’). 18

Variables and Assignments: Changing the value of a variable: >>> n=12 >>> n=11 >>>

Variables and Assignments: Changing the value of a variable: >>> n=12 >>> n=11 >>> n 11 Changing the type of a variable: >>> n=1. 3141 >>> n 1. 3141 Variables can be used in expressions: >>> pi = 3. 14159 >>> pi*2 + 1 7. 28318 19

Variables and Assignments – Cont. Referring to undefined variables leads to runtime error >>>

Variables and Assignments – Cont. Referring to undefined variables leads to runtime error >>> check_this Traceback (most recent call last): File "<pyshell#16>", line 1, in <module> check_this Name. Error: name 'check_this' is not defined 20

Program Readability • Real computer programs include thousands of code lines, lots of variables.

Program Readability • Real computer programs include thousands of code lines, lots of variables. • Readability is very important for code maintenance, it is a requirement in this course! • The next slide list some programming conventions that are crucial for readability. 21

Program Readability – Cont. • Choose informative variable names: Not informative: a_string sm w

Program Readability – Cont. • Choose informative variable names: Not informative: a_string sm w student_name word_count • Informative: Are i, j, m , n informative names? sum_of_expenses Depends on context. • Comments: • option 1: begin with # (one line comment) • option 2: surrounded by """ (3 double quotes) when spanned over multiple lines • Documentation is most important before ‘logical units’ or complex implementation. 22

Strings • A string is an ordered sequence of characters. • In Python, string

Strings • A string is an ordered sequence of characters. • In Python, string constants can be enclosed in either 'single quotes' or "double quotes". • Choose between the quotes at your convenience: "Here's one example. " 'She said: "this is cool". ' 23

Strings – Cont. >>> mssg 1="Let there" >>> mssg 1[0] 'L' >>> mssg 2="

Strings – Cont. >>> mssg 1="Let there" >>> mssg 1[0] 'L' >>> mssg 2=" be light" >>> mssg 1 + mssg 2 'Let there be light‘ >>> len('abcde') 5 >>> str(5) ‘ 5’ What will the next expression print? >>> mssg 1 + mssg 2 * 3 'Let there be light' 24

String Slicing Think of string indexes as pointing between characters. >>> a=‘Hello’ >>> a[1:

String Slicing Think of string indexes as pointing between characters. >>> a=‘Hello’ >>> a[1: 3] 'el' >>> a[1: ] 'ello' >>> a[-4: -2] 'el' >>> a[-2: -4: -1] ‘ll’ >>> a[: -3] 'He' >>> a[-3: ] 'llo’ >>> 'hello'[1: 5: 2] 'el' H e l l o 0 1 2 3 4 -5 -4 -3 -2 -1 25

Boolean Variables, Logical Operators • Boolean values: True or False. >>> >>> a =

Boolean Variables, Logical Operators • Boolean values: True or False. >>> >>> a = True b = True c = False • Compose boolean expressions with logical operators: and / or / not: >>> a and b True >>> a and c False >>> a or c True >>> not a False 26

Comparisons • Comparison operators: • == (Note: twice ‘=‘, this is not assignment) •

Comparisons • Comparison operators: • == (Note: twice ‘=‘, this is not assignment) • != • > • < • >= • <= • Comparisons evaluate to True or False. • Can be chained: e. g. 1 < 3 < 6 != 7 evaluates to True. • Can we compare a < 3? Go ahead and try! 27

Comparison Examples Numbers Strings (compared lexicographically) >>> 5. 0 == 5 >>> 'abc' ==

Comparison Examples Numbers Strings (compared lexicographically) >>> 5. 0 == 5 >>> 'abc' == 'abc' True >>> 6 != 2*3 >>> 'abc' == 'ABC' False >> not(-2 >= 1) >>> 'a' > 'b' True False >>> (-2 >= 1) or (-2 <= -1) >>> 'kz' > 'ka' True >>> a = 1 <= -2 <= -1 >>> 'abc'[1: ] == 'bc' >>> print a True False >>> '7' == 7 >>> type(a) False <type 'bool'> 28

Variables - Summary • We saw the types ‘int’, 'float', 'str‘, ‘bool’. • ‘int’

Variables - Summary • We saw the types ‘int’, 'float', 'str‘, ‘bool’. • ‘int’ – integer numbers, ‘float’ – real numbers. • Assignments: variable name = expression • Subsequent assignments to the same variable can change its value and even its type. • Some operations allow “mixing" variables of different types, e. g. 'hi' * 2. • Booleans: • True and False are boolean constants. • Boolean expressions through or / and / not. • Comparisons yield boolean values. 29

Algorithms…. 30

Algorithms…. 30

Algorithms…. You can think of it as a very good instruction list Leave no

Algorithms…. You can think of it as a very good instruction list Leave no room for doubts 31

Conditional Statements, if if condition: do something 32

Conditional Statements, if if condition: do something 32

if Example >>>  if 54 % 18 == 0: # the remainder of

if Example >>> if 54 % 18 == 0: # the remainder of 54 divided by 18 print ("54 is divisible by 18”) print ("54 is also divisible by 2 and 3”) 54 is divisible by 18 54 is also divisible by 2 and 3 • Following the if statement: Open a new scope = one tab to the right. • The indented commands are under the scope of the if statement only. 33

Conditional Statements, if-else if condition: statements 1 else: statements 2 34

Conditional Statements, if-else if condition: statements 1 else: statements 2 34

if-else Example >>>  if 54 % 17 == 0: # the remainder of

if-else Example >>> if 54 % 17 == 0: # the remainder of 54 divided by 17 print ("54 is divisible by 17”) else: print ("54 is not divisible by 17”) 54 is not divisible by 17 Note how each of if and else has its own indented statements under its own scope. 35

Conditional Statements, if-else if condition 1: statements 1 elif condition 2: statements 2 elif

Conditional Statements, if-else if condition 1: statements 1 elif condition 2: statements 2 elif condition 3: statements 3 else: statements 4 36

if-else Example >>> my_chips = 4*9*3 >>> your_chips = 5*8*2 >>>  if my_chips

if-else Example >>> my_chips = 4*9*3 >>> your_chips = 5*8*2 >>> if my_chips > your_chips: print ("I won : -)”) elif your_chips > my_chips: print ("You won : -(”) else: print ("It's a tie : -O”) I won : -) Again, each of if, else has its own indented statements. 37

Nested Conditional Statements if n % 2 == 0: if n % 5 ==

Nested Conditional Statements if n % 2 == 0: if n % 5 == 0: # NESTED if print (n, 'is divisible by 2 and by 5, so also by 10. ’) else: # NESTED else, pertains to NESTED if. print (n, 'is divisible by 2 but not by 5. ’) else: # Not nested, thus pertains to FIRST if. print (n, 'is not divisible by 2. ’) • What will be printed when n = 20? 20 is divisible by 2 and by 5, so also by 10. • What will be printed when n = 22? 22 is divisible by 2 but not by 5. • What will be printed when n = 21? 21 is not divisible by 2. 38

Class Example Donuts: Input: Define a variable named donuts and assign to it some

Class Example Donuts: Input: Define a variable named donuts and assign to it some number (of donuts). Output: • If donuts is no more than 5, print 'Number of donuts: donuts. ' • Otherwise, if donuts is no more than 10, print 'Number of donuts: donuts. . . ' • Otherwise, print 'Number Note: the trailing ‘. ’ / space before them. of donuts: a lot!' ‘…’ / ‘!’ must be printed without any Run your program. Examples are in the next slide. 39

Class Example – Cont. Examples: For 5 donuts you should get: Number of donuts:

Class Example – Cont. Examples: For 5 donuts you should get: Number of donuts: 5. For 9 donuts you should get: Number of donuts: 9. . . For 23 donuts you should get: Number of donuts: a lot! 40

Solution to Class Example donuts = 7 if donuts <= 5: print ('Number of

Solution to Class Example donuts = 7 if donuts <= 5: print ('Number of donuts: ', str(donuts) + '. ‘) elif donuts <= 10: print ('Number of donuts: ', str(donuts) + '. . . ‘) else: print ('Number of donuts: a lot!‘) 41

“My Code doesn’t Work!” • Go over your code carefully. • Consult course slides.

“My Code doesn’t Work!” • Go over your code carefully. • Consult course slides. • Google (a useful and legitimate source). • Good forums to ask questions online: stackoverflow. com, underwar. co. il • Check the public forum in Moodle. • Submit a question to forum (reply within 48 hours). • Please never paste solution code in the forum. 42

Understanding Errors Where in your program? Traceback (most recent call last): File "C: UsersJohnDesktopblah.

Understanding Errors Where in your program? Traceback (most recent call last): File "C: UsersJohnDesktopblah. py", line 2, in <module> b = 2 / a Zero. Division. Error: integer division or modulo by zero The last line of the error is most informative. 43