Numeric Expressions, Data type, Type Conversions

damjaeng-i·2022년 7월 31일
0

2022 PY4E

목록 보기
6/18
post-thumbnail

Numeric Expressions

  • Becuase of the lack of mathematical symbols on computer keyboards - we use “computer-speak” to express the classic math operations
  • Asterisk is multiplication
  • Exponentiation (raise to a power) looks different than in math
OperatorOperation
+Addition
-Subtraction
*Multiplication
/Division
**Power
%Remainder

Order of Evaluation

  • When we string operators together - Python must know which one to do first
  • This is called operator precedence
  • Which operator takes precedence over the others?

Parenthesis → Power → Multiplication → Addition → Left to Right

Operator Precedence

  • Remember the rules top to bottom
  • When writing code - use parentheses
  • When writing code - keep mathematical expressions simple enough that they are easy to understand
  • Break long series of mathematical operations up to make them more clear

What does “Type” Mean?

  • In Python variables, literals, and constants have a “type”
  • Python knows the difference between an integer number and a string
  • For example “+” means “addition” if something is a number and “concatenate” if something is a string
>>> ddd = 1 + 4
>>> print(ddd)
5
>>> eee = 'hello ' + 'there'
>>> print(eee)
hello there

Type Matters

  • Python knows that “type” everything is
  • Some operations are prohibited
  • You cannot “add 1” to a string
  • We can ask Python what type something is by using the type() function

Type Conversions

  • When you put an integer and floating point in an expression, the integer is implicitly converted to a float
  • You can control this with the built-in functions int() and float()
>>> print(float(99) + 100)
199.0
>>> i = 42
>>> type(i)
<class 'int'>
>>> f = float(i)
>>> print(f)
42.0
>>> type(f)
<class 'float'>

Integer Division

Integer division produces a floating point result

>>> print(10/2)
5.0
>>> print(9/2)
4.5

String conversions

  • You can also use int() and float() to convert between strings and integers
  • You will get an error if the string does not contain numeric characters

User Input

  • We can instruct Python to pause and read data from the user using the input() function
  • The input() function returns a string
nam = input('Who are you? ')
print('Welcome', nam)

Converting User Input

  • If we want to read a number from the user, we must convert it from a string to a number using a type conversiong function
  • Later we will deal with bad input data
inp = input('Europe floor?')
usf = int(inp) + 1
print('US floor', usf)

Comments in Python

  • Anything after a # is ignored by Python
  • Why comment?
  1. Describe what is going to happen in a sequence of code
  2. Document who wrote the code or other ancillary information
  3. Turn off a ling of code - perhaps temporarily
profile
목표 : 부지런한 개발자

0개의 댓글