Sei sulla pagina 1di 2

Each item in a list can be accessed by the index number. >>> print('{} and {}'.

format('spam',
>>> lst = ['a', 'b', 'c'] 'eggs')
>>> print(lst[0]) # first item spam and eggs
>>> print(lst[-1]) # last item
6. basic string operators
a
1. print statement c A string is a sequence, comparable to a list or tuple. The
The print function displays the argument in the python length of list can be checked by the len function.
console. 4. basic operators
>>> print(len('hello world'))
Python uses the following signs to perform mathematical
>>> print('hello world! ') 11
operations.
hello world!
With the index number, each character can be accessed.
>>> + # add
2. variables and types >>> - # subtract >>> a = 'some string'
Variables are objects that contain data. A variable is >>> * # multiply >>> print(a[1], a[-1])
always of certain type, e.a.: integer, float, string or >>> / # divide o g
boolean. Variable names are always lower-case (PEP8). >>> ** # power
>>> % # modulo The str function returns a string.
>>> a = 1 # type integer
>>> b = 1.0 # type float 5. string formatting >>> x = 1.25
>>> c = 'some text' # type string >>> x = str(x)
String formatting can be done using a placeholder.
>>> d = True # type boolean >>> print(x[2])
>>> text = 'world' 2
The type of an object can be checked with the type >>> print('hello %s!' % text)
function. hello world! The upper and lower method turn a string into capital or
lower-case letters.
>>> a = 'some text' Different types of variables use different placeholders.
>>> print(type(a)) >>> string = 'Hello World'
<class 'str'> >>> %s # placeholder strings >>> print(string.upper())
>>> %d # placeholder decimal values >>> print(string.lower())
3. lists >>> %f # placeholder floating values HELLO WORLD
A list is a data form that holds a sequence of items. hello world
For floating values, the number of digits behind the
>>> lst = [] # empty list decimal point can be controlled. The split method divides a string into multiple items and
>>> lst.append('text') # add text item returns them as a list.
>>> value = 1.23456
>>> lst.append('1.0') # add float item
>>> print('The value %0.2f.' % value) >>> string = 'a,b,c'
>>> print(lst)
The value is 1.23. >>> lst = string.split(',')
['text', 1.0]
>>> print(lst)
Multiple items can be added using a tuple. A tuple is ['a', 'b', 'c']
A list can also be compost directly.
sequence. It looks like a list, but a tuple cannot be
>>> lst = [1, 'a', False] formatted. 7. conditions
>>> print(lst) A condition returns a boolean.
[1, 'a', False] >>> tuple = ('foo', 'bar')
>>> print('%s loves %s' % tuple) >>> x = 2
Other methods for the list object: clear, copy, foo loves bar >>> print(x == 2)
count, extend, index, insert, pop, remove, >>> print(x == 3)
reverse, sort. There is an alternative approach for string formatting
True
using the format method.
False
>>> for i in range(3): >>> def add(x, y):
The following conditions can be tested in python. >>> print(i) >>> return x + y
0 >>> print(add(1, 3))
>>> == # equal to 1 4
>>> != # not equal to 2
>>> > # greater than 10. classes
>>> < # smaller than A while loop keeps iterating until it fulfills a certain In python objects are an encapsulation of variables and
>>> >= # greater or equal to condition. functions into a single entity. A class is essentially a
>>> <= # smaller or equal to template for an object. class names are always to be
>>> x = 0
In combination with the if statement it adds logic to a >>> while x < 3: written in PascalCase (PEP8).
code. The colon and the tab are mandatory. >>> print('x equals: ', x)
>>> class Car:
>>> x = x + 1
>>> """
>>> x = 3 x equals: 0
>>> Always use docstring description.
>>> if x == 3: # returns True x equals: 1
>>> """
>>> print('three') # will print x equals: 2
>>> def __init__(self, color, kms):
>>> if x == 2: # returns False
The break statement can also terminate a while loop. >>> self.color = color
>>> print('two') # won’t print
>>> self.kms = kms
three
>>> y = 0 >>>
Other logical statements are elif and else. >>> while True: >>> def drive(self, km):
>>> print('y equals: ', y) >>> self.kms = self.kms + km
>>> x = 0.5 >>> y += 1 # short for y = y + 1
>>> if x > 1: >>> if y >= 3: An instance of a class results in an object. The attributes
>>> print('too high') >>> break of the object give information about the object. In this case
>>> elif x <= 0: y equals: 0 the color of the car and the km’s it has made.
>>> print('too low') y equals: 1
>>> else: y equals: 2 >>> a_car = Car(color='red',
>>> print('perfect') kms=34000)
perfect 9. functions >>> print(a_car.color)
>>> print(a_car.kms)
A function is a predefined block of code that can be used
8. loops red
multiple times. The def statement is used to define a
34000
A loop is used to iterate through a sequence. A for loop function. Function names are always lower-case (PEP8).
determines the number of iterations before it starts With the defined method drive the amount of km’s can be
iterating. >>> def hello_world():
increased.
>>> """
>>> lst = ['a', 'b', 'c'] >>> Always use docstring description. >>> a_car.drive(500)
>>> for item in lst: >>> """ >>> print(a_car.kms)
>>> print(item) >>> print('hello world! ') 34500
a >>>
b >>> hello_world() # watch parentheses
c >>> hello_world() # use it again
hello world!
Instead of a list, a for loop can also use a range. A hello world!
range is a generator that yields a number from 0 till its
input argument. A function can also take arguments and return an output
with the return statement.

Potrebbero piacerti anche