Презентация «Basic programming»

Смотреть слайды в полном размере
Презентация «Basic programming»

Вы можете ознакомиться с презентацией онлайн, просмотреть текст и слайды к ней, а также, в случае, если она вам подходит - скачать файл для редактирования или печати. Документ содержит 74 слайда и доступен в формате ppt. Размер файла: 170.62 KB

Просмотреть и скачать

Pic.1
Tirgul 2 Basic programming
Tirgul 2 Basic programming
Pic.2
Overview Variables Types : int, float, string User input Functions with input and output The Boolean
Overview Variables Types : int, float, string User input Functions with input and output The Boolean type and Boolean operations Conditional operation (if…else…)
Pic.3
Variables - Motivation Write a program which calculates the difference in the areas of a square with
Variables - Motivation Write a program which calculates the difference in the areas of a square with side = 1. 5 and the circle enclosed within it.
Pic.4
Variables - Motivation 1. 5*1. 5 –3. 14*(1. 5/2 )**2
Variables - Motivation 1. 5*1. 5 –3. 14*(1. 5/2 )**2
Pic.5
Variables - Motivation Two problems : The expression 1. 5*1. 5 –3. 14*(1. 5/2 )**2 is really difficu
Variables - Motivation Two problems : The expression 1. 5*1. 5 –3. 14*(1. 5/2 )**2 is really difficult to understand : When you get back to it after one week When debugging When the side of the …
Pic.6
Variables - Motivation Wouldn’t it be much more readable, modular, easy to modify in this format : s
Variables - Motivation Wouldn’t it be much more readable, modular, easy to modify in this format : side = 1. 5, PI = 3. 14 square_area = side*side radius = side/2 circle_area = PI*r2 answer = …
Pic.7
Variables Variables let us define “memory units” which can “remember” values. Variables have 2 main
Variables Variables let us define “memory units” which can “remember” values. Variables have 2 main components : name value
Pic.8
Variables Variables have 2 main functionalities : Set their value number_of_apples = 3 Get their val
Variables Variables have 2 main functionalities : Set their value number_of_apples = 3 Get their values tomorrow_apples = number_of_apples + 1
Pic.9
Variables – Naming conventions Use lower case letter number,apples Separate multiple words with unde
Variables – Naming conventions Use lower case letter number,apples Separate multiple words with underscore word_and_more_words Use meaningful names for names (don’t be shy to open a dictionary) z = …
Pic.10
Types Can we perform the following command ? x = 3 + 5 And this one ? x = 3 + “hello” Why not? 3 and
Types Can we perform the following command ? x = 3 + 5 And this one ? x = 3 + “hello” Why not? 3 and ‘hello’ are not of the same category. The name Python gives to the categories which differentiate …
Pic.11
Types int (Integer) : represent an Integer number (מספר שלם). E. g. 1024, 13, 92,0 float : represent
Types int (Integer) : represent an Integer number (מספר שלם). E. g. 1024, 13, 92,0 float : represent a fractional number. E. g. : 0. 0, 15. 62545, 3. 14 str (String) : represent text, a list of …
Pic.12
Types The type() function receives a value and return its type. type(3)  int type(3. 0)  float typ
Types The type() function receives a value and return its type. type(3)  int type(3. 0)  float type('3. 0')  str What happens when we mix types? type(1 + 0. 5)  float type(1 + …
Pic.13
Types What happens when we mix types? type(1 + 'some string') TypeError: unsupported opera
Types What happens when we mix types? type(1 + 'some string') TypeError: unsupported operand type(s) for +: 'int' and 'str' This is an error message which tells us we …
Pic.14
Error message Error messages are our friends, they help us detect bugs in our program and point out
Error message Error messages are our friends, they help us detect bugs in our program and point out how to fix them. When you get an error “keep calm and read the error message”.
Pic.15
Error message - Example >>> x = 49 >>> x/(49**0. 5 - 7) Traceback (most recent cal
Error message - Example >>> x = 49 >>> x/(49**0. 5 - 7) Traceback (most recent call last): File "C:/my_python/test. py", line 9, in <module> x/(49**0. 5 - 7) …
Pic.16
Error message - Example Traceback (most recent call last): File "C:/my_python/test. py", l
Error message - Example Traceback (most recent call last): File "C:/my_python/test. py", line 2, in <module> x/(49**0. 5 - 7) ZeroDivisionError: float division by zero
Pic.17
Error message - Example Traceback (most recent call last): File "C:/my_python/test. py", l
Error message - Example Traceback (most recent call last): File "C:/my_python/test. py", line 2, in <module> x/(49**0. 5 - 7) ZeroDivisionError: float division by zero
Pic.18
Error message - Example Traceback (most recent call last): File "C:/my_python/test. py", l
Error message - Example Traceback (most recent call last): File "C:/my_python/test. py", line 2, in <module> x/(49**0. 5 - 7) ZeroDivisionError: float division by zero
Pic.19
Error message - Example Traceback (most recent call last): File "C:/my_python/test. py", l
Error message - Example Traceback (most recent call last): File "C:/my_python/test. py", line 2, in <module> x/(49**0. 5 - 7) ZeroDivisionError: float division by zero
Pic.20
Error message - Example Traceback (most recent call last): File "C:/my_python/test. py", l
Error message - Example Traceback (most recent call last): File "C:/my_python/test. py", line 2, in <module> x/(49**0. 5 - 7) ZeroDivisionError: float division by zero
Pic.21
Error message - Example Traceback (most recent call last): File "C:/my_python/test. py", l
Error message - Example Traceback (most recent call last): File "C:/my_python/test. py", line 2, in <module> x/(49**0. 5 - 7) ZeroDivisionError: float division by zero
Pic.22
But what if we do want to mix types? my_apples = 3 print('I have ' + my_apples + ' ap
But what if we do want to mix types? my_apples = 3 print('I have ' + my_apples + ' apples') TypeError: Can't convert 'int' object to str implicitly The error …
Pic.23
Converting types (casting) int, float and str are not only names of types but also names of function
Converting types (casting) int, float and str are not only names of types but also names of functions which convert between types. Example : str(5)  '5' float(5)  5. 0 int('5') …
Pic.24
Converting types – int(),float() Converts string representing numbers to the represented numbers int
Converting types – int(),float() Converts string representing numbers to the represented numbers int('5')5 Cannot convert strings not representing an int : int('5. 5'), …
Pic.25
User input To make a program interactive we can ask the user for some inputs and act upon them. The
User input To make a program interactive we can ask the user for some inputs and act upon them. The function input(s) : Prints to the screen s Halts the program execution and waits for the user to …
Pic.26
User input - Example square_side = input('Insert side length: ') # Wait for user … 3 - The
User input - Example square_side = input('Insert side length: ') # Wait for user … 3 - The value of square_side is 3 area = square_side * square_side Will this work?
Pic.27
User input - Example area = square_side * square_side '3'*'3' TypeError: can
User input - Example area = square_side * square_side '3'*'3' TypeError: can't multiply sequence by non-int of type 'str' Input returns a string, and we can’t …
Pic.28
User input - Example square_side = float(input('Insert side length: ')) # Wait for user …
User input - Example square_side = float(input('Insert side length: ')) # Wait for user … 3 area = square_side * square_side The value of area is 9. 0
Pic.29
Functions with input def function_name(param1, param2,…,paramN): #indented code is here #as usual
Functions with input def function_name(param1, param2,…,paramN): #indented code is here #as usual
Pic.30
Functions with input When we call a function with input parameters, we can use the parameters’ value
Functions with input When we call a function with input parameters, we can use the parameters’ value inside the function using their name.
Pic.31
Functions with input
Functions with input
Pic.32
Functions with input
Functions with input
Pic.33
Functions with input
Functions with input
Pic.34
A word about scopes
A word about scopes
Pic.35
A word about scopes
A word about scopes
Pic.36
A word about scopes
A word about scopes
Pic.37
A word about scopes
A word about scopes
Pic.38
A function with more than 1 input def get_details(name, password): print('Name is :' + nam
A function with more than 1 input def get_details(name, password): print('Name is :' + name + ', Password is:' + password ) get_details('John', '1234')
Pic.39
Functions’ parameters default value Sometimes …. A function has an obvious use case that will be uti
Functions’ parameters default value Sometimes …. A function has an obvious use case that will be utilized most of the time You have prepared a good option for the user but don’t want to force her to …
Pic.40
Functions’ parameters default value def shoresh(number, root=2): print(number ** (1/root)) The first
Functions’ parameters default value def shoresh(number, root=2): print(number ** (1/root)) The first parameter, number, has no default value. Hence every call to the function must indicate its value. …
Pic.41
Functions’ parameters default value def shoresh(number, root=2): print(number ** (1/root)) shoresh(6
Functions’ parameters default value def shoresh(number, root=2): print(number ** (1/root)) shoresh(64) # Here we didn’t indicate the second variable, hence the default value was used >> 8 …
Pic.42
Function’s return value Many times we want functions to not only perform some functionality, but als
Function’s return value Many times we want functions to not only perform some functionality, but also to return a result. Using the return keyword, a function is able to return a value.
Pic.43
Function’s return value def always_return_5(): return 5 print('hi')
Function’s return value def always_return_5(): return 5 print('hi')
Pic.44
Function’s return value def always_return_5(): return 5 print('hi') print(3 + always_retur
Function’s return value def always_return_5(): return 5 print('hi') print(3 + always_return_5()) >>> 8
Pic.45
Function calling a function We can use the return value of one function as another function’s input.
Function calling a function We can use the return value of one function as another function’s input. def per_week(per_day=1): return per_day * 7 def per_year(how_many_per_week): return …
Pic.46
Function calling a function def per_week(per_day=1): return per_day * 7 # return 7 def per_year(how_
Function calling a function def per_week(per_day=1): return per_day * 7 # return 7 def per_year(how_many_per_week): return how_many_per_week * 52 print('Apples per year : ' + …
Pic.47
Function calling a function def per_week(per_day=1): return per_day * 7 # return 7 def per_year(how_
Function calling a function def per_week(per_day=1): return per_day * 7 # return 7 def per_year(how_many_per_week): return how_many_per_week * 52 # return 364 print('Apples per year : ' + …
Pic.48
Function calling a function We can use the return value of one function as another function’s input.
Function calling a function We can use the return value of one function as another function’s input. def per_week(per_day =1): return per_day * 7 # return 7 def per_year(how_many_per_week): return …
Pic.49
Multiple outputs functions To return more than one value, separate return values by comma def diff_a
Multiple outputs functions To return more than one value, separate return values by comma def diff_and_ratio(num1, num2): return num1-num2, num1/num2 diff, ratio = diff_and_ratio(1, 5) print(diff) …
Pic.50
None None is a special value which is used to represent absence of value. Every function which does
None None is a special value which is used to represent absence of value. Every function which does not return value explicitly, return None implicitly.
Pic.51
None - example def print_hi(): print('hi') x = print_hi() # x is assigned the value None p
None - example def print_hi(): print('hi') x = print_hi() # x is assigned the value None print(x) >>>hi >>>None
Pic.52
The Boolean type Like int, str and float , Boolean is another Python type. Boolean can get only one
The Boolean type Like int, str and float , Boolean is another Python type. Boolean can get only one of two values : True False type(True) >>> <class 'bool'>
Pic.53
Boolean expressions Boolean expressions are expressions which use Boolean operators to evaluate a va
Boolean expressions Boolean expressions are expressions which use Boolean operators to evaluate a value of True or False. For example > is a Boolean operator. Its Boolean evaluation is “Is the …
Pic.54
Boolean operators
Boolean operators
Pic.55
Boolean expressions 7 == 4  ? (7 != 2) == (5 > 4)  ? type(5 > 7) == type(8 < 3)  ?
Boolean expressions 7 == 4  ? (7 != 2) == (5 > 4)  ? type(5 > 7) == type(8 < 3)  ?
Pic.56
Boolean expressions 7 == 4  False (7 != 2) == (5 > 4)  True type(5 > 7) == type(8 < 3) 
Boolean expressions 7 == 4  False (7 != 2) == (5 > 4)  True type(5 > 7) == type(8 < 3)  True
Pic.57
Complex Boolean operators Take few Boolean operators and evaluate a new Boolean value from them. and
Complex Boolean operators Take few Boolean operators and evaluate a new Boolean value from them. and and or evaluate 2 Boolean expressions not evaluates 1 Boolean expression The return value of …
Pic.58
Complex Boolean operators Truth table
Complex Boolean operators Truth table
Pic.59
Conditional operation We do not always want to execute all the lines in our code. Sometimes we want
Conditional operation We do not always want to execute all the lines in our code. Sometimes we want to execute some lines only if a certain condition is maintained. For example : Divide 9 by user’s …
Pic.60
Conditional operation - if How do we implement this notion in Python? if boolean_expression: #Code t
Conditional operation - if How do we implement this notion in Python? if boolean_expression: #Code to perform if the #boolean_expression is True #(Note the indentation under the if #block).
Pic.61
Conditional operation - if For example : num = float(input('Insert a number‘)) if num != 0 : pr
Conditional operation - if For example : num = float(input('Insert a number‘)) if num != 0 : print(9/num) But what if the number does equal 0? We still want to let the user know.
Pic.62
Conditional operation - if num = float(input('Insert a number')) if num != 0 : print(9/num
Conditional operation - if num = float(input('Insert a number')) if num != 0 : print(9/num) if num == 0 : print('Cannot divide by 0') This is not a natural way to present our …
Pic.63
Conditional operation - else num = float(input('Insert a number')) if num != 0 : print(9/n
Conditional operation - else num = float(input('Insert a number')) if num != 0 : print(9/num) else: print('Cannot divide by 0') else should appear directly under an if block with …
Pic.64
Conditional operation - elif And what if we had some more options to choose from? If condition1 then
Conditional operation - elif And what if we had some more options to choose from? If condition1 then result1, if not, than if condition2 then result2 … if not, than if conditionN then resultN If none …
Pic.65
Conditional operation - elif if now == 'Morning': print('Good morning!') elif no
Conditional operation - elif if now == 'Morning': print('Good morning!') elif now == 'Noon': print('Good noon') else: print('It must be evening') The …
Pic.66
Nested if What operations could be included inside an if block? Any operations we like : print input
Nested if What operations could be included inside an if block? Any operations we like : print input … and – another if! An if inside another if is called nested if – it opens a new block with its …
Pic.67
Nested if - example if now == 'morning': if 'y' == input('Are you hungry?&#
Nested if - example if now == 'morning': if 'y' == input('Are you hungry?'): print('Bon appetit!') else: print('Some other time than') elif now == …
Pic.68
Nested if - example if now == 'morning': if 'y' == input('Are you hungry?&#
Nested if - example if now == 'morning': if 'y' == input('Are you hungry?'): print('Bon appetit!') else: print('Some other time than') elif now == …
Pic.69
split() The method split() returns a list of all the words in the string, using a given string as th
split() The method split() returns a list of all the words in the string, using a given string as the separator (default is whitespace) # a = 'hello'; b = 'world' >>> a,b …
Pic.70
Example Calculate the circumference (היקף) of a circle or square according to user request. Let’s br
Example Calculate the circumference (היקף) of a circle or square according to user request. Let’s break the problem into parts : 1. Get user input 2. Validate if is it either a circle or a rectangle …
Pic.71
Example – break it up into functions calculate_circle_ circumference() calculate_rectangle_ circumfe
Example – break it up into functions calculate_circle_ circumference() calculate_rectangle_ circumference() is_valid_shape_choice(choice) get_user_input() calculater_user_choice_circumference() …
Pic.72
«Basic programming», слайд 72
Pic.73
«Basic programming», слайд 73
Pic.74
Summary Today we have learned : How to use variable What are types and how to convert between them H
Summary Today we have learned : How to use variable What are types and how to convert between them How to receive an input from a user How to use functions which get input and return output …


Скачать презентацию

Если вам понравился сайт и размещенные на нем материалы, пожалуйста, не забывайте поделиться этой страничкой в социальных сетях и с друзьями! Спасибо!