Back

Python Chrestomathics

Ahead


 

Part 6 — Some other built-in functions

Some more additions — For your programming toolbox — type, id, round, escape

keyboard     id badge     circle     escaping

Section 6.1: Functions type() and id()

Identifier Type Identity
distance integer #459720864
hours integer #459721184
speed decimal #459726944

# get variable values

reply = input( "Enter integer and decimal: " )

n, x = reply.split()

n = int( n )

x = float( x )

print()

# display variable characteristics

print( "reply:", type( reply ), id( reply ) )

print( "n:", type( n ), id( n ) )

print( "x:", type( x ), id( x ) )

Enter integer and decimal: 1112 2.5

reply: <class 'str'> 140191214505136

n: <class 'int'> 140191214778256

x: <class 'float'> 140191214778448

Enter integer and decimal: 1112 2.5

reply: <class 'str'> 140162385530032

n: <class 'int'> 140162385803152

x: <class 'float'> 140162385803344



Section 6.2: Function round()

# get input and convert to decimal

reply = input( "Enter number: " )

number = float( reply )

# compute eight versions of number

number6 = round( number, 6 ) # rounds to six places after the decimal

number5 = round( number, 5 ) # rounds to five places after the decimal

number4 = round( number, 4 ) # rounds to four places after the decimal

number3 = round( number, 3 ) # rounds to three places after the decimal

number2 = round( number, 2 ) # rounds to two places after the decimal

number1 = round( number, 1 ) # rounds to one place after the decimal

number0 = round( number, 0 ) # rounds to zero places after the decimal

  # (produces a decimal)

rounded = round( number ) # rounds to an integer

Enter number: 3.1415926

number: 3.1415926

round( number, 6 ): 3.141593

round( number, 5 ): 3.14159

round( number, 4 ): 3.1416

round( number, 3 ): 3.142

round( number, 2 ): 3.14

round( number, 1 ): 3.1

round( number, 0 ): 3.0

round( number ): 3

Enter number: 2.7182818

number: 2.7182818

round( number, 6 ): 2.718282

round( number, 5 ): 2.71828

round( number, 4 ): 2.7183

round( number, 3 ): 2.718

round( number, 2 ): 2.72

round( number, 1 ): 2.7

round( number, 0 ): 3.0

round( number ): 3



Section 6.3: Escape sequences

Escape sequence Meaning
\\ Backslash (\)
\" Double quote (")
\' Single quote (')
\t Tab
\n Newline

a = "x\ty\tz"

b = "Hello\nGoodbye"

c = "They said \"How are you\""

x y z

Hello

Goodbye

They said "How are you"


Section 6.4: What’s next


Back

Python Chrestomathics

Ahead

 


© Jim Cohoon. For now, all rights reserved.