Variable and Data Type I

Similar documents
Variable and Data Type I

ENGR 101 Engineering Design Workshop

Selection Statement ( if )

PROGRAMMING FUNDAMENTALS

CSCE 110 Programming I Basics of Python: Variables, Expressions, Input/Output

Chapter 3 : Informatics Practices. Class XI ( As per CBSE Board) Python Fundamentals. Visit : python.mykvs.in for regular updates

Getting Started with Python

Lecture 27. Lecture 27: Regular Expressions and Python Identifiers

Fundamentals of Programming (Python) Getting Started with Programming

There are two ways to use the python interpreter: interactive mode and script mode. (a) open a terminal shell (terminal emulator in Applications Menu)

Introduction to Computers. Laboratory Manual. Experiment #3. Elementary Programming, II

Python - Variable Types. John R. Woodward

There are two ways to use the python interpreter: interactive mode and script mode. (a) open a terminal shell (terminal emulator in Applications Menu)

Python memento TI-Smart Grids

CHAPTER 2: Introduction to Python COMPUTER PROGRAMMING SKILLS

Variables, expressions and statements

UNIVERSITÀ DI PADOVA. < 2014 March >

\n is used in a string to indicate the newline character. An expression produces data. The simplest expression

CMSC 201 Computer Science I for Majors

CSCE 110 Programming I

Getting Started. Office Hours. CSE 231, Rich Enbody. After class By appointment send an . Michigan State University CSE 231, Fall 2013

BASIC ELEMENTS OF A COMPUTER PROGRAM

Python Input, output and variables

Python Input, output and variables. Lecture 23 COMPSCI111/111G SS 2018

Python Input, output and variables. Lecture 22 COMPSCI111/111G SS 2016

Chapter 1 Summary. Chapter 2 Summary. end of a string, in which case the string can span multiple lines.

Algorithms and Data Structures

Computer Programming, I. Laboratory Manual. Experiment #2. Elementary Programming

Full file at

There are four numeric types: 1. Integers, represented as a 32 bit (or longer) quantity. Digits sequences (possibly) signed are integer literals:

Constants. Variables, Expressions, and Statements. Variables. x = 12.2 y = 14 x = 100. Chapter

C++ Programming: From Problem Analysis to Program Design, Third Edition

PRG PROGRAMMING ESSENTIALS. Lecture 2 Program flow, Conditionals, Loops

Here n is a variable name. The value of that variable is 176.

UNIT - I. Introduction to C Programming. BY A. Vijay Bharath

Introduction to Python

Lab1. Introduction to Python. Lab 4: Selection Statement. Eng. Mai Z. Alyazji

Chapter 2 Writing Simple Programs

PYTHON- AN INNOVATION

Babu Madhav Institute of Information Technology, UTU 2015

DaMPL. Language Reference Manual. Henrique Grando

Variables, Expressions, and Statements

Basic Concepts. Computer Science. Programming history Algorithms Pseudo code. Computer - Science Andrew Case 2

Basic Syntax - First Program 1

Variable and Data Type 2

Variables and Constants

And Parallelism. Parallelism in Prolog. OR Parallelism

Computer Programming : C++

These are reserved words of the C language. For example int, float, if, else, for, while etc.

1. What type of error produces incorrect results but does not prevent the program from running? a. syntax b. logic c. grammatical d.

Programming with Python

Chapter 4 : Informatics Practices. Data Handling. Class XI ( As per CBSE Board) Visit : python.mykvs.in for regular updates

Work relative to other classes

L-System Fractal Generator: Language Reference Manual

Professor: Sana Odeh Lecture 3 Python 3.1 Variables, Primitive Data Types & arithmetic operators

Computer System and programming in C

COLLEGE OF ENGINEERING, NASHIK-4

Python Numbers. Learning Outcomes 9/19/2012. CMSC 201 Fall 2012 Instructor: John Park Lecture Section 01 Discussion Sections 02-08, 16, 17

Introduction to Python, Cplex and Gurobi

>>> * *(25**0.16) *10*(25**0.16)

C++ Basic Elements of COMPUTER PROGRAMMING. Special symbols include: Word symbols. Objectives. Programming. Symbols. Symbols.

Eng. Mohammed S. Abdualal

Full file at C How to Program, 6/e Multiple Choice Test Bank

c) Comments do not cause any machine language object code to be generated. d) Lengthy comments can cause poor execution-time performance.

Lexical Considerations

The Three Rules. Program. What is a Computer Program? 5/30/2018. Interpreted. Your First Program QuickStart 1. Chapter 1

Scripting Languages. Python basics

The float type and more on variables FEB 6 TH 2012

About Variables in Python F E B 1 1 T H

Advanced Algorithms and Computational Models (module A)

D R S H YA M N C H AW D A

Review: Exam 1. Your First C++ Program. Declaration Statements. Tells the compiler. Examples of declaration statements

DEPARTMENT OF MATHS, MJ COLLEGE

Algorithms and Programming I. Lecture#12 Spring 2015

Course Outline Introduction to C-Programming

Python The way of a program. Srinidhi H Asst Professor Dept of CSE, MSRIT

Jython. secondary. memory

Groups of two-state devices are used to represent data in a computer. In general, we say the states are either: high/low, on/off, 1/0,...

06/11/2014. Subjects. CS Applied Robotics Lab Gerardo Carmona :: makeroboticsprojects.com June / ) Beginning with Python

Built-in Types of Data

C/C++ Programming for Engineers: Working with Integer Variables

Introduction to Python

Unit-II Programming and Problem Solving (BE1/4 CSE-2)

Introduction to Informatics

Basic Elements of C. Staff Incharge: S.Sasirekha

UNIT- 3 Introduction to C++

Features of C. Portable Procedural / Modular Structured Language Statically typed Middle level language

LCSL Reference Manual

Tokens, Expressions and Control Structures

MICROPROCESSOR SYSTEMS INTRODUCTION TO PYTHON

Introduction to Python Programming

DECLARATIONS. Character Set, Keywords, Identifiers, Constants, Variables. Designed by Parul Khurana, LIECA.

Hello, World and Variables

CSc 10200! Introduction to Computing. Lecture 2-3 Edgardo Molina Fall 2013 City College of New York

Python for ArcGIS. Lab 1.

egrapher Language Reference Manual

Python. Objects. Geog 271 Geographic Data Analysis Fall 2010

Lexical Considerations

CSC Web Programming. Introduction to JavaScript

STSCI Python Introduction. Class URL

Transcription:

The Islamic University of Gaza Faculty of Engineering Dept. of Computer Engineering Intro. To Computers (LNGG 1003) Lab 2 Variable and Data Type I Eng. Ibraheem Lubbad February 18, 2017

Variable is reserved a location in memory to store values, based on the data type of a variable, the interpreter allocates memory and decides what can be stored in the reserved memory. Therefore, by assigning different data types to variables, you can store integers, decimals, or characters in these variables. Assigning Values to Variables Python variables do not need explicit declaration to reserve memory space. The declaration happens automatically when you assign a value to a variable. Multiple Assignment: Python allows you to assign a single value to several variables simultaneously. For example: Example 1: a = b = c = 1 Here, an integer object is created with the value 1, and all three variables are assigned to the same memory location. print id(a) print id(b) print id(c) You can also assign multiple values to multiple variables. For example: Example 2: a, b, c = 1, 2, "IUG" Identifiers are the names that identify the elements such as classes, methods, and variables in a program, all identifiers must obey the following rules: Identifiers must contain at least one character. The first character must be an alphabetic letter (upper or lower case) or the underscore (_) The remaining characters (if any) may be alphabetic characters (upper or lower case), the underscore, or a digit No other characters (including spaces) are permitted in identifiers. A reserved word (Python Keywords) cannot be used as an identifier. and del from None try as elif global nonlocal True assert else if not while break except import or with class False in pass yield continue finally is raise def for lambda return Python keywords Id (): identity of the location of the object in memory.

Standard Data Types: Python has various standard data types that are used to define the operations possible on them and the storage method for each of them. Python has 5 standard data types: Numbers String List Tuple Dictionary *In this lab we will take just about Numbers and String Python Numbers: Number data types store numeric values. Number objects are created when you assign a value to them. For example: Example 3 var1 = 10 var2 = 1.5 var3 = 2.5-1j Python supports four different numerical types: int (signed integers) long (long integers) float (floating point real values) complex (complex numbers) int long float complex 10 51924361L 15.20 3.14j -786 0xDEFABCECBDAECBFBAEl 32.3+e18 4.53e-7j Python displays long integers with a lowercase l or an uppercase L. A complex number consists of an ordered pair of real floating-point numbers denoted by x + yj, where x is the real part and b is the imaginary part of the complex number.

Python Arithmetic Operators: Assume variable a holds 2 and variable b holds 5, then: Operator Example + Addition a + b = 7 - Subtraction a b = -3 * Multiplication a * b = 10 / Division b / a = 2 % Modulus b % a = 1 ** Exponent a**b =32 // Floor Division 9//2 = 4 and 9.0//2.0 = 4.0 but 9/2 = 4 and 9.0/2.0 = 4.5 Python Assignment Operators: Operator Example = Assign c = a + b assigns value of a + b into c += Add AND Assign c += a is equivalent to c = c + a -= Subtract AND Assign c -= a is equivalent to c = c - a *= Multiply AND Assign c *= a is equivalent to c = c * a /= Divide AND Assign c /= a is equivalent to c = c / a %= Modulus AND Assign c %= a is equivalent to c = c % a **= Exponent AND Assign c **= a is equivalent to c = c ** a //= Floor Division Assign c //= a is equivalent to c = c // a

Example 4: Example 4: Assignment_Operators.py a=2 b=3 c=0 print "a=",a," b=",b, " c=", c c = a + b print "c = a + b, Value of c is ", c c += a print "c += a c *= a print "c *= a c /= a print "c /= a, Value of c is ", c, Value of c is ", c, Value of c is ", c c = 3 c %= a print "c = 3,c %= a, Value of c is ", c c **= a print "c **= a c //= a print "c //= a, Value of c is ", c, Value of c is ", c Output of Example 4 (Assignment_Operators.py): ) shows: Comments: text contained within comments is ignored by the Python interpreter. The # symbol begins comment in the source code. The comment is in effect until the end of the line of code:

Python Strings: Strings in Python are identified as a contiguous set of characters represented in the quotation marks either pairs of single or double quotes. Subsets of strings can be taken using the slice operator ([ ] and [:]) with indexes starting at 0 in the beginning of the string and working their way from -1 at the end So ([-1] represent last index). The plus (+) sign is the string concatenation operator. The asterisk (*) is the repetition operator. For example: Example 5: String_Python.py str = 'Python Lab ' print str # Prints complete string print str[0] # Prints first character of the string print str[2: 5] # Prints characters starting from 3rd to 5th print str[2:] # Prints string starting from 3rd character print str * 2 # Prints string two times print str + "Exam" # Prints concatenated string print "length str ",len(str) Output of Example 5 (String_Python.py): Conversion functions: int() : convert string containing an integer number to an integer float() :convert string containing a floating point number to a floating point number str():convert number to string. a = "34" a = "3.4" print "data type a ",type(a) print "data type a ",type(a) x = int (a) x = float (a) print "data type x ",type(x) print "data type x ",type(x) Output:

User Input: The print function enables a Python program to display textual information to the user. Programs may use the input function to obtain information from the user. For example: input function assign entered value to x x = input () Examples: Example 6: usinginput.py x = input ("Please enter your name: ") print "Text entered: ", x print " Type: ", type(x) Output of Example 6 (String_Python.py): Example 7: usinginput.py x = input ("Please enter an integer value: ") y = input("please enter an integer value: ") print x, ' +', y, ' =', x + y Output of Example 7 (usinginput.py):

Formatted Output: Use the modulo operator "%" to perform string formatting, by convert various class types (like int, float and so on) into a formatted string. The following example show how the string modulo operator ( %) works: print "Units : %3d Price per unit :%5.2f"%(250,32.056)) Output: String modulo operator The general syntax for a format is: %[flags][width][.precision]type Conversion d, i e, E f s o X, X Meaning Signed integer decimal. Floating point exponential format Floating point decimal format. String (converts any python object using str()). Unsigned octal. Unsigned hexadecimal The following examples show some cases of the conversion rules from the table above:

Flag Meaning # Used with o, x or X specifies the value is preceded with 0, 0o, 0O, 0x or 0X respectively. 0 The conversion result will be zero padded for numeric values. - The converted value is left adjusted + A sign character ("+" or "-") will precede the conversion (overrides a "space" flag). Work lab: Write program that converts a Fahrenheit degree to Celsius using the formula Celsius = 5 (fahrenheit 32) 9 Example 8: Convert Fahrenheit into Celsius fahrenheit= input("enter a degree in Fahrenheit:") Celsius=(5.0/9)*(fahrenheit-32) print "Fahrenheit", fahrenheit, " is ", Celsius, " in Celsius" Output of Example 8:

Exercises: 1) What happens if you attempt to use a variable within a program, and that variable has not been assigned a value? 2) Classify each of the following as either a legal or illegal Python identifier: a) Salim b) If c) 2x d) -4 e) sum_total f) sumtotal g) sum-total h) sum total i) public j) $16 k) _4 l) m) a27834 n) wilma s 3) Write an application to convert centimeters (input) to feet and inches (output). 1 inch= 2.54 cm 1 foot =30.48 cm 4) Write a Python program that split up a given number of seconds to hours, minutes, and seconds For example: If the user enters 10000 seconds, the program prints 2 hr, 46 min, 40 sec.