0% found this document useful (0 votes)
7 views40 pages

Programming and Data Representation

This document is a workshop presentation focused on programming and data representation using Python. It covers various topics including programming basics, data types, boolean expressions, selection, iteration, built-in functions, and procedures. The content is structured to guide beginners through fundamental concepts and practical examples in Python programming.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
7 views40 pages

Programming and Data Representation

This document is a workshop presentation focused on programming and data representation using Python. It covers various topics including programming basics, data types, boolean expressions, selection, iteration, built-in functions, and procedures. The content is structured to guide beginners through fundamental concepts and practical examples in Python programming.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 40

forbeginners.html workshop.

cs

1
2
3 Programming and Data Representation
4
5
6
[Computer science Workshop]
7
8
9 < Erik Iusupov, Vladislav Nikitin, Ivan Tsarapkin >
10
11
12
13 }
14

Programming Language
forbeginners.html workshop.cs

1
2
Contents Of ‘This Presentation’;
3 Presentation contains:
4 ∗ Programming languages (python).
∗ Programming basics.
5 ∗ Data types.
6 ∗ Boolean expressions.
∗ Selection.
7 ∗ Iteration.
8 ∗ Built-in functions.
∗ Procedures.
9 ∗ Functions.
10 ∗ Passing parameters to subroutines.
∗ Passing parameters to functions.
11
∗ Passing parameters to procedures.
12 ∗ Putting it all together.
13 ∗ Arrays.
∗ Text files.
14

Programming Language
forbeginners.html workshop.cs

01 {
1
2
3
4
5
6 [Programming languages]
7
8
9
< Python >
10
11

}
12
13
14

Programming Language
Introduction to Python
1 Python was developed by Guido von Rossum in the late 1980s. Python 2.0 was released in 2000 and
2 Python 3.0 in 2008. Python is multi-paradigm programming language, which mean it supports both
object-oriented programming and structured programming.
3
4 Key features:
5 Every statement must be on separate line;
6 Indentation is significant;
7 Keywords are written in lower case;
8 Case is important;
9 Programs are interpreted;
10 Code often uses concept called “slicing”.
11
12
13
14
forbeginners.html workshop.cs

02 {
1
2
3
4
5
6 [Programming basics]
7
8
9
< Python >
10
11

}
12
13
14

Programming Language
Variables
1 Variable is container which store one piece of information (e.g.
2 number or text)
3
Unlike many programming languages, which use static typing
4
(requiring a variable type to be declared), Python uses dynamic
5
typing. That means you can assign values of any type to a variable
6
without declaring it beforehand.
7
8 To assign a variable in Python, we write variable name, followed by
9 equal sign (=) and then the value we assign.
10
11 Example:
12
x=5
13
14 y = “Hello”
Arithmetic Operators
1 In Python, we use following arithmetic operators:
2 Notation Name Example Result
3
4 + Addition 10 + 3 13 Task (Question 14.01)
5 - Subtraction 10 - 3 7
6 Evaluate examples:
7 * Multiplication 10 * 3 30 4 * 3 - 3 ** 2
8 / Division 10 / 3 3.3333… (4 * 3 - 3) ** 2
9 4 * (3 - 3) ** 2
10 // Integer 10 // 3 3 (only whole 4 * (3 - 3 ** 2)
division part)
11
12 ** Exponent 10 ** 3 1000
13
% Modulus 10 % 3 1
14
Output to the screen
1 In Python, function print() is used to display
2 text or variables to the screen. The argument
3
inside of brackets is the text which will be
4
5
displayed on screen.
6
You are also able to combine strings by using
7
either plus (+) or comma (, ) signs.
8
9 Example:
10
11 name = “Denis”
12
13 print(“Hello, ” + name)
14
Input from the user
1 The input() function allows program to get
2 input from the user. You are also able to
3
write a tip for user as argument inside of
4
5
the brackets.
6
Example:
7 Task 14.02
8 name = input(“What is your name?”)
9 Write code asking user to
10 print(“Hello, “ + name) write distance in
11 kilometers, and then
12 output distance in miles.
13 One mile is equal to 1.61
14 km.
Comments
1 Comments are lines of texts, ignored by interpreter. You
2 can explain meaning of your code, or for instance, hide
3
some code which you don’t use at the moment, but may need
4
5
later.
6
In Python, comments are created using hashtag (#) sign.
7
8 Example:
9
10 #This text is ignored by interpreter
11
12 #print(“Hello, world”)
13
#Even previous line of code will not work, since it is
14
only comment!
forbeginners.html workshop.cs

03 {
1
2
3
4
5
6 [Data types]
7
8
9
< Python >
10
11

}
12
13
14

Programming Language
Data types
1 Python supports 4 basic data types - int
2 (Integer; whole numbers), float (Real; number
3 with decimal point), bool (Boolean; True or
4 False), str (String; some text).
5
6 Example:
7
x = 52 # int
8
9 y = 13.4 # float
10
11
name = “Denis” # str
12 is_fun = True # bool
13
14
forbeginners.html workshop.cs

04 {
1
2
3
4
5
6 [Boolean expressions]
7
8
9
< Python >
10
11

}
12
13
14

Programming Language
Boolean Expressions
1 Python has following relational operators:
2
Notation Name Example Result Notation Name
3
4 == Equal 5 == 3 False __ and __ Logical
5 AND
!= Not equal 6 != 2 True
6
7 > Greater 10 > 9 True
8 __ or __ Logical
>= Greater or 7 >= 8 False OR
9
Equal
10
11 < Less 5<8 True
not __ Logical
12 NOT
<= Less or 8 <= 7 False
13 Equal
14
forbeginners.html workshop.cs

05 {
1
2
3
4
5
6 [Selection]
7
8
9
< Python >
10
11

}
12
13
14

Programming Language
Selection
1 Python uses if, elif, else statements for performing different actions based on conditions.
2
3
Example:
4 age = int(input(“How old are you?”)) # int() translates from str to int data type
5
6 if age >= 18: # first selection statement
7
print(“You can watch 18+ content!”)
8
9 elif age >= 16: # this stement works only if previous ones fails
10
11 print(“You can watch 16+ content!”)
12
else: # this statement works only if all previous ones failed
13
14 print(“You cannot watch this content!”)
Cross-topic exercise 1
1
2
Write program that will receive 3 numbers from the user, and
3 then using conditions and boolean expressions, find the largest
4 value. Program has to display the largest number and average of
5 3 initial numbers.
num1 = int(input(“Enter the first number: ”))
6 num2 = int(input(“Enter the second number: ”))
7 num3 = int(input(“Enter the third number: ”))

8 Extra questions (for discussion):


if num1 >= num2 and num1 >= num3:
max = num1
9 * How to check is the largest elif num2 >= num1 and num2 >= num3:
10 max = num2
number odd or even number? else:
11 max = num3
12 * How to find the smallest number?
avg = (num1 + num2 + num3) / 3
13 print(“The largest value is “ + max)
14 print(“Average value is “ + avg)
forbeginners.html workshop.cs

06 {
1
2
3
4
5
6 [Iteration]
7
8
9
< Python >
10
11

}
12
13
14

Programming Language
Count-controlled (FOR) loops
1 In Python, count-controlled for loops are loops that execute a
2 specific number of times. They are typically implemented using the
3 range() function, which generates a sequence of numbers.
4 Syntax:
5
for <control variable> in range (s, e, i): #the values s,e and i must
6 be integer
7
8 <statement(s)> #s=start number, e=stop number, i=step
9 Example:
10
for x in range(2, 14, 3):
11
12 print(x, end=’ ‘)
13 Output: 2, 5, 8, 11
14
Pre-condition loops
1 Pre-condition loops are loops where the condition is checked before
2 the body of the loop is executed. These are typically implemented
3 using a while loop. Pre-condition loops will execute the statements
within the loop as long as the condition evaluates to true.
4
5 Syntax:
6 while <condition>
7
8 <statement(s)>
9 Example:
10
Answer = ‘ ‘
11
12 while Answer != ‘Y’:
13 Answer = input(“Enter Y or N”)
14
forbeginners.html workshop.cs

07 {
1
2
3
4
5
6 [Built-in functions]
7
8
9
< Python >
10
11

}
12
13
14

Programming Language
String manipulation functions
1 Programming environments provide many built-in functions. Some of
them are always available to use; some need to be imported from
2
specialists module libraries.
3
This String [P]#Access a single characters using its position P in a sting ThisString
4 #Counts from 0

5 chr(i) #Returns the character whose ASCII value is i

6 ord(ch) #Returns the ASCII value of character ch

7 len(S) #Returns the integer value representing the length of string S

S[0:L] #Returns leftmost L characters from S


8
S[-L:] #Returns rightmost L character from S
9
S[P : P + L] #Returns a string of length L starting at position P from S
10
Ch.lower() #Returns the character value representing the lower case equivalent of Ch
11
Ch.upper() #Returns the character value representing the upper case equivalent of Ch
12 S.upper() #Returns a string formed by converting all alphabetic characters of S to upper case
13 S.lower() #Returns a string formed by converting all alphabetic characters of S to lower case
14 S = S1 + S2 #Concatenate (join) two stings
Slicing in Python
1
2
3
4
5 Slicing in Python is a method for extracting a subset of elements
6 from sequences like strings, lists, tuples, and other iterable
7 objects. With slicing, you can retrieve a portion of a collection
8 without modifying the original.
9
10
11
12
13
14
forbeginners.html workshop.cs

08 {
1
2
3
4
5
6 [Procedures]
7
8
9
< Python >
10
11

}
12
13
14

Programming Language
forbeginners.html workshop.cs

09 {
1
2
3
4
5
6 [Functions]
7
8
9
< Python >
10
11

}
12
13
14

Programming Language
forbeginners.html workshop.cs

10 {
1
2
3
4
5 [Passing parameters to
6
7 subroutines]
8
9
< Python >
10
11

}
12
13
14

Programming Language
Definition
When a subroutine requires one or more values from the main program,
1 we supply these as arguments to the subroutine at call time. This is
2 how we use built-in functions. We don’t need to know the identifiers
used within the function when we call a built-in function.
3
4 When we define a subroutine that requires values to be passed to the
5 subroutine body, we use a parameter list in the subroutine header.
When the subroutine is called, we supply the arguments in brackets.
6
The arguments supplied are assigned to the corresponding parameter of
7 the subroutine (note the order of the parameters in the parameter
8 list must be the same as the order in the list of arguments). This is
9 known as the subroutine interface.
10 Example:
11
12 def greet(name): # name — Parameter
13 print(f"Hello, {name}!")
14
greet("Alice") # "Alice" — Argument
forbeginners.html workshop.cs

11 {
1
2
3
4
5
6 [Passing parameters to functions]
7
8
9
< Python >
10
11

}
12
13
14

Programming Language
Function definition (by value)
In Python, you can give parameters to a function in the function definition.
1
2 The syntax for defining a function with parameters is as follows:
3
def function_name(param1, param2, ...):
4
5 # Function body

6
In this syntax, function_name is the name of the function, param1, param2, and
7 so on, are the parameters that the function takes. You can define as many
8 parameters as needed by separating them with commas.

9 When you call the function, you can pass arguments to the function using the
10 following syntax:
11
function_name(arg1, arg2, ...)
12
13 In this syntax, function_name is the name of the function, and arg1, arg2, and
so on, are the arguments that you want to pass to the function. The arguments
14 should be passed in the order that the parameters are defined in the function.
forbeginners.html workshop.cs

12 {
1
2
3
4
5
6 [Passing parameters to procedures]
7
8
9
< Python >
10
11

}
12
13
14

Programming Language
1. Procedure definition (by reference)

1 For procedures, a parameter can be passed by reference. At call time, the


argument must be a variable. A pointer to the memory location (the address) of
2
that variable is passed into the procedure. Any changes that are applied to
3
the variable’s contents will be effective outside the procedure in the calling
4 program/module. When parameters are passed by reference, when the values
5 inside the subroutine change, this affects the values of the variables in the
6 calling program. Consider the pseudocode procedure AdjustValuesForNextRow
7 below.
8
We can now make that explicit:
9
10 PROCEDURE AdjustValuesForNextRow(BYREF Spaces : INTEGER, Symbols : INTEGER)
11
Spaces ← Spaces - 1
12
13 Symbols ← Symbols + 2
14
ENDPROCEDURE
2. Procedure definition (by reference)

1 The pseudocode statement to call the procedure is:


2
CALL AdjustValuesForNextRow(NumberOfSpaces,
3
NumberOfSymbols)
4
5 The values of the parameters Spaces and Symbols are
6 changed within the procedure when this is called. The
7 variables NumberOfSpaces and NumberOfSymbols in the
8 program code after the call will store the updated
9 values that were passed back from the procedure.
10
11 Note that neither of these methods of parameter passing applies to
Python. In Python, the method is called pass by object reference. This is
12 basically an object-oriented way of passing parameters. The important
13 point is to understand how to program in Python to get the desired effect.
14 If you want to know it, let us know! We will be happy to present our
findings to you in the near future, if you would like.
forbeginners.html workshop.cs

13 {
1
2
3
4
5
6 [Putting it all together]
7
8
9
< Python >
10
11

}
12
13
14

Programming Language
The good ending of our program

1 The parameters of the


2 subroutines are given different Sometimes, you may feel intimidated by
3 names from the variables in the complicated and
4
main program. This is done difficult-to-understand programs, but
deliberately to make it clear that don't worry! Just stay calm and
5
the parameters and local collected, like this guy.
6 variables within a subroutine are
7 distinct from those in the calling
8 program or module. When a
9 parameter is passed by
10 reference to a procedure, the
parameter name within the
11
procedure refers to the same
12 memory location as the variable
13 name passed to the procedure
14 as an argument.
The good ending of our program
# This function adds two numbers while True:

1
# take input from the user
def add(x, y): choice = input("Enter choice(1/2/3/4): "
)
return x + y
2 # check if choice is one of the four options
if choice in ('1', '2', '3', '4'):

3 # This function subtracts two numbers #this helps you to identify errors during the execution of your
def subtract(x, y): program
4 return x - y try:
num1 = float(input("Enter first number: "))

5
num2 = float(input("Enter second number: "))
# This function multiplies two numbers except ValueError:
print("Invalid input. Please enter a number.")
6 def multiply(x, y): continue
return x * y
7
if choice == '1':
print(num1, "+", num2, "=", add(num1, num2))
# This function divides two numbers
8 def divide(x, y):
elif choice == '2':
print(num1, "-", num2, "=", subtract(num1, num2))

9 return x / y elif choice == '3':


print(num1, "*", num2, "=", multiply(num1, num2))
10 elif choice == '4':

11
print("Select operation.") print(num1, "/", num2, "=", divide(num1, num2))
print("1.Add") # check if user wants another calculation
12 print("2.Subtract") # break the while loop if answer is no
next_calculation =input("Let's do next calculation? (yes/no): )"
print("3.Multiply")
13 print("4.Divide")
if next_calculation == "no":
break
else:
14 print("Invalid Input")
forbeginners.html workshop.cs

14 {
1
2
3
4
5
6 [Arrays]
7
8
9
< Python >
10
11

}
12
13
14

Programming Language
1D Arrays

1 ● An array is an ordered, static set of elements in a fixed-size memory location


2 ● An array can only store 1 data type
3 ● A 1D array is a linear array
4 ● Indexes start at generally start at 0, known as zero-indexed
5
Declaration of an array:
6 DECLARE List1 : ARRAY[1:3] OF STRING // 3 elements in this list
7 DECLARE List2 : ARRAY[0:5] OF INTEGER // 6 elements in this list
DECLARE List3 : ARRAY[1:100] OF INTEGER // 100 elements in this list
8 DECLARE List4 : ARRAY[0:25] OF STRING // 26 elements in this list
9
10
11
12
13
14
2D Arrays

1 ● A 2D array extends the concept on a 1D array by adding another dimension


2 ● A 2D array can be visualised as a table with rows and columns
3 ● When navigating through a 2D array you first have to go down the rows and then
across the columns to find a position within the array
4
5 In pseudocode, a 2D array declaration is written as:
6 DECLARE <identifier> : ARRAY[<LBound1>:<UBound1>,
7 <LBound2>:<UBound2>] OF <dataType>
8
9
10
11
12
13
14
Lists

1 In Python, there are no arrays. The equivalent data structure is called a list. A list is an ordered
2 sequence of items that do not have to be of the same data type.
3 As there are no declarations, the only way to generate a list is to initialise one. You can
4 append elements to an existing list.
5 Example (1D):
6 List1 = [] Example(2D):
7 List1.append("Fred") Board = [[0, 0, 0, 0, 0, 0, 0],
List1.append("Jack") [0, 0, 0, 0, 0, 0, 0],
8
List1.append("Ali") [0, 0, 0, 0, 0, 0, 0],
9 [0, 0, 0, 0, 0, 0, 0],
10 [0, 0, 0, 0, 0, 0, 0],
11 [0, 0, 0, 0, 0, 0, 0]]
Board = [[0 for i in range(7)]
12
for j in range(6)]
13 Board = [[0] * 7] * 6
14
forbeginners.html workshop.cs

15 {
1
2
3
4
5
6 [Text files]
7
8
9
< Python >
10
11

}
12
13
14

Programming Language

You might also like