Python 3

home

Introduction to Python

davidbpython.com




Built-In Functions

built-in functions

Built-in functions activate functionality when they are called.


aa = 'hello'        # str, 'hello'

bb = len(aa)        # pass string object aa as an argument to function len(),
                    # which returns an integer object as a return value.

print(bb)            # int, 5





len() function

The len() function takes a string argument and returns an integer -- the length of (number of characters in) the string.


varx = 'hello, world!'

vary = len(varx)        # 13




round() function

The round() function takes a float argument and returns another float, rounded to the specified decimal place.


aa = 5.9583

bb = round(aa, 2)   # 5.96

cc = round(aa)      # 6





float precision and the round() function

Some floating-point operations will result in a number with a small remainder:

x = 0.1 + 0.2
print(x)          # 0.30000000000000004  (should be 0.3?)

y = 0.1 + 0.1 + 0.1 - 0.3
print(y)               # 5.551115123125783e-17  (should be 0.0?)

The solution is to round any result

x = 0.1 + 0.2     # 0.30000000000000004

z = round(x, 1)
print(z)          # 0.3




input() function

This function allows us to enter data into the program through the keyboard.


cc = input('enter name:  ')    # program pauses!  Now the user types something

print(cc)                      # [a string, whatever the user typed]





exit() function: terminate the program

The exit() function terminates execution immediately. An optional string argument can be passed as an error message.


aa = input('to quit, press "q" ')
if aa == 'q':
    exit(0)                           # 0 indicates a successful termination (no error)

if aa == '':                          # if user typed nothing and hit [Return]

    exit('error:  input required')    # string argument passed to exit()
                                      # indicates an error led to termination

Note: the above examples make use of if, which we will cover in a later lesson.





exit() to manipulate execution during development

This function can be used as a temporary stop to the program if we'd like to isolate some statements.


We can also use exit() to simply stop program execution in order to debug:

aa = '55'
bb = float(aa)
print('type of bb is:')
print((type(bb)))
exit()                  # we inserted this to stop the code
                        # from continuing; we'll remove it later

cc = bb * 2             # because of exit() above, this code
                        # will not be reached




int() "conversion" function

This function converts an appropriate value to the int type.


# str -> int
aa = '55'
bb = int(aa)         # 55 (an int)
print(type(bb))      # <class 'int'>

# float -> int
var = 5.95
var2 = int(var)      # 5:  the rest is lopped off (not rounded)


The conversion functions are named after their types -- they take an appropriate value as argument and return an object of that type.





float() "conversion" function

This function converts an appropriate value to the float type.


# int -> float
xx = 5
yy = float(xx)      # 5.0

# str -> float
var = '5.95'
var2 = float(var)   # 5.95 (a float)






str() "conversion" function

This function converts any value to the str type.


var = 5
var2 = 5.5

svar = str(var)     # '5'
svar2 = str(var2)   # '5.5'

print(len(svar))    # 1
print(len(svar2))   # 3




conversion challenge: treating a string like a number

Because Python is strongly typed, conversions can be necessary.


Numeric data sometimes arrives as strings (e.g. from input() or a file). Use int() or float() to convert to numeric types.


aa = input('enter number and I will double it:  ')

print(type(aa))         # <class 'str'>

num_aa = int(aa)        # int() takes the user's input as an argument
                        # and returns an integer

print(num_aa * 2)       # prints the user's number doubled

You can use int() and float() to convert strings to numbers.





avoid improvising syntax!

It's important for early coders to follow existing syntax and not make up their own.


Imagine that would like to find the length of a string. What do you do? Some students being writing code off the top of their head, even though they are not completely familiar with the right syntax


they may write something like this...

var = 'hello'

mylen = var.len()      # or mylen = length('var')
                       # or mylen = lenth(var)

...and then run it, only to get a strange error that's difficult to diagnose.





using existing examples of a feature to write new code using it

When you want to use a Python feature, you must follow an existing example -- you must not improvise!


Let's say you have a string and you'd like to get its length:

s = "this is a string I'd like to measure"     # determine length (36)

You look up the function in a reference, like pythonreference.com:

mylen = len('hello')

Then you use the feature syntax very carefully:

slen = len(s)         # int, 36

However, your code will be slightly different from the example code:





review: distinguish between variables and string literals

early on we need to distinguish between a variable and a literal.


xx = 10               # assign 10 to xx
yy = 2

zz = xx * yy          # compute 10 * 2 and assign integer 20 to variable yy

print(zz)             # print 20 to screen





review: distinguish between variables and string literals

early on we need to distinguish between a variable and a literal.


xx = 10
yy = 2

zz = xx * yy

print(zz)





taking care not to confuse a string literal and a variable name

Here's a common error that beginners make - try to avoid it!


Going back to our previous example - you'd like to use len() to measure this string:

s = "this is a string I'd like to measure"     # determine length (36)

You look up the function in a reference, like pythonreference.com:

mylen = len('hello')

You have been told to make your syntax match the example's. But should you do this?

slen = len('s')            # int, 1

You were expecting a length of 36, but you got a length of 1. Can you see why? The variable s points to a long string. The literal 's' is just a one-character string. In trying to match the example code, you may have thought you The takeaway is this: anyplace a literal is used, a variable can be used instead; and anyplace a variable is used, a literal can be used instead.





[pr]