Python

From wiki
Jump to navigation Jump to search

Print the text

print("text")

print("Mark","Brett","Joan","Rick", "Kerri", sep="")
print(10,15,20,25,sep="***")
print("Journey",  "REO Speedwagon" , "Foreigner", sep="\n")

result:

 MarkBrettJoanRickKerri
 10***15***20***25
 Journey
 REO Speedwagon
 Foreigner

Character Case

  • Camel case
print(name.title())
  • Upper Case
print(name.upper())
  • Lower Case
print(name.lower()) 

Concatenating String

name = firstname + " " + lastname

New line and Tab symbols

print("language\n\tPython") - \n(new line) \t(Tab)

Remove whitespace

remove whitespace at the right end of string

rstrip()

remove whitespace from the left of the string

lstrip()

remove whitespace both sides

strip()

Represent non-string values as string

str()

List

In Python, square brackets ( [] ) indicate a list, and individual elements in the list are separated by commas

    bicycles = ['trek', 'cannondale', 'redline', 'specialized']
    print(bicycles)

result:

['trek', 'cannondale', 'redline', 'specialized']


first element in the list

    print(bicycles[0])

result:

trek


last element in the list

    print(bicycles[-1])

result:

specialized

Modifying Elements in a List

    motorcycles = ['honda', 'yamaha', 'suzuki']
    print(motorcycles)

    motorcycles[0] = 'ducati'
    print(motorcycles)

result:

['honda', 'yamaha', 'suzuki']
['ducati', 'yamaha', 'suzuki']

Appending Elements to the End of a List

The append() method adds 'ducati' to the end of the list without affecting any of the other elements in the list:

    motorcycles.append('ducati')

result:

['honda', 'yamaha', 'suzuki', 'ducati']

Inserting Elements into a List

   add a new element at any position in your list by using the insert() method. This operation shifts every other value in the list one position to the right:
    motorcycles = ['honda', 'yamaha', 'suzuki']
    motorcycles.insert(0, 'ducati')
    print(motorcycles)

result:

['ducati', 'honda', 'yamaha', 'suzuki']

Removing an Item Using the del Statement

    motorcycles = ['honda', 'yamaha', 'suzuki']
    print(motorcycles)

    del motorcycles[1]
    print(motorcycles)

result:

   ['honda', 'yamaha', 'suzuki']
   ['honda', 'suzuki']

Removing an Item Using the pop() Method

The pop() method removes the last item in a list, but it lets you work with that item after removing it.

    motorcycles = ['honda', 'yamaha', 'suzuki']
    print(motorcycles)

    popped_motorcycle = motorcycles.pop()
    print(motorcycles)
    print(popped_motorcycle)

result:

 ['honda', 'yamaha', 'suzuki']
 ['honda', 'yamaha']
 suzuki

use pop() to remove an item in a list at any position by including the index of the item

  motorcycles = ['honda', 'yamaha', 'suzuki']
  first_owned = motorcycles.pop(0)
  print('The first motorcycle I owned was a ' + first_owned.title() + '.')

Remember that each time you use pop() , the item you work with is no longer stored in the list.when you want to delete an item from a list and not use that item in any way, use the del statement; if you want to use an item as you remove it, use the pop() method.

Removing an Item by Value

If you only know the value of the item you want to remove, you can use the remove() method.

  motorcycles = ['honda', 'yamaha', 'suzuki', 'ducati']
  print(motorcycles)
  motorcycles.remove('ducati')
  print(motorcycles)

result:

 ['honda', 'yamaha', 'suzuki', 'ducati']
 ['honda', 'yamaha', 'suzuki']
 suzuki

The remove() method deletes only the first occurrence of the value you specify. If there’s a possibility the value appears more than once in the list, you’ll need to use a loop to determine if all occurrences of the value have been removed.

Sorting a List Permanently with the sort() Method

Python’s sort() method makes it relatively easy to sort a list

  cars = ['bmw', 'audi', 'toyota', 'subaru']
  cars.sort()
  print(cars)

result:

 ['audi', 'bmw', 'subaru', 'toyota']
 suzuki

You can also sort this list in reverse alphabetical order by passing the argument reverse=True to the sort() method.

  cars = ['bmw', 'audi', 'toyota', 'subaru']
  cars.sort(reverse=True)
  print(cars)

result:

 ['toyota', 'subaru', 'bmw', 'audi']

Sorting a List Temporarily with the sorted() Function

The sorted() function lets you display your list in a particular order but doesn’t affect the actual order of the list.

  cars = ['bmw', 'audi', 'toyota', 'subaru']
  print("Here is the original list:")
  print(cars)
  print("\nHere is the sorted list:")
  print(sorted(cars))
  print("\nHere is the original list again:")
  print(cars)

result:

 Here is the original list:
 ['bmw', 'audi', 'toyota', 'subaru']
 Here is the sorted list:
 ['audi', 'bmw', 'subaru', 'toyota']
 Here is the original list again:
 ['bmw', 'audi', 'toyota', 'subaru']

The sorted() function can also accept a reverse=True argument if you want to display a list in reverse alphabetical order.

Sorting a list alphabetically is a bit more complicated when all the values are not in lowercase. There are several ways to interpret capital letters when you’re deciding on a sort order, and specifying the exact order can be more complex than we want to deal with at this time. However, most approaches to sorting will build directly on what you learned in this section.

Printing a List in Reverse Order

To reverse the original order of a list, you can use the reverse() method.

  cars = ['bmw', 'audi', 'toyota', 'subaru']
  print(cars)
  cars.reverse()
  print(cars)

result:

 ['bmw', 'audi', 'toyota', 'subaru']
 ['subaru', 'toyota', 'audi', 'bmw']

Finding the Length of a List

You can quickly find the length of a list by using the len() function

  >>> cars = ['bmw', 'audi', 'toyota', 'subaru']
  >>> len(cars)
  4

Python counts the items in a list starting with one, so you shouldn’t run into any off- by-one errors when determining the length of a list.

Looping Through an Entire List

When you want to do the same action with every item in a list, you can use Python’s for loop.

  magicians = ['alice', 'david', 'carolina']
  for magician in magicians:
    print(magician)

result:

 alice
 david
 carolina

Any lines of code after the for loop that are not indented are executed once without repetition

  
  magicians = ['alice', 'david', 'carolina']
  for magician in magicians:
	print(magician.title() + ", that was a great trick!")
	print("I can't wait to see your next trick, " + magician.title() + ".\n")
  print("Thank you, everyone. That was a great magic show!")

result:

 Alice, that was a great trick!
 I can't wait to see your next trick, Alice.
 David, that was a great trick!
 I can't wait to see your next trick, David.
 Carolina, that was a great trick!
 I can't wait to see your next trick, Carolina.
 Thank you, everyone. That was a great magic show!

Using the range() Function

 range(stop)
 range(start, stop[, step])
   Rather than being a function, range is actually an immutable sequence type, as documented in Ranges and Sequence Types — list, tuple, range.
  
for value in range(1,5):
 print(value)

result:

 1
 2
 3
 4
  even_numbers = list(range(2,11,2))
  print(even_numbers)

the range() function starts with the value 2 and then adds 2 to that value. It adds 2 repeatedly until it reaches or passes the end value, 11, and produces this

result:

 [2, 4, 6, 8, 10]
  squares = []
  for value in range(1,11):
	square = value**2
	squares.append(square)
  print(squares)

In Python, two asterisks ( ** ) represent exponents

result:

 [1, 4, 9, 16, 25, 36, 49, 64, 81, 100]

To do integer division and get an integer result, discarding any fractional result, there is another operator, //:

  print(10 // 3) #Floor Division = 3

Working with Part of a List

The code prints a slice of this list, which includes just the first three players

  players = ['charles', 'martina', 'michael', 'florence', 'eli']
  print(players[0:3])

result:

 ['charles', 'martina', 'michael']

You can generate any subset of a list. For example, if you want the sec- ond, third, and fourth items in a list, you would start the slice at index 1 and end at index 4 :

players = ['charles', 'martina', 'michael', 'florence', 'eli']
print(players[1:4])

result:

 ['martina', 'michael', 'florence']

If you omit the first index in a slice, Python automatically starts your slice at the beginning of the list:

  players = ['charles', 'martina', 'michael', 'florence', 'eli']
  print(players[:4])

result:

 ['charles', 'martina', 'michael', 'florence']

A similar syntax works if you want a slice that includes the end of a list.

  players = ['charles', 'martina', 'michael', 'florence', 'eli']
  print(players[2:])

result:

 ['michael', 'florence', 'eli']

if we want to output the last three players on the roster, we can use the slice players[-3:] :

Looping Through a Slice

Instead of looping through the entire list of players at u, Python loops through only the first three names:

 players = ['charles', 'martina', 'michael', 'florence', 'eli']

 print("Here are the first three players on my team:")
 for player in players[:3]:
   print(player.title())

result:

 Here are the first three players on my team:
 Charles
 Martina
 Michael

Copying a List

To copy a list, you can make a slice that includes the entire original list by omitting the first index and the second index ( [:] )

 my_foods = ['pizza', 'falafel', 'carrot cake']
 v friend_foods = my_foods[:]
 
 print("My favorite foods are:")
 print(my_foods)
 
 print("\nMy friend's favorite foods are:")
 print(friend_foods)

result:

My favorite foods are:
['pizza', 'falafel', 'carrot cake']
My friend's favorite foods are:
['pizza', 'falafel', 'carrot cake']

If we had simply set friend_foods equal to my_foods , we would not produce two separate lists. For example, here’s what happens when you try to copy a list without using a slice:

 my_foods = ['pizza', 'falafel', 'carrot cake']

 # This doesn't work:
 friend_foods = my_foods

 my_foods.append('cannoli')
 friend_foods.append('ice cream')

 print("My favorite foods are:")
 print(my_foods)

 print("\nMy friend's favorite foods are:")
 print(friend_foods)

result:

My favorite foods are:
['pizza', 'falafel', 'carrot cake', 'cannoli', 'ice cream']
My friend's favorite foods are:
['pizza', 'falafel', 'carrot cake', 'cannoli', 'ice cream']

Defining a Tuple

sometimes you’ll want to create a list of items that cannot change. Tuples allow you to do just that. Python refers to values that cannot change as immutable, and an immutable list is called a tuple.

dimensions = (200, 50)
print(dimensions[0])
print(dimensions[1])


Let’s see what happens if we try to change one of the items in the tuple dimensions :

  dimensions = (200, 50)
  dimensions[0] = 250

result:

Traceback (most recent call last): File "dimensions.py", line 3, in <module> dimensions[0] = 250 TypeError: 'tuple' object does not support item assignment

if Statements

The loop in this example first checks if the current value of car is 'bmw'. If it is, the value is printed in uppercase. If the value of car is anything other than 'bmw' , it’s printed in title case:

 cars = ['audi', 'bmw', 'subaru', 'toyota']

 for car in cars:
   if car == 'bmw':
     print(car.upper())
   else:
     print(car.title())

result:

 Audi
 BMW
 Subaru
 Toyota

Checking Whether a Value Is Not in a List

You can check whether a user has been banned before allowing that person to submit a comment:

banned_users = ['andrew', 'carolina', 'david']
user = 'marie'

  if user not in banned_users:
    print(user.title() + ", you can post a response if you wish.")

The if-elif-else Chain

Often, you’ll need to test more than two possible situations, and to evaluate these you can use Python’s if - elif - else syntax. Python executes only one block in an if - elif - else chain. It runs each conditional test in order until one passes. When a test passes, the code following that test is executed and Python skips the rest of the tests.

 age = 12

 if age < 4:
  price = 0
 elif age < 18:
  price = 5
 elif age < 65:
  price = 10
 else:
  price = 5

print("Your admission cost is $" + str(price) + ".")

Using if Statements with Lists

As an example, let’s check whether the list of requested toppings is empty before building the pizza. If the list is empty, we’ll prompt the user and make sure they want a plain pizza

When the name of a list is used in an if statement, Python returns True if the list contains at least one item; an empty list evaluates to False . If requested_toppings passes the conditional test, we run the same for loop we used in the previous example. If the conditional test fails, we print a message asking the customer if they really want a plain pizza with no toppings

 requested_toppings = []
 if requested_toppings:
  for requested_topping in requested_toppings:
   print("Adding " + requested_topping + ".")
  print("\nFinished making your pizza!")
 else:
 print("Are you sure you want a plain pizza?")

Using Multiple Lists
The following example defines two lists. The first is a list of available top- pings at the pizzeria, and the second is the list of toppings that the user has requested. This time, each item in requested_toppings is checked against the list of available toppings before it’s added to the pizza:

 available_toppings = ['mushrooms', 'olives', 'green peppers','pepperoni', 'pineapple', 'extra cheese'] //we define a list of available toppings at this pizzeria. Note that this could be a tuple if the pizzeria has a stable selection of toppings.
 requested_toppings = ['mushrooms', 'french fries', 'extra cheese'] //we make a list of toppings that a customer has requested.
 for requested_topping in requested_toppings: //we loop through the list of requested toppings.Inside the loop, we first check to see if each requested topping is actually in the list of available toppings
 if requested_topping in available_toppings: //If it is, we add that topping to the pizza. If the requested topping is not in the list of available toppings, the else block will run
   print("Adding " + requested_topping + ".")
 else: //The else block prints a message telling the user which toppings are unavailable.
   print("Sorry, we don't have " + requested_topping + ".")
 print("\nFinished making your pizza!")

result:

 Adding mushrooms.
 Sorry, we don't have french fries.
 Adding extra cheese.
 Finished making your pizza!

Working with Dictionaries

A dictionary in Python is a collection of key-value pairs. Each key is connected to a value, and you can use a key to access the value associated with that key. A key’s value can be a number, a string, a list, or even another dictionary.

 alien_0 = {'color': 'green', 'points': 5}
 print(alien_0['color'])
 print(alien_0['points'])

Adding New Key-Value Pairs

Dictionaries are dynamic structures, and you can add new key-value pairs to a dictionary at any time

 alien_0 = {'color': 'green', 'points': 5}
 print(alien_0)

 alien_0['x_position'] = 0
 alien_0['y_position'] = 25

 print(alien_0)

result:

 {'color': 'green', 'points': 5}
 {'color': 'green', 'points': 5, 'y_position': 25, 'x_position': 0}

It’s sometimes convenient, or even necessary, to start with an empty diction- ary and then add each new item to it.

 alien_0 = {}
 alien_0['color'] = 'green'
 alien_0['points'] = 5
 print(alien_0)

Modifying Values in a Dictionary

To modify a value in a dictionary, give the name of the dictionary with the key in square brackets and then the new value you want associated with that key

Fixed-Type Arrays in Python

class array.array(typecode[, initializer])
   A new array whose items are restricted by typecode, and initialized from the optional initializer value, which must be a list, a bytes-like object, or iterable over elements of the appropriate type.
   If given a list or string, the initializer is passed to the new array’s fromlist(), frombytes(), or fromunicode() method (see below) to add initial items to the array. Otherwise, the iterable initializer is passed to the extend() method.
Type code C Type Python Type Minimum size in bytes
'b' signed char int 1
'B' unsigned char int 1
'u' Py_UNICODE Unicode character 2
'h' signed short int 2
'H' unsigned short int 2
'i' signed int int 2
'I' unsigned int int 2
'l' signed long int 4
'L' unsigned long int 4
'q' signed long long int 8
'Q' unsigned long long int 8
'f' float float 4
'd' double float 8
import array
L = list(range(10))
A = array.array('i', L)
A

result:

array('i', [0, 1, 2, 3, 4, 5, 6, 7, 8, 9])

Here 'i' is a type code indicating the contents are integers.

Creating Arrays from Python Lists

import numpy as np
# integer array:
np.array([1, 4, 2, 5, 3])

result:

array([1, 4, 2, 5, 3])

 unlike Python lists, NumPy is constrained to arrays that all contain
 the same type. If types do not match, NumPy will upcast if possible (here, integers are
 upcast to floating point):
import numpy as np
np.array([3.14, 4, 2, 3])

result:

array([ 3.14,4.,2.,3.])

 If we want to explicitly set the data type of the resulting array, we can use the dtype keyword:
import numpy as np
np.array([1, 2, 3, 4], dtype='float32')

result:

array([ 1.,2.,3.,4.], dtype=float32)

 unlike Python lists, NumPy arrays can explicitly be multidimensional; here’s
 one way of initializing a multidimensional array using a list of lists:
# nested lists result in multidimensional arrays
np.array([range(i, i + 3) for i in [2, 4, 6]])

result:

array([[2, 3, 4], [4, 5, 6], [6, 7, 8]])

Creating Arrays from Scratch

numpy.zeros

# Create a length-10 integer array filled with zeros
np.zeros(10, dtype=int)

result:

array([0, 0, 0, 0, 0, 0, 0, 0, 0, 0])

numpy.ones

# Create a 3x5 floating-point array filled with 1s
np.ones((3, 5), dtype=float)

result:

array([[ 1.,[ 1.,[ 1.,1.,1.,1.,1.,1.,1.,1.,1.,1.,1.],1.],1.]])

numpy.full

# Create a 3x5 array filled with 3.14
np.full((3, 5), 3.14)

result:

array([[ 3.14, 3.14, 3.14, 3.14, 3.14], [ 3.14, 3.14, 3.14, 3.14, 3.14], [ 3.14, 3.14, 3.14, 3.14, 3.14]])

numpy.arange

 numpy.arange([start, ]stop, [step, ]dtype=None)

Return evenly spaced values within a given interval. Values are generated within the half-open interval [start, stop) (in other words, the interval including start but excluding stop). For integer arguments the function is equivalent to the Python built-in range function, but returns an ndarray rather than a list. When using a non-integer step, such as 0.1, the results will often not be consistent. It is better to use linspace for these cases.

Parameters: start : number, optional
   Start of interval. The interval includes this value. The default start value is 0.
stop : number
   End of interval. The interval does not include this value, except in some cases where step is not an integer and floating point round-off affects the length of out.
step : number, optional
   Spacing between values. For any output out, this is the distance between two adjacent values, out[i+1] - out[i]. The default step size is 1. If step is specified as a position argument, start must also be given.
dtype : dtype
   The type of the output array. If dtype is not given, infer the data type from the other input arguments.
Returns: arange : ndarray
   Array of evenly spaced values.
For floating point arguments, the length of the result is ceil((stop - start)/step). Because of floating point overflow, this rule may result in the last element of out being greater than stop.
# Create an array filled with a linear sequence
# Starting at 0, ending at 20, stepping by 2
# (this is similar to the built-in range() function)
np.arange(0, 20, 2)


result:

array([ 0,2,4,6,8, 10, 12, 14, 16, 18])

numpy.linspace

numpy.linspace(start, stop, num=50, endpoint=True, retstep=False, dtype=None):
   Return evenly spaced numbers over a specified interval.
   Returns `num` evenly spaced samples, calculated over the
   interval [`start`, `stop`].
   The endpoint of the interval can optionally be excluded.
Parameters start : scalar
       The starting value of the sequence.
stop : scalar
       The end value of the sequence, unless `endpoint` is set to False.
       In that case, the sequence consists of all but the last of ``num + 1``
       evenly spaced samples, so that `stop` is excluded.  Note that the step
       size changes when `endpoint` is False.
num : int, optional
       Number of samples to generate. Default is 50. Must be non-negative.
endpoint : bool, optional
       If True, `stop` is the last sample. Otherwise, it is not included.
       Default is True.
retstep : bool, optional
       If True, return (`samples`, `step`), where `step` is the spacing
       between samples.
dtype : dtype, optional
       The type of the output array.  If `dtype` is not given, infer the data
       type from the other input arguments.
       .. versionadded:: 1.9.0
Returns samples : ndarray
       There are `num` equally spaced samples in the closed interval
       ``[start, stop]`` or the half-open interval ``[start, stop)``
       (depending on whether `endpoint` is True or False).
step : float, optional
       Only returned if `retstep` is True
       Size of spacing between samples.
# Create an array of five values evenly spaced between 0 and 1
np.linspace(0, 1, 5)


result:

array([ 0.,0.25,0.5 ,0.75,1.])

numpy.random.random

 numpy.random.random(size=None)
   Return random floats in the half-open interval [0.0, 1.0).
Parameters: size : int or tuple of ints, optional
   Output shape. If the given shape is, e.g., (m, n, k), then m * n * k samples are drawn. Default is None, in which case a single value is returned.
Returns: out : float or ndarray of floats
   Array of random floats of shape size (unless size=None, in which case a single float is returned).
# Create a 3x3 array of uniformly distributed
# random values between 0 and 1
np.random.random((3, 3))


result:

array([[ 0.99844933,0.52183819,0.22421193], [ 0.08007488,0.45429293,0.20941444], [ 0.14360941,0.96910973,0.946117 ]])

numpy.random.normal

 numpy.random.normal(loc=0.0, scale=1.0, size=None)

Draw random samples from a normal (Gaussian) distribution.

Parameters: loc : float or array_like of floats
   Mean (“centre”) of the distribution.
scale : float or array_like of floats
   Standard deviation (spread or “width”) of the distribution.
size : int or tuple of ints, optional
   Output shape. If the given shape is, e.g., (m, n, k), then m * n * k samples are drawn. If size is None (default), a single value is returned if loc and scale are both scalars. Otherwise, np.broadcast(loc, scale).size samples are drawn.
Returns: out : ndarray or scalar
   Drawn samples from the parameterized normal distribution.
# Create a 3x3 array of normally distributed random values
# with mean 0 and standard deviation 1
np.random.normal(0, 1, (3, 3))


result:

array([[ 1.51772646,0.39614948, -0.10634696], [ 0.25671348,0.00732722, 0.37783601], [ 0.68446945,0.15926039, -0.70744073]])