CI6010a-Introduction To Programming Using Python

3y ago
32 Views
2 Downloads
1.82 MB
40 Pages
Last View : 6d ago
Last Download : 3m ago
Upload by : Mya Leung
Transcription

INTRODUCTION TO PROGRAMMINGUSING PYTHONDr Norbert G GyengeResearch IT, IT Services, University of Sheffield2020

http://rcg.group.shef.ac.uk/courses/python

Course Outline:-Data TypesVariableOperatorsConditional StatementsFor and While Loops

*DATA TYPES Numbers:-Integer: Whole number. ℤ { - 2, -1, 0, 1, 2, }100-Float: Representation of real numbers. ℝ {3.12, -9.12154 }6.62-Complex: Contains a "real" part and an "imaginary" part. ℂ {2 5i, }3 4jString:- A sequence of characters between single or double quotation marks. “Hello World!“‘99 bottles of beer‘“It’s Python!“‘This is a “Quote”‘Boolean:- A boolean expression evaluates to one of two states true or false.* List and Dictionary to be discussed later.TrueFalse

VARIABLESPython variables do not need explicit declaration to reserve memory space.The declaration happens automatically when you assign a value to a variable.counter 100pi 3.14name “David”num counterAn integer assignment.A floating point number.A string with double or single quotation marks.Using another variable to define a new one.Variables can be re-assigned / deleted after you have declared them.iteration 100iteration 99del iterationNew integer assignment.100 stays in the memory as junk.Delete a variable.

*OPERATORSAn operator in a programming language is asymbol that tells the compiler or interpreterto perform specific mathematical, relational orlogical operation and produce final result. Arithmetic OperatorsComparison OperatorsAssignment OperatorsLogical OperatorsMembership Operators* Limited list. In total there are 7 operator families. Bitwise and Identity Operators are excluded.

ARITHMETIC OPERATORSAssume variable x holds 10 and variable y holds 3, thenOperator */%**//10 3 ulusExponentiationFloor divisionExamplex yx-yx*yx/yx%yx ** yx // yResults (x 10, y 3)137303.333110003

ASSIGNMENT OPERATORSAn assignment operator is used to assign values to a variable.Operator - * / % // ** x 5y 10c x yExamplex 5x 3x - 3x * 3x / 3x % 3x // 3x ** 3Same Asx 5x x 3x x-3x x*3x x/3x x%3x x // 3x x ** 3

COMPARISON OPERATORSThese operators compare the values on either sides of them and decide the relation among them.Operator ! 10 3 TrueNameEqualNot equalGreater thanLess thanGreater than or equal toLess than or equal toExamplex yx ! yx yx yx yx yResults (x 10, y 3)FalseTrueTrueFalseTrueFalse

LOGICAL OPERATORSAssume variable x holds 10, thenOperatorDescriptionExampleResultandReturns True if bothstatements are trueReturns True if one of thestatements is trueReverse the result, returnsFalse if the result is true.x 20 and x 5Falsex 20 or x 5Trueornotnot(False and True or True) Falsenot(x 20 and x 5) True

OPERATOR PRECEDENCEWhen two operators share an operand, theoperator with the higher precedence goes first.Arithmetic Comparison Logical Note that comparisons all have the sameprecedence and have a left-to-right chainingfeature.Arithmetic operators follow thesame precedence rules as in mathematics.5 5 5 and False False5 5 5 and True True3 ! 2 and (4 / 2) 0 True1 * 2 ** 3 * 1 8not(not(True and True)) True3 2 and (8 / 2) 0 False

STANDARD OUTPUTThe print() function prints the specifiedmessage to the screen. The message can be anyPython type (int, float, string, etc ) or variable.print(“Hello World!”) # Printing a stringprint(5 10)# Printing the result of the operator.print(hello, world)# Printing variables in one line

COMMENTSSingle-line comment#This line displays Hello World!print(“Hello World!“)Inline commentprint(“Hello World!“)Multi-line comment‘’’This linedisplaysHello World!’’’print(“Hello World!“)# My first program.

Study DrillDefine two variables as ’a 12’ and ‘b 3’. Print the basic arithmetics ( , -, *, /) of thetwo numbers. Investigate the output. Now change the numbers to 0.1 and 0.2 andstudy your output again.

#Define the variablesa 12b 3#Print the basic arithmetics.print(a b)# Output: 15print(a - b)# Output: 9print(a * b)# Output: 36print(a / b)# Output: 4.0andandandand0.30 04-0.10.020 040.5

ROUNDING ERRORPython cannot accurately represent a floating point number because it uses aspecial format for storing real numbers, called binary floating-point.a 0.1b 0.2print(a b)# Result: 0.30000000000000004a 0.2b 0.3print(a b)# Result: 0.5Example: Fraction to decimal conversion. 10 over 3 is a perfect representation, however 3.333 is inaccurateafter performing the conversion.103.3.333333

STANDARD INPUTReading a new variable from the keyboardcan be done by using the input() function. Bydefault the variable x is defined as a string!new variable input(“string”)# Variables from keyboardx input('Type something here: ')# Display the inputprint(x)

TYPE CONVERSIONSometimes it is necessary to perform conversions between the built-in types by using float() and int() functions.Integer to float:Integer to string:Float to integer:Float to string:String to integer:String to float:test variable 77.00000“7a”“7a”errorerror#String can be anything, even a “number”converted variable int(test variable) #conversion string to integerprint(converted variable) #Print the created variable

Study DrillModify your calculator. Let the user define the input numbers and print the basic arithmetics.

#Define the variablesa input(‘First number? ')b input(‘Next number? ')#Type conversion.a float(a)b float(b)#Print the basic arithmetics.print(a b)print(a - b)print(a * b)print(a / b)

CONDITIONAL STATEMENTS

IF STATEMENTif condition :indentedStatementBlock The condition could be any logical statement. If the condition is true, then do the indentedstatements. If the condition is not true, then skip theindented statements. The body of the if statement is indicated by theindentation.

x 4if x 0:# TRUEprint('Positive')y -4if y 0:# FALSEprint('Positive')x 4y 4if x y:# TRUEprint('Equal')

IF - ELSE EXPRESSIONSif condition:indentedStatementBlock 1else:indentedStatementBlock 2 If the condition is true, then do the indented statements. If the condition is not true, then do the other indented statements.

#Define a numberx 4#Mind the indentationif x 0:print(‘Positive')else:print('Negative')

ELIF STATEMENTx 4y 7if x y:print('X is smaller.')elif x y:print('Y is smaller.')else:print('X is equal to Y.')

NESTED CONDITIONSx 3y 7if x y:print('Y is larger.’)0else:if x 0:print('X is pos.’)else:print('X is neg.')

MULTIPLE CONDITIONSa 3b 5c 2if a 0 or b 0 or c 0:print(‘Positive number(s)!’)else:print(‘All negative number(s) or zero(s).’)if a 0 and b 0 and c 0:print('All positive!')else:print('Negative number(s) or zero(s).’)

Study DrillWrite a program that reads three inputs (angles). The program has tocheck whether the three given angles compose a triangle or not.Requirements:(a) Each of the angles is a positive number and(b) the total of the angles is 180.

#Define the variablesa input(“1st angle? “)b input(“2nd angle? “)c input(“3rd angle? “)#Convert the variablesa float(a)b float(b)c float(c)#Print the basic arithmetics.if a 0 and b 0 and c 0:if a b c 180:print('Possible triangle')else:print('The sum is not equals to 180.')else:print('One of the angle (or more than one) is zero.')

LOOPS

WHILE VS FOR LOOPSDefinite Iteration: For Loops The number of times the designated blockwill be executed is specified explicitly atthe time the loop starts.Loops repeatactions So you don’thave toIndefinite Iteration: While Loops The number of times the loop is executed isn’t specified explicitlyin advance. Rather, the designated block is executed repeatedly aslong as some condition is met.

FOR LOOPSfor LOOP VARIABLE in SEQUENCE:STATEMENTSSEQUENCE: Iterating over a sequence that is either a list, a dictionary, a set of number, astring and so on.LOOP VARIABLE: The name of the loop variable is defined by the programmer. Variablenames such as i, j, iter, row or column are commonly used. The type of the loop variable depends on the sequence.

THE RANGE FUNCTIONrange(6)012345outputrange(0, 6)6012345stopstart outputrange(0, 10, 2)0 1 2 3 4 5 6 7 8 9 10start02468outputstop6stop

FOR LOOPfor i in range(5):print(i)Output01234

Study DrillWrite a program that will ask the user for a message (string) and thenumber of times they want that message displayed. Then output themessage that number of times.

SOLUTION#Define the variablesmsg input('Please write the message here: ')n input('How many times would you like to repeat?: ')#Conversionn int(n)#For loop for printing multiple linesfor i in range(n):print(msg)

WHILE LOOPSwhile condition:STATEMENTS We can execute a set of statements aslong as a condition is true. We generally use this loop when wedon't know beforehand, the number oftimes to iterate.i 1while i 6:print(i)i i 1

Study Drill100Write a program that will calculate x n2 12 22 1002n 1

x 0n 1# While loop towhile n 100:x x (n ** 2)n n 1# Print the sumprint(x)

Python cannot accurately represent a floating point number because it uses a special format for storing real numbers, called binary floating-point. Example: Fraction to decimal conversion. 10 over 3 is a perfect representation, however 3.333 is inaccurate

Related Documents:

work/products (Beading, Candles, Carving, Food Products, Soap, Weaving, etc.) ⃝I understand that if my work contains Indigenous visual representation that it is a reflection of the Indigenous culture of my native region. ⃝To the best of my knowledge, my work/products fall within Craft Council standards and expectations with respect to

About this Programming Manual The PT Programming Manual is designed to serve as a reference to programming the Panasonic Hybrid IP-PBX using a Panasonic proprietary telephone (PT) with display. The PT Programming Manual is divided into the following sections: Section 1, Overview Provides an overview of programming the PBX. Section 2, PT Programming

Programming is the key word here because you make the computer do what you want by programming it. Programming is like putting the soul inside a body. This book intends to teach you the basics of programming using GNU Smalltalk programming language. GNU Smalltalk is an implementation of the Smalltalk-80 programming language and

Object Oriented Programming 7 Purpose of the CoursePurpose of the Course To introduce several programming paradigms including Object-Oriented Programming, Generic Programming, Design Patterns To show how to use these programming schemes with the C programming language to build “good” programs.

Functional programming paradigm History Features and concepts Examples: Lisp ML 3 UMBC Functional Programming The Functional Programming Paradigm is one of the major programming paradigms. FP is a type of declarative programming paradigm Also known as applicative programming and value-oriented

1 1 Programming Paradigms ØImperative Programming – Fortran, C, Pascal ØFunctional Programming – Lisp ØObject Oriented Programming – Simula, C , Smalltalk ØLogic Programming - Prolog 2 Parallel Programming A misconception occurs that parallel

Programming paradigms Structured programming: all programs are seen as composed of control structures Object-oriented programming (OOP): Java, C , C#, Python Functional programming: Clojure, Haskell Logic programming based on formal logic: Prolog, Answer set programming (ASP), Datalog

1 This practice is under the jurisdiction of ASTM Committee C-16 on Thermal Insulation and is the direct responsibility of Subcommittee C16.30 on Thermal Measurements. Current edition approved Jan. 27, 1989. Published May 1989. Originally published as C 680 – 71. Last previous edition C 680 – 82e1. 2 Annual Book of ASTM Standards, Vol 04.06. 3 Annual Book of ASTM Standards, Vol 14.02. 4 .