Variables and data types

Similar documents
Fundamentals of Programming (C)

1.1. INTRODUCTION 1.2. NUMBER SYSTEMS

Data Representation and Binary Arithmetic. Lecture 2

Unit 3, Lesson 2 Data Types, Arithmetic,Variables, Input, Constants, & Library Functions. Mr. Dave Clausen La Cañada High School

Bits and Bytes. Data Representation. A binary digit or bit has a value of either 0 or 1; these are the values we can store in hardware devices.

Fundamentals of Programming

Chapter 2 Bits, Data Types, and Operations

Numbers and Computers. Debdeep Mukhopadhyay Assistant Professor Dept of Computer Sc and Engg IIT Madras

CPS 104 Computer Organization and Programming Lecture-2 : Data representations,

Number Representations

Chapter 2 Bits, Data Types, and Operations

Number System (Different Ways To Say How Many) Fall 2016

CS/ECE 252: INTRODUCTION TO COMPUTER ENGINEERING UNIVERSITY OF WISCONSIN MADISON

CS/ECE 252: INTRODUCTION TO COMPUTER ENGINEERING UNIVERSITY OF WISCONSIN MADISON

Binary Numbers. The Basics. Base 10 Number. What is a Number? = Binary Number Example. Binary Number Example

DATA REPRESENTATION. Data Types. Complements. Fixed Point Representations. Floating Point Representations. Other Binary Codes. Error Detection Codes

CMSC 313 Lecture 03 Multiple-byte data big-endian vs little-endian sign extension Multiplication and division Floating point formats Character Codes

Chapter 2 Bits, Data Types, and Operations

Chapter 2 Bits, Data Types, and Operations

Chapter 3. Information Representation

Chapter 2 Number System

ASSIGNMENT 5 TIPS AND TRICKS

Chapter 8. Characters and Strings

The Binary Number System

Number Systems Base r

Oberon Data Types. Matteo Corti. December 5, 2001

Lecture (09) x86 programming 8

Chapter 2 Bits, Data Types, and Operations

plc numbers Encoded values; BCD and ASCII Error detection; parity, gray code and checksums

Number Systems for Computers. Outline of Introduction. Binary, Octal and Hexadecimal numbers. Issues for Binary Representation of Numbers

Experiment 3. TITLE Optional: Write here the Title of your program.model SMALL This directive defines the memory model used in the program.

Positional Number System

UNIT 2 NUMBER SYSTEM AND PROGRAMMING LANGUAGES

Introduction to Decision Structures. Boolean & If Statements. Different Types of Decisions. Boolean Logic. Relational Operators

Review. Single Pixel Filters. Spatial Filters. Image Processing Applications. Thresholding Posterize Histogram Equalization Negative Sepia Grayscale

Source coding and compression

Data Representa5on. CSC 2400: Computer Systems. What kinds of data do we need to represent?

Exercises Software Development I. 03 Data Representation. Data types, range of values, internal format, literals. October 22nd, 2014

Simple Data Types in C. Alan L. Cox

CMSC 313 COMPUTER ORGANIZATION & ASSEMBLY LANGUAGE PROGRAMMING LECTURE 02, FALL 2012

5/17/2009. Digitizing Discrete Information. Ordering Symbols. Analog vs. Digital

Connecting UniOP to Datalogic Barcode Readers

CSE-1520R Test #1. The exam is closed book, closed notes, and no aids such as calculators, cellphones, etc.

Data Representa5on. CSC 2400: Computer Systems. What kinds of data do we need to represent?

CSE-1520R Test #1. The exam is closed book, closed notes, and no aids such as calculators, cellphones, etc.

Do not start the test until instructed to do so!

Chapter 1. Hardware. Introduction to Computers and Programming. Chapter 1.2

CS341 *** TURN OFF ALL CELLPHONES *** Practice NAME

Do not start the test until instructed to do so!

Fundamental Data Types

void mouseclicked() { // Called when the mouse is pressed and released // at the same mouse position }

1. Character/String Data, Expressions & Intrinsic Functions. Numeric Representation of Non-numeric Values. (CHARACTER Data Type), Part 1

Arrays. Theoretical Part. Contents. Keywords. Programming with Java module 3

Do not start the test until instructed to do so!

Number Systems II MA1S1. Tristan McLoughlin. November 30, 2013

Under the Hood: Data Representation. Computer Science 104 Lecture 2

Hardware. ( Not so hard really )

EE 109 Unit 2. Analog vs. Digital. Analog vs. Digital. Binary Representation Systems ANALOG VS. DIGITAL

EXPERIMENT 8: Introduction to Universal Serial Asynchronous Receive Transmit (USART)

2a. Codes and number systems (continued) How to get the binary representation of an integer: special case of application of the inverse Horner scheme

Control structures and logic

EE 109 Unit 3. Analog vs. Digital. Analog vs. Digital. Binary Representation Systems ANALOG VS. DIGITAL

EXPERIMENT 7: Introduction to Universal Serial Asynchronous Receive Transmit (USART)

Unit 3. Analog vs. Digital. Analog vs. Digital ANALOG VS. DIGITAL. Binary Representation

Introduction. Chapter 1. Hardware. Introduction. Creators of Software. Hardware. Introduction to Computers and Programming (Fall 2015, CSUS)

CMSC 313 COMPUTER ORGANIZATION & ASSEMBLY LANGUAGE PROGRAMMING LECTURE 02, SPRING 2013

CS 159 Credit Exam. What advice do you have for students who have previously programmed in another language like JAVA or C++?

PureScan - ML1. Configuration Guide. Wireless Linear Imager Wireless Laser scanner - 1 -

User s Manual. Xi3000 Scanner. Table of Contents

6.096 Introduction to C++ January (IAP) 2009

Objectives. Chapter 2: Basic Elements of C++ Introduction. Objectives (cont d.) A C++ Program (cont d.) A C++ Program

Chapter 2: Basic Elements of C++

Chapter 2: Basic Elements of C++ Objectives. Objectives (cont d.) A C++ Program. Introduction

FA269 - DIGITAL MEDIA AND CULTURE

EE 109 Unit 2. Binary Representation Systems

Universal Asynchronous Receiver Transmitter Communication

o Echo the input directly to the output o Put all lower-case letters in upper case o Put the first letter of each word in upper case

Characters Lesson Outline

Programmable #182 Parallel Interface Cash Drawer Manual

Chapter 7. Binary, octal and hexadecimal numbers

3.1. Unit 3. Binary Representation

Xi2000-BT Series Configuration Guide

Configuration Manual PULSAR C CCD SCANNER. Table of Contents

CMSC 313 COMPUTER ORGANIZATION & ASSEMBLY LANGUAGE PROGRAMMING LECTURE 02, FALL 2012

The following are the data types used in the C programming language:

Week 1 / Lecture 2 8 March 2017 NWEN 241 C Fundamentals. Alvin Valera. School of Engineering and Computer Science Victoria University of Wellington

4/14/2015. Architecture of the World Wide Web. During this session we will discuss: Structure of the World Wide Web

RS-232 Control of the Advantage EQ281/8, EQ282/8 and Advantage SMS200

CPSC 301: Computing in the Life Sciences Lecture Notes 16: Data Representation

RS-232 Digital Relay I/O

Table of Contents Sleep Settings How to Configure the Scanner. 7 Chapter 2 System Setup

This is great when speed is important and relatively few words are necessary, but Max would be a terrible language for writing a text editor.

User s Manual. Addendum to. Ranger Wedge Interface. Part No. 25-WEDGE-06A Ver. April 1999

APPENDIX A : KEYWORDS... 2 APPENDIX B : OPERATORS... 3 APPENDIX C : OPERATOR PRECEDENCE... 4 APPENDIX D : ESCAPE SEQUENCES... 5

n NOPn Unary no operation trap U aaa NOP Nonunary no operation trap i

Objects. Theoretical Part. Contents. Keywords. Programming with Java Module 5. 1 Module Overview 3

8.2 User Defined Protocol Communication

Midterm CSE 131 Winter 2012

CMPSC 311- Introduction to Systems Programming Module: Strings

FD-011WU. 2D Barcode Reader User Guide V1.6CC

Transcription:

Programming with Python Module 1 Variables and data types Theoretical part Contents 1 Module overview 4 2 Writing computer programs 4 2.1 Computer programs consist of data and instructions......... 4 2.2 Programs have to be translated..................... 5 2.2.1 Writing and executing Python programs............ 5 2.2.2 Comments.............................. 6 3 Representation of numbers and characters in the computer 6 3.1 Binary system................................ 6 3.2 Representation of numbers in the binary system........... 6 3.3 Representation of characters in binary system............. 7 4 Variables and data types 7 4.1 Defining variables.............................. 7 4.2 Data types of variables........................... 9 4.3 Data type of variables in Phyton..................... 10 5 Operations and expressions 11 5.1 Operators.................................. 11 5.2 Expressions................................. 12 6 Input and output of data 12 6.1 Output in the Python-console....................... 12

6.2 Input via the keyboard........................... 13 Keywords Programming language Algorithm Program Editor Source code Syntax Semantic Compiler Bit/Byte Comments Binary system ASCII code Variable Data type Integer Float String Value assignment Arithmetic operators Screen input and output Authors: Lukas Fässler, Dennis Komm, David Sichau Translation: Christa Furrer E-Mail: et@ethz.ch Date: 18 July 2018 Version: 1.1 Hash: d2eb005 The authors try the best to provide an error free work, however there still might be some errors. The Authors are thankful for your feedback and suggestions. This work is licensed under a Creative Commons Attribution-NonCommercial-NoDerivatives 4.0 International License. 2

To view a copy of this license, visit http://creativecommons.org/licenses/by-nc-nd/4.0/ 3

1 Module overview The development of the computer has made it possible that machines perform computing work. However, the computer on its own is not able to solve any problems: we have to prescribe an approach (processing rules). This approach is relayed to the computer in the form of a program. This happens in a special language: the programming language. Processing rules for solving a task are called algorithms. We demand that an algorithm terminates its task and therefore does not run endlessly if it is executed and that it generates a useful output for each input. Hence, algorithm is an abstract term. We can understand, for example, a cake recipe or directions given to a tourist as an algorithm. Here, however, we only consider algorithms that have been formulated in a concrete way in a programming language. 2 Writing computer programs If two people communicate, spoken words are accompanied, for example, by facial expressions and gestures. The answer fine to the question how are you? can be interpreted in different ways depending on the intonation, for example. People have an intellect that enables them to interpret a dialog and to put it in a context. Computers do not have this capability. We have to express ourselves very precisely to communicate with a computer. The computer doesn t know what we actually meant if we expressed ourselves in the wrong way. This was a very laborious work for the first computers because the language a computer understands is not intuitive at all for people. Therefore, so-called standard languages that are closer to our natural language have been developed. To implement algorithms as a computer program, you will use such a language in this course: Python. 2.1 Computer programs consist of data and instructions A computer program is mainly a selection of data and a sequence of instructions which fulfill a certain function when they are executed. Each instruction performs a certain operation, for example a calculation. For a better understanding, you can imagine a cooking recipe as mentioned above. It first contains the quantities of the ingredients (data) and then the order of the steps (instructions) which have to be executed to cook a certain meal. The basic structure of a recipe is almost always the same: first the ingredients then the individual steps. A computer program is very similar to this. Each program also follows a basic pattern. However, we do not speak of a pattern but of the syntax of a programming language, i.e. of the rules that have to be adhered to for the structure of a program. As already mentioned, there are some essential differences to the steps in 4

a recipe. The instructions have to be formulated precisely. We will not find instructions such as season to taste here since the computer is not able to interpret them unambiguously. The following line shows a very simple example for the programming language Python: print ("Welcome to programming with Python.") Our program contains in this example: an instruction (the print command print()) the data (in this case the text Welcome to programming with Python). When executing this program now, the following line is output on the screen: Welcome to programming with Python. What the program executes, i.e. its meaning, is called semantics of the program. 2.2 Programs have to be translated Programs in a programming language such as Python are readable and understandable for humans. As already mentioned, a computer doesn t understand them directly but only after a conversion into instructions for its processor. They are not only difficult to understand for us, but also significantly simpler than the commands of a program in a high-level language as Python. This means that a single instruction of a program results in a sequence of several processor instructions. Therefore, the commands of the program have to be translated into instructions of the computer so that the computer is able to execute our program. Special computer programs (so-called compilers) are required to translate programs from a programming language into a sequence of processor instructions. Hence, the process of translating is called compiling. 2.2.1 Writing and executing Python programs Programs are stored in files. We need an editor to be able to edit and store these files. There are a wide range of editors and development environments for Python. After writing a program, the source code is stored. Files containing Python source code have the extension.py. In the next step, the compiler translates the source code into a format called bytecode which is not visible for the user. It gets the extension.pyc. 5

2.2.2 Comments Comments are reading aids for humans. They serve to document the source code. Comments are skipped and completely ignored by the compiler. Any number of comments can be entered. It is necessary to specify where a comment begins and where it ends. In Python, a hash sign (#) at the beginning of the line is used to mark a comment. In the following example, the lines 1, 3 and 4 are ignored by the compiler, but the 2nd line is translated. # This is a comment and it is ignored by the compiler. print("this line is translated by the compiler") # This is also a comment and it is ignored by # the compiler. 3 Representation of numbers and characters in the computer Data which differ in type (e.g. characters, numbers or logical data) are processed in a program. Digital data are always represented by digits. To understand the representation of characters, numbers and texts in the computer, we have to understand the binary system. 3.1 Binary system All computers represent informations in the binary system. It only knows two digits: 0 and 1 (in contrast to the decimal system with digits between 0 and 9). Such a digit is called a bit (abbreviation for binary digit). A bit indicates the smallest storable value in a computer. 8 bits are bundled together into a byte. Therefore, a byte can store 2 8 = 256 different sequences of 8 bit each. 3.2 Representation of numbers in the binary system Consider the number 91 which is represented binarily with 8 bits as 01011011 (see table 1). Therefore, we talk of the binary representation of 91 (and not of the decimal representation which is easier to read) in this context. An 8-bit number, as in our example, can store values between 00000000 (0 in the decimal system) and 11111111 (255 in the decimal system). To convert from the 6

Bit 8 7 6 5 4 3 2 1 Binary value 0 1 0 1 1 0 1 1 Intrinsic value 2 7 = 128 2 6 = 64 2 5 = 32 2 4 = 16 2 3 = 8 2 2 = 4 2 1 = 2 2 0 = 1 Decimal value 0 64 0 16 8 0 2 1 = 91 Table 1: Binary representation of the decimal number 91. Details see text. binary to the decimal value, we multiply the binary value with the value of the bit (0 or 1) for each bit and add them up. If the number to be represented is larger than 255, we have to provide a larger storage area than 8 bits. 3.3 Representation of characters in binary system For the representation of characters in the computer, the so-called ASCII code was developed. ASCII stands for American Standard Code for Information Interchange. 128 different characters (2 7 ) can be represented with the help of 7-bit ASCII code or, vice versa, each character is assigned a bit pattern of 7 bits (see table 2). The characters largely correspond to those of the computer keyboard. The ASCII code was extended to 8 bits which allows the representation of 256 characters (2 8 ). The ASCII table also contains non-representable characters (such as the character representing a line break). The most important of these are shown in table 3. 4 Variables and data types You can imagine variables as a container for storing values. Variables have names by which they can be invoked and they store a concrete value. The value of the variables can be changed during the execution of the program (it can vary, hence the name). 4.1 Defining variables If you require a variable with the name mynumber you want to store, for example, the value 4 in, you achieve this in Python by using the following command. mynumber = 4 7

0-31 31-63 64-95 96-127 Dec Characters Dec Characters Dec Characters Dec Characters 0 NUL 32 SP 64 @ 96 1 SOH 33! 65 A 97 a 2 STX 34 " 66 B 98 b 3 ETX 35 # 67 C 99 c 4 EOT 36 $ 68 D 100 d 5 ENQ 37 % 69 E 101 e 6 ACK 38 & 70 F 102 f 7 BEL 39 71 G 103 g 8 BS 40 ( 72 H 104 h 9 HT 41 ) 73 I 105 i 10 LF 42 * 74 J 106 j 11 VT 43 + 75 K 107 k 12 FF 44, 76 L 108 l 13 CR 45-77 M 109 m 14 SO 46. 78 N 110 n 15 SI 47 / 79 O 111 o 16 DLE 48 0 80 P 112 p 17 DC1 49 1 81 Q 113 q 18 DC2 50 2 82 R 114 r 19 DC3 51 3 83 S 115 s 20 DC4 52 4 84 T 116 t 21 NAK 53 5 85 U 117 u 22 SYN 54 6 86 V 118 v 23 ETB 55 7 87 W 119 w 24 CAN 56 8 88 X 120 x 25 EM 57 9 89 Y 121 y 26 SUB 58 : 90 Z 122 z 27 ESC 59 ; 91 [ 123 { 28 FS 60 < 92 \ 124 29 GS 61 = 93 ] 125 } 30 RS 62 > 94 ˆ 126 ~ 31 US 63? 95 _ 127 DEL Table 2: ASCII table 8

Dec Characters Meaning 8 BS Backspace. Deleting the character to the left 10 NL New Line. Beginning a new line 32 SP Space. 127 DEL Delete. Deleting the character to the right Table 3: Non-representable characters of the ASCII table Storing values is done with the assignment operator. In Python, as in many programming languages, the equal sign (=) is used for it. Thereby, the value of the expression to the right of the assignment operator is assigned to the variable on the left-hand side. The process of assigning a value to the variable for the first time is called initialization of the variable. As mentioned previously, the value of a variable can change during the execution of the program. Let s have a look at the following example: First, we store the value 4 in the variable mynumber and then we overwrite it with the value 6 in a further line. mynumber = 4 # Value of mynumber is 4 mynumber = 6 # Value of mynumber is 6 4.2 Data types of variables The data type indicates which data can be stored in a variable. Programming languages have predefined data types which differ in the way they interpret the stored data and in their size. Most programming languages distinguish the following data types. Type for numerical values Type for character values Type for truth values Table 4 provides an overview of the most important data types which occur in many programming languages. 9

Type Description Example boolean Truth value True or False int Integer 108, -455 float Floating-point number 8.988, -4.69 string character string "Monday", "7.9" Table 4: The most important data types in Python 4.3 Data type of variables in Phyton Unlike in many other programming languages, the data type of a variable does not have to be defined at the start. This means, you only need to name a variable (as described above). The type of the variable is later defined automatically based on the type of the value during the run time. The following example shows a variable a, the data type of which is defined as integer, a variable b, the data type of which is defined as float, and a variable c, the data type of which is defined as string. a = 4 # a is defined as integer b = 0.1 # b is defined as float c = "Monday" # c is defined as string When defining string variables, the value has to be enclosed in double quotes ("). Several strings can be concatenated by using a plus (+). For example, a new text that is stored in the variable d results from several individual parts. d = "Hello, " + " these " + "are " + "several " + "words." Although the data types are determined automatically in Python, it can nevertheless be useful to know the data type for some tasks. By using the following command, the data type of a variable d can be displayed. type(d) 10

The data type of variables can also change during the execution of the program. In the following example, the variable a initially has the type integer but then changes to the type float. a = 1 # a is defined as integer a = a + 0.1 # a is defined as float The data type of a variable can be changed explicitly. In the following example, the data type of a variable a is first defined as float and then changed to integer. a = 1.9 # a is defined as float a = int(a) # a is defined as integer. The value is 1 now. 5 Operations and expressions 5.1 Operators To perform calculations in a program, various arithmetic operators are available (see table 5). Operator Expression Description Provides Example + a + b Addition Sum 5 + 2 = 7 - a - b Subtraction Difference 5-2 = 3 a b Multiplication Product 5 2 = 10 / a / b Division Quotient 5 / 2 = 2.5 % a % b Modulo Integer remainder of a division 5 % 2 = 1 Table 5: Arithmetic operators in Python Further operators (logical and relational operators) are introduced in module 2. 11

5.2 Expressions Expressions in programming language are part of the smallest executable units of a program. They are process specifications that can consist of variables, constants and operators and lead to a result. Variables and constants that are concatenated with an operator are called operands. An expression can also consist of an individual variable. The following example shows an expression consisting of a variable i, an operator + and a constant 5. Therefore, i and 5 are operands. i + 5 The result of the expression can again be stored in a variable. In the following example, we use the variable i. Therefore, the previous value of i is overwritten. i = i + 5 The order in which the expressions are executed can be influenced by the choice of the operator and by using brackets. For this, the mathematical rules as we learnt them at school apply, i.e. first brackets and then multiplication/division before addition/subtraction. Example: 5 * (2 + 10) The brackets make sure that the addition is executed before the multiplication. 6 Input and output of data It is often desirable that a user of the program can interact with the program. For this purpose, almost every programming language has special input and output functions. This means that the user can enter something (for example via the keyboard) or that the program performs an output (for example the result of a calculation or a text). 6.1 Output in the Python-console By the following function, which we have already used above, we can output the text "The program ends here." in the console: 12

print("the program ends here.") However, we may sometimes not want to output a given text, but, for example, the result of a calculation stored in a variable (e.g. myresult). The following function outputs the value of the variable myresult in the console: print(myresultat) Variable values and text can be connected with a comma (,) in Python. print(myresult, "was calculated.") 6.2 Input via the keyboard Most programs require an input at some stage. This can be done in different ways (data base, internet, etc.). A common form of input is via the keyboard of the user. A user input via the keyboard can be made in Python by using the function input(). The following command stops the program execution until the user makes an input and confirms it with the return key. a = (input("what s your name?")) First, the string which is enclosed by brackets is output so that the user knows what he or she has to enter. The function input() always provides a string which can be stored in a variable. If another data type is desired for the keyboard input, it must be changed explicitly. b = int(input("how much do you want? ")) # Data type of b shall be integer c = float(input("what does the piece cost? ")) # Data type of c shall be float 13