程序代写 Variables and Data Types

Variables and Data Types
Image credit: https://makeameme.org/meme/data-dataeverywhere
The University of 1

Copyright By PowCoder代写 加微信 powcoder

Quickie: Number Game
– Listencarefully.
– Answerthequestionsinfrontofyou. – Ready?
The University of 2

Variables in Programs
– Before you can use a variable, it must be declared and initialize.
– This is important for static-typed languages e.g. C. Once a variable of
specific type is declared, it cannot be assigned a different data type.
– In dynamically-typed languages e.g. Python, data type is determined at run-time. Programmers can re-assign a variable to a different data type after it is initialized.
The University of 3

Data Types and Objects
– DataTypes
– Asetofvaluesandasetofoperationsdefinedonthosevalues.
– Operatorsarerepresentationofadata-typeoperation.Canbeunary, binary and ternary.
– Primitivetypesarebasicdatatypesthatusesfixedamountofmemory. Examples of these are usually: int, float, char, bool.
– Objectsareblocksofmemorythatcontainrelateddataandassociated
operations for that data.
– OneobjectcancontainmanyotherObjects.Theycanhavecustomised operators defined by the programmer i.e., you define the actions of operators (more in W10).
– InPython,everythingisanObject!
The University of 4

Variables and Data Types in Programs
– Good programmers always:
– Knowthedatatypethattheyareworkingwiththroughouttheprogram. – Knowthescopeofeachvariable.
– Initializethevariablestosomethinguseful.
– Factsweknowsofar:
– Machinecodeisusuallyinbinaryformat.
– Pythonisahigh-levellanguage,closetohumanlanguage.Hasfourbasic data types:
Image credit: https://introcs.cs.princeton.edu/python/12types/
The University of 5

Important: Variable Names
– Must start with a letter.
– Must not have spaces.
– Case sensitive! X and x refers two different variables.
– Avoid reserved keywords – words that have special purpose.
– Name variables to describe purpose of value.
– All CAPS indicate constants e.g. FLAT_RATE
– Good practice to use lowercase with words separated by underscores (_) to improve readability.
– Avoid using variable names that already exist as other objects in Python because they are already attached to existing Python functions e.g. print, int, str.
Your task:
• Read: https://www.python.org/dev/peps/pep-0008/#function-and-variable-names • Reflect: Are the contents on this slide consistent with the recommendations?
The University of 6

Reserved Keywords
False class finally
None continue for
True def from
and del global
as elif if or yield
assert else import pass
break except in raise
– Do not need to memorize.
– Most development environments will highlight these keywords in a different
The University of 7
is return
lambda try
nonlocal while
not with

Practice Exercise
– Whichoftheseidentifiersarevalidvariablenames? • num
• 5th_person • mass_obj2 • \tallest
– GotoEdLessontocheckyouranswer. The University of 8

Type Annotation
– Python does not require you to declare the type of variable during initialization because it a dynamic typed language.
– The type is determine at runtime. However, type annotation can be used to indicate the variable type or type of data that the variable contains.
x: int = 10
– In other languages e.g. C language, you must declare the type during initialization. If the value is different from the variable type, an error will be raised.
The University of 9

Activity: Data IRL
Identify the data type most suitable to represent the following information:
– Blood Group
– Number of cars on the road
– Your current weight
– Price of oranges e.g. $1.50/orange
– Number of siblings
– Name of current Prime Minister of Australia
– Is it raining?
– Do you have an umbrella with you now?
Write Python statements to initialize variables with example of real life values for each information. Go to: Ed Lesson
The University of 10

Reflect: What did we just do?
– Howmanyvariablesareoftypestring? – How many variable are of type Boolean? – Howmanyvariablesareoftypeinteger? – Checkyouranswers:EdLesson
The University of 11

Data Type – float
– Float variables can be initialized using a sequence of digits with decimal points or in scientific notation.
– Arithmetic operators (+, -, *, /) works with float objects too BUT results are stored as float objects due to implicit type casting.
– Typically have 15-17 decimal digits precision.
– Floating-point numbers are approximations of the real-numbers. Be careful when performing comparisons with floating-point numbers.
pi = 3.14159
random_float = 6.02e23
The University of 12

Type Casting
– Conversion between data types.
– Explicit conversion – invoke using function calls. – str()converttotypestr
– int()convertintotypeint
– float()convertintotypefloat
– Implicit conversion – Python does the conversion automatically when appropriate.
– Examplecaseswhereresultsareimplicitlyconvertedtofloat: • Divisionbetweenafloatandint
• Divisionbetweentwoint
• Additionbetweenanintandfloat
The University of 13

Conundrum: int or float?
– Identifytheinformationthatisgoingtobestoredandhowit
changes over time.
– Are they whole numbers or can there be fractional components?
– Accuracy:Integersareexactbutfloating-pointnumbersarenot.
– Range:Ifyouaredealingwithverylargeorsmallnumbers,youhaveto use float – their range is much bigger.
– Isthereanydangerofusingafloatingpointtypeinyour program if only integers are expected?
The University of 14

Expression
– An expression is a combination of literals, variables, and operators that Python evaluates to produce a value.
– Many expressions looks like mathematical formulas:
The University of 15

Activity: Data IRL
– Extend the program to calculate the total amount that you have to pay if you are to buy one orange for each sibling and yourself.
– Display this amount to the terminal and check if the calculation is correct using a digital/physical calculator.
– Goto:EdLesson
The University of 16

Reflect: What did we just do?
– Didyoumanagetocreateanexpressionusingthevariables that you have created?
– Whatdatatypearetheoperandsforeachoperator?
– Whatdatatypeisthenumberoforangesbought?
– Checkyouranswers:EdLesson The University of 17

Activity: Data IRL
– Ifthepriceperorangeisnow$1.30andyouareaskedtobuy 3 oranges. How much is the total amount that you have to pay to buy the oranges?
– Write codes to perform this calculation in your program.
– Once again, display the price to the terminal and check if the
calculation is correct.
– Goto:EdLesson
The University of 18

Reflect: What did we just do?
– Did the program produce the correct answer?
– True/False: Floating points are accurate representations of real
– Checkyouranswers:EdLesson
The University of 19

Data Type – bool
– Two possible values – False (0) and True (1).
– Comparison operators are mixed operators that will result in a Boolean.
– Boolean operators in Python: not, and, or
The University of 20

Truth Table
– All possible inputs and output combinations for each operation can be looked up in the truth table:
The University of 21

Activity: Data IRL
– Write an expression to determine if you will get wet in the rain.
– Save the result of the expression into a variable called is_wet. The variable should contain only two values to represent the state: wet (True) and not wet (False).
– Hint:Isitraining?Doeshehaveanumbrella?
– Goto:EdLesson The University of 22

Truth Table – Example
is_raining
has_umbrella
(Expected)
0 represents False 1 represents True
The University of 23

Reflect: What did we just do?
– WhichBooleanoperatordidyouuse?
– Howdidyouverifythattheexpressioniscorrect?
– Checkyouranswers:EdLesson
The University of 24

Data Type – str
– ObservationsfromLab1:
– Stringsmustbeenclosedwithsingle/doublequotes.
– Backslashcharacterinstringdenotesescapecharactertoindicate characters with special meaning e.g. ‘\\’means backslash.
– Stringconcatenationusing+operator
– Stringrepetitionusing*operator
The University of 25

Data Type – str
– A string of characters only make sense when they are together.
– A string variable contains the memory address that contains all characters.
– Can perform many more operations on string variables using string methods.
– https://docs.python.org/3/library/stdtypes.html#string-methods
– str.format() returns a copy where each replacement field if replace with string value of the corresponding argument.
– str.lower() returns a copy of str converted to all lowercase.
– str.capitalize()returnsacopyofstrwithfirstcharactercapitalize.
– str.upper()returnsacopyofstrconvertedtoalluppercase.
The University of 26

– Writeprogramsthatcontainsvariableswithdifferentdata types and expressions.
– Ourfocusthislecture–integer,floatandbooleans.
– Nextlecture–stringmethodsandgettinginputfromusers.
The University of 27

Self-Study
– Chapter1.2.Sedgewick,R.,Wayne,K.,&Dondero,R.(2015). Introduction to programming in Python: An interdisciplinary approach. Addison- .
The University of 28

程序代写 CS代考 加微信: powcoder QQ: 1823890830 Email: powcoder@163.com