Python training exercise 1

From BITS wiki
Jump to: navigation, search

Introduction

Just printing things is not that interesting, what you really want to do with a computer program is manipulate data. This is why variables are so important - they allow you to assign information to a name that you can re-use later on.

In this section we will introduce the basic types of variables and how you can manipulate them.

Exercises

Strings

We already saw strings in the previous section. You can assign a string to a variable like this:

myString = "Hello world!"
print(myString)

This will do exactly the same as the first program of 1.1. What happens here is that you assign a value ("Hello world!") to a variable (myString) and then print it out. You can now keep on using myString throughout your program. Note that myString is not quoted because it is now part of the program, try this for example:

myString = "Hello world!"
print("myString")

You will now still assign the value "Hello world!" to the variable myString, but because of the quotes you then print off the string "myString", not the variable.

You can assign strings in the following ways:

myString1 = "Hello world!"
myString2 = 'Hello sun!'
myString3 = """Hello
universe."""
print(myString1)
print(myString2)
print(myString3)

The single and double quotes are essentially the same. If you use triple double quotes """you can assign a string over multiple lines.

Strings from user input

Python provides a very simple way to get user input. This input is always returned as a string, so try the following:

myString = input("Give me a line:")
print myString

Integers

Integers are non-decimal numbers. Python will recognize numbers in the code automatically, so you can do:

myInteger = 5  # Assign integer 5 to the myInteger variable
print(myInteger)

Note the use of # here - this is a comment in the code. Python will ignore everything that comes after the # character on the same line.

You can also do standard mathematical operations on integers:

print(5 + 5)  # Addition
print(5 - 8)  # Subtraction
print(2 * 5)  # Multiplication
print(4 / 2)  # Division
print(5 % 2)  # Modulus, emainder of division
print(2 ** 3) # Power

It doesn't matter if you use variables or integers for this:

x = 5
y = 2
print(x + 5)  # Addition
print(x - 8)  # Subtraction
print(y * x)  # Multiplication
print(4 / y)  # Division
print(5 % y)  # Modulus, remainder of division
print(y ** 3) # Power

The string formatting characters from section 1.2 allow you to print off integers inside a string:

myResult = 5 * 4 + 3 - 2 / 1
print("The result of the calculation is {}.".format(myResult))

Note here the precedence of operations; * and / take precedence over + and -. You can use () to change the results, see what happens if you put 4 + 3 between brackets:

myResult = 5 * (4 + 3) - 2 / 1
print("The result of the calculation is {:10d}.".format(myResult))

The above example also illustrates how you can determine the position of the integer in the output, similar to strings.

Floats

Floats (floating point numbers) are decimal numbers that behave in the same way as integers, except that they are more accurate:

myFloat = 5.4  # Assign float 5.5 to the myFloat variable
print(myFloat)

Mathematical operations are the same:

print(5.2 + 4.8)  # Addition
print(5.2 - 8.3)  # Subtraction
print(2.0 * 5.11212)  # Multiplication
print(4.2 / 2.7)  # Division
print(5.4 % 2.0)  # Modulus, remainder of division
print(4 ** 0.5) # Power

Formatting floats for printing is done with the f formatting character. You can determine the number of characters before and after the decimal point as well:

myFloat = 4545.4542244
print("Print the full float {:f},\ncut off decimals {:.2f},\nor determine the characters before the decimal {:10.1f}.".format(myFloat,myFloat,myFloat))

Note here that we put three formatting characters in the string; we then also need three values to print out. Try removing one and see what happens.

Floats, integers and strings

You can also force a conversion between them with the int() and float() conversions:

myFloat = 4.5
print myFloat
print int(myFloat)  # Note that it will print the result of the operation; myFloat remains an integer!
myInteger = 5
print myInteger
myOtherFloat = float(myInteger)
print myOtherFloat

The same is possible to convert between strings with str(), you can also convert strings back to integers and floats but only if the content of the string is an integer or float:

myFloat = 4.5
myFloatString = str(myFloat)
myInteger = 5
myIntegerString = str(myInteger)
print("My strings are {} and {}".format(myFloatString,myIntegerString))
print("My string converted to integer is {}".format(int(myIntegerString)))
print("My string converted to float is {}".format(float(myFloatString)))


To convert a number to an absolute value, you can use abs():

myInteger = -6
print(myInteger)
print(abs(myInteger))

You can also add, and for number substract, divide and multiple a variable by a number or other variable directly:

myFloat = 6
myString = "ABC"
 
myFloat += 5   # Same as myFloat = myFloat + 5
print(myFloat)
 
myString += "DE"  # Addition works for strings as well
print myString
 
myFloat -= 5   # Same as myFloat = myFloat - 5
print(myFloat)
 
myFloat /= 2   # Same as myFloat = myFloat / 2
print(myFloat)
 
myFloat *= 2   # Same as myFloat = myFloat * 2
print(myFloat)

Finally, you can check what data type a variable is by using type():

myInteger = -6
myFloat = 5.22
myString = "Text!"
 
print(myInteger, type(myInteger))
print(myFloat, type(myFloat))
print(myString, type(myString))

Note here that you can print multiple values by using a comma in between the values.

Booleans and None

Finally, there are the booleans True and False, as well as the nothing value None.

Python returns booleans when comparing values:

myInteger = 5
print(myInteger == 6)   # This means 'is myInteger equal to 6?'
print(myInteger < 6)   # This means 'is myInteger smaller than 6?'
print(myInteger > 6)   # This means 'is myInteger greater than 6?'
print(myInteger <= 6)   # This means 'is myInteger smaller or equal to 6?'
print(myInteger >= 6)   # This means 'is myInteger greater or equal to 6?'
print(myInteger != 6)   # This means 'is myInteger not equal to 6?'

You can also use is and not:

myInteger = 5
print(myInteger is 6)       # Same as ==
print(myInteger is not 6)   # Same as !=
print(not myInteger > 6)    # Same as <=

It is also possible to use logic combinations with and and or:

x = 5
y = 6
print(x == 5 and y > 2)    # Both have to be True for the result to be True
print(x != 5 or y > 2)     # Only one has to be True for the result to be True

Finally, the None value. Although Python will assume 0 and an empty string "" as being False in logic terms:

print(not True)
print(not False)
print(not 0)
print(not "")

Really 0 is still an integer, "" a string, so None is really nothing:

print(not None)
print(0 == None)
print("" == None)

Back to main page