Básicos del Lenguaje

1

Guía de instalación y conceptos básicos

2

Archivos y slides del curso práctico de Python

3

IMPORTANTE: Instalando Ubuntu Bash en Windows para facilitarte el seguimiento del curso desde Windows.

4

¿Qué es la programación?

5

¿Por qué programar con Python?

6

Operadores matemáticos

7

Variables y expresiones

8

Presentación del proyecto

9

Funciones

10

Usando funciones en nuestro proyecto

11

Operadores lógicos

12

Estructuras condicionales

Uso de strings y ciclos

13

Strings en Python

14

Operaciones con Strings en Python

15

Operaciones con strings y el comando Update

16

Operaciones con strings y el comando Delete

17

Operaciones con strings: Slices en python

18

For loops

19

While loops

20

Iterators and generators

Estructuras de Datos

21

Uso de listas

22

Operaciones con listas

23

Agregando listas a nuestro proyecto

24

Diccionarios

25

Agregando diccionarios a nuestro proyecto

26

Tuplas y conjuntos

27

Tuplas y conjuntos en código

28

Introducción al módulo collections

29

Python comprehensions

30

Búsquedas binarias

31

Continuando con las Búsquedas Binarias

32

Manipulación de archivos en Python 3

Uso de objetos y módulos

33

Decoradores

34

Decoradores en Python

35

¿Qué es la programación orientada a objetos?

36

Programación orientada a objetos en Python

37

Scopes and namespaces

38

Introducción a Click

39

Definición a la API pública

40

Clients

41

Servicios: Lógica de negocio de nuestra aplicación

42

Interface de create: Comunicación entre servicios y el cliente

43

Actualización de cliente

44

Interface de actualización

45

Manejo de errores y jerarquía de errores en Python

46

Context managers

Python en el mundo real

47

Aplicaciones de Python en el mundo real

Conclusiones finales

48

Python 2 vs 3 (Conclusiones)

Clases bonus

49

Entorno Virtual en Python y su importancia: Python en el mundo real

No tienes acceso a esta clase

¡Continúa aprendiendo! Únete y comienza a potenciar tu carrera

Agregando listas a nuestro proyecto

23/49
Recursos

Agregaremos la reciente Estructura de Datos aprendida a nuestro proyecto de PlatziVentas, en este caso listas.

Aportes 68

Preguntas 13

Ordenar por:

¿Quieres ver más aportes, preguntas y respuestas de la comunidad?

index() es un método que busca la posición de un elemento en una lista y nos regresa su posicion. Y si hay varios elementos iguales, nos regresa el primer elemento

https://www.programiz.com/python-programming/methods/list/index

Le doy un 10 a este profesor, su pasion su explicacion uffff ahora es que me encanta la programacion

Código actualizados:

import sys

clients = ['luisa', 'juan']

def create_client(client_name):
	global clients

	if client_name not in clients :
		clients.append(client_name)
	else:
		print ('Client already is in the client\'s list')

def list_clients():
	for idx, client in enumerate(clients):
		print ('{} : {}'.format(idx, client))


def updated_client(client_name, updated_client_name):
	global clients

	if client_name in clients :
		index = clients.index(client_name)
		clients[index] = updated_name
	else:
		print ('Client is no it client\'s list')


def delete_client(client_name):
	global clients

	if client_name in clients:
		clients.remove(client_name)
	else:
		print('Client is not in client\'s list')

def search_client(client_name):

	for client in clients:
		if client != client_name:
			continue
		else:
			return True


def _print_welcome():
	print ('WELCOME TO PLATZI VENTAS')
	print ('*' * 50)
	print ('What would you like to do today ? ')
	print ('[C]reate client')
	print ('[L]ist client')
	print ('[U]pdated client')
	print ('[D]elete client')
	print ('[S]earch client')


def _get_client_name ():
	client_name = None

	while not client_name:
		client_name = str.lower(input('What is the client name ? '))

		if client_name == 'exit':
			client_name = None
			break

	if not client_name:
			sys.exit()

	return client_name

if __name__ == '__main__':
	_print_welcome()

	command = input()
	command = command.upper()

	if command == 'C':
		client_name = _get_client_name()
		create_client(client_name)
		list_clients()
	elif command == 'L':
		list_clients()
	elif command == 'U':
		client_name = _get_client_name()
		updated_name = str.lower(input ('What is the updated client name ? '))
		updated_client(client_name, updated_name)
		list_clients()
	elif command == 'D':
		client_name = _get_client_name()
		delete_client(client_name)
		list_clients()
	elif command == 'S':
		client_name = _get_client_name()
		found = search_client(client_name)

		if found:
			print('The client is in the client\'s list')
		else:
			print('The client: {} is not in our client\'s list'.format(client_name))

	else:
		print ('Invalid command')
# pip install tabulate
# from tabulate import tabulate     
def list_clients():
    global Clients
    if Clients:
        print('Our Clients are :')
        show=[]
        for idx,name in enumerate(Clients):
            show.append([idx+1,name])
        print(tabulate(show,headers=['N°','Name'],tablefmt='fancy_grid'))
    else:
        print(' I don´t have Clients in this moment')


## console output
Our Clients are :
╒══════╤════════╕
│   N° │ Name   │
╞══════╪════════╡
│    1 │ jose   │
├──────┼────────┤
│    2 │ juan   │
├──────┼────────┤
│    3 │ jorge  │
╘══════╧════════╛

buenos días, cómo estan?
me pueden ayudar por favor con una consulta… ¿cuál es la razón por la que ya no se debe usar el

global clients

cuando definimos la función para listar los clientes? Si igual se esta llamando en la función

En lugar de:

print('{}: {}'.format(idx, client))

Podemos usar mejor

print(f'{idx}: {client}')

Les comparto mi código como va, tiene algunas funcionalidades mas que el del profesor!


import sys



clients = ['Pablo', 'Ricardo']

def Create_Cliente(client_name):
	global clients
	
	if client_name not in clients:

		clients.append(client_name)
		print('Client added')
		

	else:

		print('The name already is in clienṭ\'s list!!!')

	list_clients(clients)

def delete_client(client_name):
	
	global clients
	
	clients.remove(client_name)
	print('Client removed')
	list_clients(clients)


def update_client(client_name):
	
	global clients
	
	if client_name not in clients:
		
		print('The name you pick is not in the clienṭ\'s list!!!')
	
	else:

		updated_client_name = input('Enter the new name: ')
		index = clients.index(client_name)
		clients[index] =  updated_client_name
		print('Client Updated')

	list_clients(clients)


def search_client(client_name):
	
	global clients

	for client in clients:

		if client_name == client:

			return True

		else: 

			continue

def _finder(client_name):
	
	client_finded = search_client(client_name)

	if client_finded :

		print('The client {} is in the client\'s list'.format(client_name))

	else:

		print('The client {} isn\'t in the client\'s list'.format(client_name))

	list_clients(clients)


def break_Name(client_name):

	if client_name == 'Exit':
		print('Good Bye')
		sys.exit()
	pass

def list_clients(clients):
	print('')
	print('-°'*28)
	print('')
	for idx, client in enumerate(clients):
		print('{}: {}'.format(idx, client))
	print('')
	print('-°'*28)
	print('')



def welcome():
	
	command = None
	client_name = None
	count_Welcome = 0

	while command != 'E':
		
		command = None
		client_name = None

		count_Welcome +=1

		print('*'*56)
		print('')
		print('EXECUTION NUMBER {}'.format(count_Welcome))

		global clients
		print('')
		
		if count_Welcome == 1:
			print('-'*15+'WELCOME TO PLATZI SALES!!!'+'-'*15)
			print('')
		
		print('')
		print('*' * 56)
		print('')
		print('What would you like to do?')
		print('')
		print('[C]reate Client')
		print('[U]pdate')
		print('[S]earch')
		print('[L]ist')
		print('[D]elete client')
		print('[E]xit')
		print('')
		print('At any time you can enter "Exit" to escape the program')

		command = input('Please tell us your option: ')

		print('')
		
		if command == 'Exit':
			break_Name(command)


		command = command.upper()

		if (command == "C"):

			while client_name == None or client_name == '':
				
				client_name = input('Please enter the name you want to create: ')
				break_Name(client_name)

			Create_Cliente(client_name)

		elif (command == 'L'):

			list_clients(clients)
			break_Name(client_name)

		elif (command == "D"):
			
			while client_name == None or client_name == '':

				client_name = input('Please enter the name you want to delete: ')
				break_Name(client_name)
			
			delete_client(client_name)

		elif (command == 'U'):
			
			while client_name == None or client_name == '':
			
				client_name = input('Please enter the name you want to Update: ')
				break_Name(client_name)
			
			update_client(client_name)

		elif (command == 'S'):
			
			while client_name == None or client_name == '':

				client_name = input('please enter the name you want to Seach: ')
				break_Name(client_name)
			
			_finder(client_name)

		elif (command == 'E'):

			print('Good Bye')
			break


		else:

			print('Invalid option: ')



if __name__ == '__main__':
	

	welcome()


Muy bien explicado y desarrollado este asunto de las listas.

Es interesante que mientras contenido se aprende, mas fácil y lógico se vuelve programar.

Les recomiendo en Esta pagina web donde podemos ver mas ejemplos y casos acerca de como usar listas para basarse en la estructura de datos.

Mi código hasta ahora, le agregue el modulo os para limpiar la consola y tener un menú mas limpio.

Para linux:

import os 
os.system('clear')

Para windows:

import os 
os.system('cls')
import sys
import os

clients = ['Alejo','Alvaro']

def create_client(client_name):
    global clients
    if not (client_name in clients):
        clients.append(client_name)
    else: 
        os.system('clear')
        print('The client is already in client\'s list.')
        print('[Enter] to continue]')
        input()


def update_client(client_name):
    global clients
    if (client_name in clients):
        updated_client = input('Insert a new name: ')
        index = clients.index(client_name)
        clients[index] = updated_client
    else:
        os.system('clear')
        print('The client isn\'t in client\'s list.')
        print('[Enter] to continue]')
        input()


def delete_client(client_name):
    global clients

    if (client_name in clients):
        clients.remove(client_name)
    else:
        os.system('clear')
        print('The client isn\'t in client\'s list.')
        print('[Enter] to continue]')
        input()


def list_clients():
    
    for idx , client in enumerate(clients):
        print(f"{idx}:{client}")

def search_client(client_name):
    
    if client_name in clients:
        return True
    else:
        return False

def get_client_name():
    client_name = None

    while not (client_name):
        client_name = input('Insert the client name: ')
    return client_name


def _print_welcome():
    print('Welcome to Platzi Ventas.')
    print('*' * 25)
    print('Menu:')
    print('[C]reate client.')
    print('[U]pdate client.')
    print('[D]elete client.')
    print('[L]ist clients.')
    print('[E]xit.')
    print('Insert a command: ')


if __name__ == '__main__':
    opt = None

    while (opt != 'E') or (not opt):
        _print_welcome()
        opt = input().upper()
        if (opt == 'C'):
            os.system('clear')
            print('Creating a new client...')
            client_name = get_client_name()
            create_client(client_name)
        elif (opt == 'U'):
            os.system('clear')
            print('Updateing a client...')
            client_name = get_client_name()
            update_client(client_name)
        elif (opt == 'D'):
            os.system('clear')
            print('Deleting a client...')
            client_name = get_client_name()
            delete_client(client_name)
        elif (opt == 'L'):
            os.system('clear')
            list_clients()
            print('[Enter] to continue]')
            input()
        elif (opt == 'S'):
            client_name = get_client_name()
            found = search_client(client_name)

            if (found):
                print(f'The client {client_name} is in client\'s list.')
            else:
                print(f'The client {client_name} isn\'t in client\'s list.')
        elif (opt == 'E'):
            os.system('clear')
            sys.exit()
        else:
            os.system('clear')
            print('Try again! Invalid command.')
            print('[Enter] to continue]')
            input()
        os.system('clear')

El buscar cliente también puede ser

def search_client(client_name):
    return client_name in clients```

Yo hice un poco distinta la función search y no retorna ningún valor, directamente se imprime desde ahí, también en lugar de recorrer la lista directamente pregunto si encuentra el elemento.

def search_client(client_name):
    global clients
    if client_name in clients:
        print('The client {} is in the client list'.format(client_name))
    else:
        print('The client {} isn\'t in the client list'.format(client_name))

TIP Es mas organizado trabajar con una funcion llamada run() para introducir todo el bloque de codigo donde se llaman las funciones y en el entry point unicamente hacer el llamado de la funcion es una buena practica y es lo que se hace a nivel profesional

import sys

clients = ['pablo', 'ricardo']

def create_client(client_name):
	global clients

	if client_name not in clients :
		clients.append(client_name)
	else:
		print ('Client already is in the client\'s list')

def list_clients():
	for idx, client in enumerate(clients):
		print ('{} : {}'.format(idx, client))


def updated_client(client_name, updated_client_name):
	global clients

	if client_name in clients :
		index = clients.index(client_name)
		clients[index] = updated_name
	else:
		print ('Client is no it client\'s list')


def delete_client(client_name):
	global clients

	if client_name in clients:
		clients.remove(client_name)
	else:
		print('Client is not in client\'s list')

def search_client(client_name):

	for client in clients:
		if client != client_name:
			continue
		else:
			return True


def _print_welcome():
	print ('WELCOME TO PLATZI VENTAS')
	print ('*' * 50)
	print ('What would you like to do today ? ')
	print ('[C]reate client')
	print ('[L]ist client')
	print ('[U]pdated client')
	print ('[D]elete client')
	print ('[S]earch client')


def _get_client_name ():
	client_name = None

	while not client_name:
		client_name = str.lower(input('What is the client name ? '))

		if client_name == 'exit':
			client_name = None
			break

	if not client_name:
			sys.exit()

	return client_name

if __name__ == '__main__':
	_print_welcome()

	command = input()
	command = command.upper()

	if command == 'C':
		client_name = _get_client_name()
		create_client(client_name)
		list_clients()
	elif command == 'L':
		list_clients()
	elif command == 'U':
		client_name = _get_client_name()
		updated_name = str.lower(input ('What is the updated client name ? '))
		updated_client(client_name, updated_name)
		list_clients()
	elif command == 'D':
		client_name = _get_client_name()
		delete_client(client_name)
		list_clients()
	elif command == 'S':
		client_name = _get_client_name()
		found = search_client(client_name)

		if found:
			print('The client is in the client\'s list')
		else:
			print('The client: {} is not in our client\'s list'.format(client_name))

	else:
		print ('Invalid command')

Tengo un pequeño problema en el List_clients en el que me muestra la lista como esta definida en la variable. Este es mi código

import sys

clients = ['franco','matias','luis','tomas','rebeca']

def create_client(client_name):
	global clients

	if client_name not in clients: 
		clients.append(client_name)
	else:
		print("El cliente ya esta en la lista.")


def update_client(client_name, updated_client_name):
	global clients

	if client_name in clients:
		index = clients.index(client_name)
		clients[index] = updated_client_name

	else:
		print("El cliente no se encuentra en la lista.")


def delete_client(client_name):
	global clients

	if client_name in clients:
		clients.remove(client_name)
	else:
		print("El cliente no se puede borrar por que no esta en la lista.")


def search_client(client_name):
	for client in clients:
		if client != client_name:
			continue
		else:
			return True


def list_clients():
	for idx, client in enumerate(clients):
		print(f"{idx}: {client}")


def _print_welcome():
	print("Bienvenido")
	print("*" * 50)
	print("Que es lo primero que va a hacer?")
	print("[C]rear cliente")
	print("[L]eer clientes")
	print("[A]ctualizar")
	print("[B]orrar cliente")
	print("[S]earch client")


def _get_client_name():
	client_name = None
	while not client_name:
		client_name = input("Cual es nombre del cliente? ")

		if client_name == 'exit':
			client_name = None
			break
	if not client_name:
		sys.exit()
	
	return client_name		


if __name__ == "__main__":
	
	_print_welcome()

	command = input()
	command = command.upper()

	if command == "C":
		client_name = _get_client_name()
		create_client(client_name)
		list_clients()

	elif command == "B":
		client_name = _get_client_name()
		delete_client(client_name)
		print(clients)

	elif command == "A":
		client_name = _get_client_name()
		updated_client_name = input("Cual es el nombre del cliente actualizad: ")
		update_client(client_name, updated_client_name)
		print(clients)

	elif command == "L":
		print(clients)

	elif command == "S":
		client_name = _get_client_name()
		found = search_client(client_name)

		if found:
			print(f"El cliente {client_name} se encuentra en la lista de clientes")
		else:
			print(f"El cliente: {client_name} no se encuentra en la lista de clientes")

	else:
		print("Ingrese un comando valido")```

Excelente!!

la funcion search puede ser de la siguiente forma:

def search_name(name):
    global clients
    return name in clients

format en python 3.7 puede usarse de la siguiente forma :

f"{var1}...algo...{varN}"

tengo problemas con el append

def create_client(client_name):
    global clients

    if client_name not in clients:
        clients.append('client_name')
    else:
        print(client_name, ' ya esta creado')

AttributeError: ‘str’ object has no attribute ‘append’

Aqui un mejor search_client

def search_client(client_name):
    global clients

    if client_name in clients:
        return True
    else:
        return False

Para los que deseen saber cómo está el código, Les dejo mi código en mi repositorio (con unos pocos cambios):
https://github.com/behagoras/basic-python/blob/lists/main.py

búsqueda de clientes:

def search_client(client_name):
    return client_name in clients

M e e n c a n t a

Para search client agregre un print para que nos indique su id y su nombre:elif command == 'S':    client\_name = \_get\_client\_name()    found = search\_client(client\_name)     if found == True:        print("The client is in the client's list")        index = clients.index(client\_name)        print(f'{index+1} : {client\_name}')    else:        print(f"The client: {client\_name} is not in our client's list") ```js elif command == 'S': client_name = _get_client_name() found = search_client(client_name) if found == True: print("The client is in the client's list") index = clients.index(client_name) print(f'{index} : {client_name}') else: print(f"The client: {client_name} is not in our client's list") ```

Les comparto los cambios que vamos haciendo en el proyecto, clase por clase.

Muy bueno el curso. Asi es que debe ser. Menos mal use Git antes de hacer los cambios 🤣, llevar bien el registro de cambios importantes.

Mi codigo actualizado:

<
import sys
from ast import Delete
from http import client


clients = ['pablo', 'ricardo']


def create_client(client_name):
    global clients
    if client_name not in clients:
        clients.append(client_name)
    else:
        _client_was_found()


def list_clients():
    for idx, client in enumerate(clients):
        print('{}: {}'.format(idx, client))


def update_client (client_name, updated_client_name):
    global clients

    if client_name in clients:
        index = clients.index(client_name)
        clients[index] = updated_client_name
    else:
        _client_not_found()


def delete_client(client_name):
    global clients
    
    if client_name in clients:
        clients.remove(client_name)
    else:
        _client_not_found()


def search_client(client_name):
    for client in clients:
        if client != client_name:
            continue
        else:
            return True


def _print_welcome():
    print('BIENVENIDOS A PLATZI VENTAS')
    print('*'*50)
    print('Que quieres hacer hoy?')
    print('[C]reate client')
    print('[L]ist clients')
    print('[U]pdate client')
    print('[D]elete client')
    print('[S]earch client')


def _get_client_name():
    client_name = None

    while not client_name:
        client_name = input('Cual es el nombre del cliente? ')

        if client_name == 'exit':
            break
        if not client_name:
            sys.exit()

    return client_name

def _client_not_found():
    return print('El cliente no esta registrado en la lista')


def _client_was_found():
    print('El cliente ya esta registrado en la lista')


if __name__ == '__main__':
    _print_welcome()
    command = input("Escribe un comando: ")
    command = command.upper()
    if command == 'C':
        client_name = _get_client_name()
        create_client(client_name)
        list_clients()
    elif command == 'L':
        list_clients()
    elif command == 'D':
        client_name = _get_client_name()
        delete_client(client_name)
        list_clients()
    elif command == 'U':
        client_name = _get_client_name()
        updated_client_name = input('Inglrese la actualizacion en el nombre: ')
        update_client(client_name, updated_client_name)
        list_clients()
    elif command == 'S':
        client_name = _get_client_name()
        found = search_client(client_name)
        if found:
            print('Se encontro el cliente en la lista')
        else:
            _client_not_found()
    else:
        print('Comando invalido')
> 

Mi codigo actualizado:

<


import sys
from ast import Delete
from http import client


clients = ['pablo', 'ricardo']


def create_client(client_name):
    global clients
    if client_name not in clients:
        clients.append(client_name)
    else:
        _client_was_found()


def list_clients():
    for idx, client in enumerate(clients):
        print('{}: {}'.format(idx, client))


def update_client (client_name, updated_client_name):
    global clients

    if client_name in clients:
        index = clients.index(client_name)
        clients[index] = updated_client_name
    else:
        _client_not_found()


def delete_client(client_name):
    global clients
    
    if client_name in clients:
        clients.remove(client_name)
    else:
        _client_not_found()


def search_client(client_name):
    for client in clients:
        if client != client_name:
            continue
        else:
            return True


def _print_welcome():
    print('BIENVENIDOS A PLATZI VENTAS')
    print('*'*50)
    print('Que quieres hacer hoy?')
    print('[C]reate client')
    print('[L]ist clients')
    print('[U]pdate client')
    print('[D]elete client')
    print('[S]earch client')


def _get_client_name():
    client_name = None

    while not client_name:
        client_name = input('Cual es el nombre del cliente? ')

        if client_name == 'exit':
            break
        if not client_name:
            sys.exit()

    return client_name

def _client_not_found():
    return print('El cliente no esta registrado en la lista')


def _client_was_found():
    print('El cliente ya esta registrado en la lista')


if __name__ == '__main__':
    _print_welcome()
    command = input("Escribe un comando: ")
    command = command.upper()
    if command == 'C':
        client_name = _get_client_name()
        create_client(client_name)
        list_clients()
    elif command == 'L':
        list_clients()
    elif command == 'D':
        client_name = _get_client_name()
        delete_client(client_name)
        list_clients()
    elif command == 'U':
        client_name = _get_client_name()
        updated_client_name = input('Inglrese la actualizacion en el nombre: ')
        update_client(client_name, updated_client_name)
        list_clients()
    elif command == 'S':
        client_name = _get_client_name()
        found = search_client(client_name)
        if found:
            print('Se encontro el cliente en la lista')
        else:
            _client_not_found()
    else:
        print('Comando invalido')


> 

Para no repetir código sugiero añadir la variable global clients, en run(), así no la debemos escribir en el resto de funciones porque ya es una variable global dentro de nuestro código.

El código ya Actualizado a Lista

import sys
clients = ['Jesus', 'Daniel']

def create_client(client_name): # create_client crea un nuevo cliente
    global clients
    if client_name not in clients: # Si el cliente no existe, lo crea
        clients.append(client_name)
        print (f'Cliente {client_name} Creado Satisfactoriamente')
    else: # Si el cliente ya existe, lo informa
        print(f'El Cliente {client_name} Ya Existe')

def delete_client(client_name): # Creo una funcion para eliminar un cliente
    global clients
    if client_name in clients:
        clients.remove(client_name)
        print(f'El cliente {client_name} fue eliminado satisfactoriamente')
    else:
        print(f'El Cliente {client_name} No Existe')

def update_client(client_name, update_client_name): # Creo una funcion para actualizar el nombre del cliente
    global clients
    if client_name in clients:
        clients[clients.index(client_name)] = update_client_name # Actualizo el nombre del cliente
        print (f'Cliente {client_name} Fue Actualizado Satisfactoriamente a {update_client_name}')
    else:
        print(f'El Cliente {client_name} No Existe')

def search_client(client_name): # Creo una funcion para buscar un cliente
    global clients
    found = False
    if client_name in clients:
        found = True
    return found

def list_cleints(): # list_cleints muestra los clientesa que existen
    #global clients
    for idx , client in enumerate(clients):
        print(f'Clientes: {idx} - {client}')
   

def _print_welcome(): # Imprime un mensaje de bienvenida al usuario 
    print(' _________________________________________ ')
    print('|        Bievenido a Platzi Ventas        |')
    print('|-----------------------------------------|')
    print('|[C] - Crear cliente                      |')
    print('|[E] - Eliminar cliente                   |')
    print('|[A] - Actualizar cliente                 |')
    print('|[B] - Buscar cliente                     |')
    print('|[L] - Lista                              |')
    print('|[S] - Salir                              |')
    print('|_________________________________________|')
    
    global command
    command = None
    while not command:
        command = input('Ingresa una opcion: ').upper()

        if command in ['C','E','A','B','L','S']:    
            return _get_client_action(command) # Retorno la funcion principal para que sea ejecutada y se la paso a _get_client_action
        
       
def _get_client_action(command): # Creo una Función para ejecutar las acciones de los clientes
      
    if command == 'C':
        list_cleints()
        client_name = _get_client_name()
        create_client(client_name)
        list_cleints()

    elif command == 'E':
        list_cleints()  
        client_name = _get_client_name()
        delete_client(client_name)
        list_cleints()
        pass

    elif command == 'A':
        list_cleints()
        client_name = _get_client_name()
        update_client_name = input('Ingresa el nuevo nombre del cliente: ')
        update_client(client_name ,update_client_name)
        list_cleints()
        

    elif command == 'B':
        list_cleints()
        client_name = _get_client_name()
        found = search_client(client_name)
        if found:
            print(f'El cliente {client_name} se encuentra en la lista')
        else:
            print(f'El cliente {client_name} no se encuentra en la lista')
        list_cleints()
    
    elif command == 'L':
        list_cleints()
        
    
    elif command == 'S':
        print('Saliendo...')
        sys.exit()
        
    else:
        print('                                         ')
        print(' __________Comando no encontrado__________')
      
        _print_welcome()

def _get_client_name(): # Creo una funcion para pedir el nombre del cliente
    client_name = None
    while not client_name:
        client_name = input('Ingresa el nombre del cliente: ')
        if client_name == '':
            client_name = None
            print('                                         ')
            print(' __________El nombre del cliente es requerido__________')
        
        if client_name == 'exit':
            client_name = None
            break

    if not client_name:
        sys.exit()

    
    return client_name


if __name__== '__main__':
    _print_welcome()```

Curso antiguo, pero bueno para repasar 😄 Genial

codigo actualizado

import sys

clients = ['pablo', 'ricardo']

def create_client(client_name):
    global clients

    if client_name not in clients:
        clients.append(client_name)
    else:
        print('the client is ready register')


def list_clients():
    for idx, client in enumerate(clients):
        print(f'{idx}: {client}')


def update_client(client_name,update_client_name):
    global clients
    if client_name in clients:
        index = clients.index(client_name)
        clients[index] = update_client_name
    else:
        print('client is not in client list')

def delete_client(client_name):
    global clients

    if client_name in clients:
        clients.remove(client_name)
    else:
        print('client is not in clients list')


def search_client(name_client):
    global clients

    for client in clients:
        if client != name_client:
            continue
        else:
            return True


def _print_welcome():
    print('welcome to platzi sells')
    print('*' * 50)
    print('what woul you like to do')
    print('[C]create client')
    print('[D]delete client')
    print('[U] update')
    print('[S] search client')

def _get_client_name():
    client_name = None

    while not client_name:
        client_name = input('what is the client name ')

        if client_name == 'exit':
            client_name = None
            break
    if not client_name:
        sys.exit()
    return client_name

if __name__ == '__main__':
    _print_welcome()

    command = input()
    command = command.upper()

    if command == 'C':
        client_name = _get_client_name() 
        create_client(client_name)
        list_clients()

    elif command == 'D':
        client_name = _get_client_name()
        delete_client(client_name)
        list_clients()

    elif command == 'U':
        client_name = _get_client_name()
        update_client_name = input('what is the updated client name')
        update_client(client_name,update_client_name)
        list_clients()

    elif command == 'S':
        client_name = _get_client_name()
        found = search_client(client_name)
        if found == True:
            print('the client is in the list')
        else:
            print(f'cant found the client {client_name} in our client list')
    else:
        print('invalid command')




otra forma de regrear lo valores


def list_clients():
    for idx, client in enumerate(clients):
        print(f'{idx}: {client}')
clients = ['Jorge', 'Isidro', 'David']
already = False

def create_client(name):

    global clients
    global already

    if name not in clients:

        clients.append(name.capitalize())

    else:
        
        already = True

        print('The client ' + name.capitalize() +  ' is already in the db')

        salto_de_linea()

    return clients


def read_clients():

    for i, client in enumerate(clients):

        print(str(i) + ': ' + client)

    


def update_clients(client, new_client = ''):

    global clients

    for i, name_client in enumerate(clients):

        if client != name_client:

            continue

        else:
            clients[i] = new_client

    salto_de_linea()

    list_updated()

    return clients



def delete_client(client):

    global clients

    for name_client in clients:

        if client not in name_client:
            continue

        else:

            clients.remove(client)
            print(client + ' deleted successfully!')

    return clients


def search_client(client_name):

    for client in clients:
        if client_name == client:
            return True
        else:
            continue


def salto_de_linea():

    print('\n')

def list_updated():

    print('These are the updated list of clients, with their ids')


def ciclo_create():

    global already

    while already == False:
        
        user = input('What is the name of the client? ').capitalize().strip()

        print(already)

        if user == 'Exit':

            break

        salto_de_linea()

        create_client(user)
        
        if  already != True:

            print('Client ' + user.capitalize() + ' created successfully!')

            salto_de_linea()

            list_updated()

            salto_de_linea()

            read_clients()

            salto_de_linea()

    if already:
        
        continuar = input('Do you want to continue?  Y/N ').upper().strip()

        already = False

        if continuar == 'Y':

            ciclo_create()
            salto_de_linea()

def run():

            
    print('Welcome to out database, what wouldyou like to do?')
    print('[C]reate client')
    print('[R]ead clients')
    print('[U]pdate client')
    print('[D]elete client')
    print('[S]earch client')

    salto_de_linea()

    user_choose = input('Choose a option: ').upper()

    salto_de_linea()

    if user_choose == 'C':

        ciclo_create()

        salto_de_linea()

        print('Thanks for use our services :D')

    elif user_choose == 'R':

        list_updated()

        read_clients()
    
    elif user_choose == 'U':
        
        global clients

        user = input('What client you want to update? ').capitalize().strip()

        salto_de_linea()

        if user in clients:

            new_client = input('What is the name of the new client? ').capitalize().strip()

            update_clients(user, new_client)

            # salto_de_linea()

            read_clients()

        else:
            print('The client is not in the database')

    elif user_choose == 'D':

        user_delete = input('What client do you want to delete? ').capitalize().strip()

        salto_de_linea()

        delete_client(user_delete)

        salto_de_linea()

        list_updated()

        read_clients()

    elif user_choose == 'S':

        client = input('What client do you want to search? ').capitalize().strip

        salto_de_linea()

        found = search_client(client)

        if found:

            print('The client ' + client + ' is in out database')

        else: 

            print('The client ' + client + ' is not in our database')

         
    else:
            print('Please enter a valid option')


if __name__ == '__main__':
    run()

Para tener una interfaz más agradable a la hora de ejecutar el programa, se puede hacer uso de las comillas triples para poder imprimir tal cual se mostrará en pantalla, en mi caso en la función _print_welcome() utilice el print de la siguiente manera:

print(f'''
             ___________________________________________________
            | ************************************************* |
            | ||||||||||||| Welcome to Ventas CRUD |||||||||||| |
            | ************************************************* |
            |___________________________________________________| 
            | What would you like to do today                   |
            | [C]reate client                                   |
            | [U]pdate client                                   |
            | [D]elete client                                   |
            | [S]earch client                                   |
            | [Q]uit for Ventas CRUD                            |
            |---------------------------------------------------|
             
        This is de current list:
        {list_clients()}                     
            ''')

Excelente explicación del cambio a listas y su manejo básico para su uso.

Una forma mucho más legible de usar el format:

def list_clients():
  for idx, client in enumerate(clients):
    print(f'{idx}: {client}')
mucho mas legible con listas, que con strings 😁

Para que no se perdiera información y poder validar todas las funciones del CRUD, cree el siguiente loop (ver codigo) lo comparto por si alguien lo quiere probar

def presentacion():
    while True:
        print('*****************************')
        print('* SISTEMA BUSQUEDA CLIENTES *')
        print('*****************************')
        print('')
        print('[C]rear Cliente')
        print('[L]istar Clientes')
        print('[A]ctualizar Cliente')
        print('[E]Liminar Cliente')
        print('[B]uscar Cliente')
        print('[S]alir')
        
        opcion = input('Por favor eliga una opción: ')
        print('')
        opcion = opcion.upper()
        
        if opcion in ['C', 'L', 'A', 'E', 'B', 'S']:
            return opcion
        else:
            input('!ALERTA¡ \nACABAS DE INGRESAR UN VALOR NO VALIDO\nPresiona ENTER para continuar\n')



# ******************** #
# Inicio del Programa #
# ****************** #
if __name__ == '__main__':
    
    while True:

        op = presentacion()
        # *****************************
        if op == 'C':#rear Clientes
        
            while True:
                nombre_cliente = str.capitalize(input('Ingrese el nombre del cliente: '))

                if nombre_cliente.isdigit():
                    print('!Este campo solo acepta texto¡\n')
                elif len(nombre_cliente) == 0:
                    print('!El campo se encuentra vacio¡\n')
                else:
                    break
            
            crear_usuario(nombre_cliente)
        
        # ****************************
        elif op == 'L':#Listar Clientes
            listar_usuario()
        
        # ****************************
        elif op == 'A':#Actualizar Clientes
            while True:
                nombre_buscar = str.capitalize((input('Ingrese el nombre del cliente Actualizar: ')))

                if nombre_buscar.isdigit():
                    print('!Este campo solo acepta texto¡\n') 
                elif len(nombre_buscar) == 0:
                    print('!El campo se encuentra vacio¡\n')
                else:
                    break

            while True:
                nombre_actualizar = str.capitalize((input('Ingrese el nuevo nombre: ')))

                if nombre_actualizar.isdigit():
                    print('!Este campo solo acepta texto¡\n') 
                elif len(nombre_actualizar) == 0:
                    print('!El campo se encuentra vacio¡\n')
                else:
                    break
                

            actualizar_cliente(nombre_buscar, nombre_actualizar)

        # ****************************
        elif op == 'E':#Eliminar Clientes
            while True:
                nombre_eliminar = str.capitalize((input('Ingrese el nombre del cliente a Eliminar: ')))
                
                if nombre_eliminar.isdigit():
                    print('!Este campo solo acepta texto¡\n') 
                elif len(nombre_eliminar) == 0:
                    print('!El campo se encuentra vacio¡\n')
                else:
                    break
            
            eliminar_usuario(nombre_eliminar)

        # ****************************
        elif op == 'B':#Buscar Clientes
            while True:            
                nombre_cliente = str.capitalize((input('Ingrese el nombre a Buscar: ')))
            
                if nombre_cliente.isdigit():
                    print('!Este campo solo acepta texto¡\n') 
                elif len(nombre_cliente) == 0:
                    print('!El campo se encuentra vacio¡\n')
                else:
                    break
            
            buscar_usuario(nombre_cliente)
        # ******************************
        elif op == 'S':#Salir del programa
            print('Ha salido del programa correctamente')
            print('!FIN¡')
            break
        else:
            break

El maestro Aroesti es de los mejores profesores de Platzi, en cada curso se le nota la pasión por esto, pero en particular este curso me esta permitiendo entender muy bien Python y todo su uso, gran curso hasta ahora.

Utilizando el metodo help encontre que get() tiene a None como segundo parametro default, por lo que no es necesario pasarlo al llamarlo

Por que en unos metodos se usa global y en otros no para alcanzar la variable clients?

Así quedó mi código actualizado

import sys

clientes = ['Pedro','Pablo']

def crear_cliente(nombre_cliente):
    global clientes

    if nombre_cliente not in clientes:
        clientes.append(nombre_cliente)
    else:
        print("El cliente ya existe en la lista")


def listar_clientes():
    global clientes

    for indice, cliente in enumerate(clientes):
        print("{} : {}".format(indice+1, cliente))


def actualizar_ciente(nombre_cliente, nombre_cliente_nuevo):
    global clientes

    if(nombre_cliente in clientes):
        clientes[clientes.index(nombre_cliente)] = nombre_cliente_nuevo
        listar_clientes()
    else:
        print("el cliente {} no existe en el listado".format(nombre_cliente))


def _print_bienvenido():
    print('*' * 50)
    print("Bienvenido")
    print('*' * 50)
    print("¿Qué quieres hacer hoy?")
    print("A - Actualizar cliente")
    print("B - Borrar cliente")
    print("C - Crear cliente")
    print("E - Encontrar cliente")
    print("L - Listar clientes")
    print("S - Salir")


def _obtener_nombre_cliente_existente():
    return _obtener_input("Introduzca el nombre del cliente a actualizar: ")


def _obtener_nombre_cliente():
    return _obtener_input("Introduzca el nombre del cliente: ")


def _obtener_input(texto):
    input_text = None
    while not input_text:
        input_text =  input(texto)

        if input_text == 'salir':
            break

    return input_text


def _borrar_cliente(nombre_cliente):
    global clientes

    if nombre_cliente in clientes:
        clientes.remove(nombre_cliente)
        listar_clientes()
    else:
        print("El cliente {} no existe en el listado".format(nombre_cliente)) 


def _encontrar_cliente(nombre_cliente):
    global clientes
    encontrado = False 

    for cliente in clientes:
        if(cliente != nombre_cliente):
            continue
        else:
            encontrado = True
            break
    return encontrado


if __name__ == '__main__':
    while True:
        _print_bienvenido()

        comando = input()
        comando = comando.upper()

        if comando == 'C':
            nombre_cliente = _obtener_nombre_cliente()
            crear_cliente(nombre_cliente)
            listar_clientes()
        elif comando == 'B':
            nombre_cliente = _obtener_nombre_cliente()
            _borrar_cliente(nombre_cliente)
        elif comando == 'L':
            listar_clientes()
        elif comando == 'A':
            nombre_cliente = _obtener_nombre_cliente_existente()
            nombre_cliente_nuevo = _obtener_nombre_cliente()
            actualizar_ciente(nombre_cliente, nombre_cliente_nuevo)
        elif comando == 'E':
            nombre_cliente = _obtener_nombre_cliente_existente()
            cliente_encontrado = _encontrar_cliente(nombre_cliente)
            if cliente_encontrado:
                print("Hemos encontrado a {}".format(nombre_cliente))
            else:
                print("Lo sentimos mucho, pero el cliente {} no se encuentra".format(nombre_cliente))
        elif comando == 'S':
            print("Muchas gracias por utilizar nuestro programa")
            sys.exit()
        else:
            print("Opción desconocida")

No es necesario que actualice los clientes con las comas, sólo podríamos reemplazar el valor

Codigo actualizado

import sys
clients = ["alyanna", "angel"]
var_client_name = None
nombre_cliente_actualizado = None

def create_client(client_name):
    global clients

    if client_name not in clients:
    	clients.append(client_name)
    else:
        print(f"Client {client_name} already in client's list")


def list_clients():
	global clients

	for idx, client in enumerate(clients):
		print(f"{idx} {client}")


def update_client(client_name,updated_client_name):
	global clients

	if client_name in clients:
		index = clients.index(client_name)
		clients[index] = updated_client_name
	elif client_name not in clients:
		_not_in_clients(client_name)


def delete_client(client_name):
	global clients

	if client_name in clients:
		clients.remove(client_name)


def search_client(client_name):
	for i in clients:
		if i == client_name:
			return True


def _get_client_name():
	global var_client_name

	while not var_client_name:
		var_client_name = input("What is the client name? ")
		
		if var_client_name == "exit":
			var_client_name = None
			break
	
	if not var_client_name:
		sys.exit()

	return var_client_name


def _client_name():
#con esta funcion evito declarar "var_client_name = _get_client_name" en todos los if 
	global var_client_name
	var_client_name = _get_client_name()


def _not_in_clients(client_name):
	global clients

	if client_name not in clients:
		 print(client_name, "is not in client's list")


def _print_welcome():
	print("WELCOME TO LA BOOTS VENTAS")
	print("*" * 50)
	print("What would yo like to do today?")
	print("[C]reate client")
	print("[R]ead client")
	print("[U]pdate client")
	print("[D]elete client")
	print("[S]earch client")


if __name__ == '__main__':
	_print_welcome()

	command = input()
	command = command.upper()

	if command == "C":
		_client_name()
		create_client(var_client_name)
		list_clients()
	elif command == "R":
		list_clients()
	elif command == "D":
		_client_name()
		_not_in_clients(var_client_name)
		delete_client(var_client_name)
		list_clients()
	elif command == "U":
		_client_name()
		if var_client_name in clients:
			while not nombre_cliente_actualizado:
				nombre_cliente_actualizado = input("What is the updated client name? ")
			update_client(var_client_name, nombre_cliente_actualizado)
			list_clients()
		else:
			_not_in_clients(var_client_name)
			list_clients()
	elif command == "S":
		_client_name()
		found = search_client(var_client_name)
		if found:
			print("The client: {} is in our client's list".format(var_client_name))
		else:
			print(f"{var_client_name} is not in our client's list")
	else:
		print("Invalid command, try again")

Para todos aquellos que esten sufriendo con la terminal de windows les recomiendo este video para trabajar con linux
https://www.youtube.com/watch?v=Cvrqmq9A3tA

import sys
clients = 'pablo, ricardo,'


def create_client(client_name):
    global clients

    if client_name not in clients:
        clients += client_name
        _add_comma()
    else:
        print('client already is in the client\'s list')


def list_clients():
    global clients

    print(clients)


def update_client(client_name, updated_client_name):
    global clients

    if client_name in clients:
        clients = clients.replace(client_name + ',', updated_client_name + ',')
    else:
        print(_get_not_in_list())

def delet_client(client_name):
    global clients

    if client_name in clients:
        clients = clients.replace(client_name + ',', '')
    else:
        print(_get_not_in_list())

def search_client(client_name):
    clients_list = clients.split(',')

    for client in clients_list:
        if client != client_name:
            continue
        else:
            return True


def _add_comma():
    global clients

    clients += ','

def _print_welcome():
    print('welocome to platzi ventas')
    print('*' * 50)
    print('what would you like to do today?')
    print('[C]reate client')
    print('[U]pdate client')
    print('[D]elate client')
    print('[S]earch')

def _get_client_name():
    client_name = None

    while not client_name:
        client_name = input('What is the client name?')

        if client_name == 'exit':
            client_name = None
            break

    if not client_name:
            sys.exit()

    return client_name


def _get_not_in_list():
    return input('client is nos in client list')

if __name__ == '__main__':
    _print_welcome()


    command = input()
    command = command.upper()

    if command == 'C':
        client_name = _get_client_name()
        create_client(client_name)
        list_clients()
    elif command == 'D':
        client_name = _get_client_name()
        delet_client(client_name)
        list_clients()
    elif command == 'S':
        client_name = _get_client_name()
        found = search_client(client_name)
        if found:
            print('the client is in the client\'s list')
        else:
            print('the client: {} is not in the client list'.format(client_name))
    elif command == 'U':
        client_name = _get_client_name()
        updated_client_name = input('whats the o¡updated client name?')
        update_client(client_name, updated_client_name)
        list_clients
    else:
        print('Invalid command')

los operadores de pertenencias funcionan en la lista

Mi código me da algunos errores. ¿Me puedes ayudar please?

Mi código:

<code>import sys

clients = ['luisa', 'juan']

def create_client(client_name):
	global clients

	if client_name not in clients :
		clients.append(client_name)
	else:
		print ('Client already is in the client\'s list')

def list_clients():
	for idx, client in enumerate(clients):
		print ('{} : {}'.format(idx, client))


def updated_client(client_name, updated_client_name):
	global clients

	if client_name in clients :
		index = clients.index(client_name)
		clients[index] = updated_name
	else:
		print ('Client is no it client\'s list')


def delete_client(client_name):
	global clients

	if client_name in clients:
		clients.remove(client_name)
	else:
		print('Client is not in client\'s list')

def search_client(client_name):

	for client in clients:
		if client != client_name:
			continue
		else:
			return True


def _print_welcome():
	print ('WELCOME TO PLATZI VENTAS')
	print ('*' * 50)
	print ('What would you like to do today ? ')
	print ('[C]reate client')
	print ('[L]ist client')
	print ('[U]pdated client')
	print ('[D]elete client')
	print ('[S]earch client')


def _get_client_name ():
	client_name = None

	while not client_name:
		client_name = str.lower(input('What is the client name ? '))

		if client_name == 'exit':
			client_name = None
			break

	if not client_name:
			sys.exit()

	return client_name

if __name__ == '__main__':
	_print_welcome()

	command = input()
	command = command.upper()

	if command == 'C':
		client_name = _get_client_name()
		create_client(client_name)
		list_clients()
	elif command == 'L':
		list_clients()
	elif command == 'U':
		client_name = _get_client_name()
		updated_name = str.lower(input ('What is the updated client name ? '))
		updated_client(client_name, updated_name)
		list_clients()
	elif command == 'D':
		client_name = _get_client_name()
		delete_client(client_name)
		list_clients()
	elif command == 'S':
		client_name = _get_client_name()
		found = search_client(client_name)

		if found:
			print('The client is in the client\'s list')
		else:
			print('The client: {} is not in our client\'s list'.format(client_name))

	else:
		print ('Invalid command')

Primer error:
Al ejecutar el programa. Me salta el menú pero al introducir cualquier letra del menú debo introducir las ’ + la letra sino me da error. Aquí el error:
WELCOME TO BARCKCODE CLIENTS


What would you like to do today?
[C]reate client
[L]ist clients
[U]pdate client
[D]elete client
[S]earch client
C
Traceback (most recent call last):
File “main.py”, line 90, in <module>
command = input()
File “<string>”, line 1, in <module>
NameError: name ‘C’ is not defined

Sin embargo si pongo ‘C’ si funciona:
WELCOME TO BARCKCODE CLIENTS


What would you like to do today?
[C]reate client
[L]ist clients
[U]pdate client
[D]elete client
[S]earch client
’C’
What is the client name?

El código con algunas modificaciones que a mi parecer hace que se lea mejor:

import sys

clients = ['pablo', 'ricardo']

def welcome():
        print('Welcome!',
              '*'*20,
              'What would you like to do?',
              'C -> Create client',
              'U -> Update client',
              'D -> Delete client',
              'S -> Search client',
              '>>>',
              sep='\n', end=' ')


def list_clients():
    """List the clients joined to his id """
    global clients # Take global variable clients to use it
    clients = [client.capitalize() for client in clients]
    for idx, client in enumerate(clients):
        print('{id}: {cl}'.format(id=idx, cl=client))

def create_client(client_name):
    """Add an element client_name to the list clients"""
    global clients
    client_name = client_name.lower()

    if client_name not in clients:
        clients.append(client_name) # Add element client_name to the list
    else:
        print('{client} is already in the client\'s list'.format(client=client_name))

def update_client(client_name):
    """Change a client from clients to another given by the user"""
    global clients
    client_name = client_name.lower()

    if client_name in clients:
        updated_client_name = input('What is the updated client name:\n>>> ')
        client_index = clients.index(client_name)
        clients[client_index] = updated_client_name
        return
    print('Client is not in client\'s list')

def delete_client(client_name):
    """Delete the element client_name from the list clients"""
    global clients
    client_name = client_name.lower()

    if client_name in clients:
        clients.remove(client_name)
        return
    print('Client is not in client\'s list')

def search_client(client_name):
    global clients
    client_name = client_name.lower()

    if client_name in clients:
        print('The client is in the client\'s list')
        return
    print('The client: {} is not in the client\'s list'.format(client_name))

def _get_client_name():
    """Throw an input to get the client name"""
    client_name = None
    
    #Repeat the function until the user responds
    while not client_name:
        client_name = input('What is the client name?:\n>>> ')
        # Turn off the program if the client_name is exit
        if client_name == 'exit':
            sys.exit()
    return client_name

if __name__ == '__main__':
    welcome()

    user_decision = input()
    user_decision = user_decision.upper()

    if user_decision == 'C':
        client_name = _get_client_name()
        create_client(client_name)
        list_clients()
    elif user_decision == 'D':
        client_name = _get_client_name()
        delete_client(client_name)
        list_clients()
    elif user_decision == 'U':
        client_name = _get_client_name()
        update_client(client_name)
        list_clients()
    elif user_decision == 'S':
        client_name = _get_client_name()
        search_client(client_name)
    else:
        print('Invalid command')

Yo realicé otros dos métodos, quizá no ayudan mucho en este proyecto porque es muy poco su uso, pero en proyectos con listas muy grandes y búsquedas muy rutinarias son de más ayuda.
def _notExists():
print(‘Course does not exists’)
def _doesExists():
print(‘Course already exists’)
Esto se sustituye por cada print(‘Course already in course’s list’)
*Yo estoy haciendo mi CRUD de unos cursos , por eso no dice clients.

Tengo una consulta, el uso keyword global¿es innecesario cuando utilizamos objetos de tipo lista?

Comenté todos los global clients del código, y todo funciona normal.

Aquí mi código:

Si quieren profundizar mas sobre las listas aquí les dejo la documentación de python en español sobre esta estructura de datos, tiene pequeños ejemplos de como y para que funcionan sus métodos, se los recomiendo no solo para las listas, si no para complementar todo el curso
http://docs.python.org.ar/tutorial/2/datastructures.html

tengo problemas con el append

<def create_client(client_name):
    global clients

    if client_name not in clients:
        clients.append('client_name')
    else:
        print(client_name, ' ya esta creado')>

me saca este error
AttributeError: ‘str’ object has no attribute ‘append’

Por si las dudas index —> busca los elementos de una lista y te devuelve la posicion de cada uno de ellos.

import sys

clients= ['pablo','ricardo']


def create_client(client_name):
    global clients

    if client_name not in clients:
        clients.append(client_name)
        #_add_comma() # en lista ya no sirve
    else:
        print('Client already is in the client\'s list ')

def list_clients():
    global clients
    for idx,client in enumerate(clients):
        print('{}:{}'.format(idx,client))


def update_client(client_name,updated_client_name):
    global clients

    if client_name in clients:
        index=clients.index(client_name)
        #clients=clients.replace(client_name+',',updated_client_name+',')
        clients[index]=updated_client_name
    else:
        pass
        #print('Client is not in clients list')

def delete_client(client_name):
    global clients

    #_exist_client(client_name)
    Exist_client= _exist_client(client_name)
    print(Exist_client)
    if Exist_client==True :
        #index=clients.index(client_name)
        clients.remove(client_name)
        #clients[index]=clients.replace(client_name+',','')

def search_client(client_name):

    for client in clients:
        if client != client_name:
            continue
        else:
            return True




def _exist_client(client_name):
    global clients
    #print (clients)
    #print(client_name)
    val=client_name in clients
    #print(val)
    if val == True:
        return True
    else:
        print('The Client: '+client_name+' is not in clients list')
        return False

def _empty_client(client_name,value):

    while not client_name:
        client_name=_get_input_action(value)

    return client_name



def _print_welcome():
    print('WELCOME TO BOLTA VENTAS')
    print('*'* 50)
    print('What would you like to do today?')
    print('[C]reate client')
    print('[L]ist clients')
    print('[U]pdate client')
    print('[D]elete client')
    print('[S]earch client')
    print('[E]xit(SALIR)')

#def _get_client_name():
#    return input('what is the client name?')

#def _get_updated_client_name():
#    return input('what is the updated client name?')

def _get_input_action(value):
    action = None
    name_local=None

    if value == 1:
        action=input('what is the client name?')
        name_local=action
        action=_empty_client(action,value)
        #_exist_client(action)

    elif value == 2:
        action=input('what is the updated client name?')
        name_local=action
        action=_empty_client(action,value)
        #_exist_client(action)
    else:
        action=print('Invalid value for input action')

    if name_local =='exit':
        print(name_local)
        sys.exit()

    return action


def _menu():
    _print_welcome()
    command=input()
    command=command.upper()

    if command == 'C':
       client_name =_get_input_action(1)
       _exist_client(client_name)
       create_client(client_name)
       list_clients()

    elif command == 'L':
        list_clients()

    elif command == 'D':
       list_clients()
       client_name = _get_input_action(1)
       delete_client(client_name)
       list_clients()
    elif command == 'U':
        list_clients()
        client_name = _get_input_action(1)#_get_client_name()
        cli_exist =_exist_client(client_name)

        if cli_exist == True:
            updated_client_name = _get_input_action(2)#_get_updated_client_name()
            _exist_client(updated_client_name)
            update_client(client_name,updated_client_name)
            list_clients()
        else:
            pass


       #list_clients()
    elif command == 'S':
        client_name= _get_input_action(1)
        _exist_client(client_name)
        found=search_client(client_name)

        if found:
            print('Client already is in the client\'s list ')


    elif command == 'E':
        sys.exit()
    else:
        print('Invalid command')


    return command






if __name__ == '__main__':

    com = 1
    while com > 0:
        _menu()

pueden poner este enunciado en la primera linea de su codigo ‘#!/usr/bin/env python3’, y darle permisos de ejecucion chmod u+x con lo cual podran ejecutar el codigo directamente ./codigo.py

La lista en Python son variables que almacenan arrays, internamente cada posición puede ser un tipo de datos distinto.

>>> factura = ['pan', 'huevos', 100, 1234]
>>> factura
['pan', 'huevos', 100, 1234]```

Here is my code

<code>

clients = ['Pablo', 'Ricardo']


def create_client(client_name):
    global clients
    if client_name not in clients:
        clients.append(client_name)
        _print_result(1)
    else:
        _print_not_in_list(2)


def update_client(client_name, update_client_name):
    global clients
    if client_name in clients:
        index = clients.index(client_name)
        clients[index] = update_client_name
        _print_result(1)
    else:
        _print_not_in_list(1)


def delete_client(client_name):
    global clients
    if client_name in clients:
        clients.remove(client_name)
        _print_result(1)
    else:
        _print_not_in_list(1)


def list_clients():
    global clients
    print('-'*50)
    print('')
    print('Clients are: ')
    for idx, cliente in enumerate(clients):
        print('{}:{}'.format(idx, cliente))
    print('')


def search_cliente(client_name):
    for client in clients:
        if client != client_name:
            continue
        else:
            return True


def _add_comma():
    global clients
    clients += ','


def _print_not_in_list(state):
    if(state == 1):
        print('')
        print('//Client isn\'t in the list//')
        print('')
    if(state == 2):
        print('')
        print('//Client already in the list//')
        print('')


def _print_search(state, client_name):
    if state:
        print('')
        print('Cliente {}, already in the List'.format(client_name))
        print('')
    else:
        print('')
        print('Cliente {}, isn\'t in the List'.format(client_name))
        print('')


def _print_result(state):
    if(state == 1):
        print('')
        print('SUCCESS'.center(50, '='))
        print('')
    if(state == 2):
        print('')
        print('Error'.center(50, '!'))
        print('')


def _print_welcome():
    print('')
    print('*'*50)
    print('Welcome To Javii Ventas')
    print('*'*50)
    print('What would you like to do today?')
    print('   [C]reate Client       ')
    print('   [R]ead Client List    ')
    print('   [U]pdate Client       ')
    print('   [D]elete Client       ')
    print('   [S]earch Client        ')
    print('*'*50)
    print('   [E]xit                ')
    print('')


def _print_option():
    print('*'*50)
    return input('What is the client name?   ').capitalize()


def _print_option_update():
    print('*'*50)
    return input('What is the NEW client name?   ').capitalize()


def main_menu():
    while True:
        _print_welcome()
        command = input()
        command = command.upper()
        if command == 'C':
            client_name = _print_option()
            create_client(client_name)
            list_clients()
        elif command == 'R':
            list_clients()
        elif command == 'D':
            client_name = _print_option()
            delete_client(client_name)
            list_clients()
        elif command == 'U':
            client_name = _print_option()
            update_client_name = _print_option_update()
            update_client(client_name, update_client_name)
            list_clients()
        elif command == 'S':
            client_name = _print_option()
            found = search_cliente(client_name)
            _print_search(found, client_name)
        elif command == 'E':
            print("GOOD BYE".center(50, '='))
            print('')
            break
        else:
            print('Invalid Command'.center(50, '='))
            print('')


if __name__ == '__main__':
    main_menu()


Alguien me puede ayudar con mi programa?
Lo que quiero hacer es modificar un valor que ya esta en una lista, pero accediendo a ese valor a traves de su indice y que se guarde el nuevo valor en el lugar que estaba el anterior valor. Aqui dejo el codigo y el problema seria en la funcion update()


solds_daily = [100, 200, 25, 35.3, 49.7, 65.14]

def daily_sales():
    solds = float(input("Ingrese el monto obtenido: $"))
    solds_daily.append(solds)
    print(solds_daily)
    print("Desea hacer otra accion? (Si/No)")
    option = input()
    option = option.lower()

    option_question(option)


def option_question(option):
    if option == "si":
        daily_sales()
    elif option == "no":
        funtion_principal()
    else:
        print("Opcion invalida")



def total_day():
    print("El total hasta ahora es: $", sum(solds_daily))
    funtion_principal()
    

def list_solds():
    print("Las ventas detalladas son:")
    for idx, solds in enumerate(solds_daily):
        print("{}: {}".format(idx, solds))
    funtion_principal()


def update_sold():
    print("")
    print("Aqui estan los valores:")
    print("")

    for idx, solds in enumerate(solds_daily):
        print("{}: {}".format(idx, solds))
    
    update()


def update():
    print("")
    value = int(input("Selecciona el indice del valor a modificar: "))
    idx = solds_daily[value]

    if idx in solds_daily:
        index = solds_daily.index(float(input("Ingrese el nuevo valor: $")))
        solds_daily[index] = solds
        # new_value = float(input("Ingrese el nuevo valor: $"))
        # solds_daily[idx] = new_value
        funtion_principal()
    else:
        print("No se encuentra ese indice.")
        funtion_principal()


def _welcome_initial():
    print("B I E N V E N I D O !")
    print(" ")
    print('''Elige una opcion:
        [V]entas diarias
        [T]otal del dia
        [D]etalles de las ventas
        [M]odificar algun ingreso
        [S]alir
    ''')


def _welcome_second():
    print(" ")
    print('''Elige una opcion:
        [V]entas diarias
        [T]otal del dia
        [D]etalles de las ventas
        [M]odificar algun ingreso
        [S]alir
    ''')
    

def initial_program():
    option = input()

    command = option.upper()


    if command == "V":
        daily_sales()
    elif command == "T":
        total_day()
    elif command == "S":
        print(" ")
        print("Saludos!")
    elif command == "D":
        list_solds()
    elif command == "M":
        #value = value_modificate()
        update_sold()
    else:
        print(" ")
        print("No existe esa opcion")


def funtion_principal():
    _welcome_second()
    initial_program()


if __name__ == "__main__":
    _welcome_initial()
    initial_program()

share my code

import sys 

clients = ['pablo', 'ricardo']

def create_client(client_name):
    global clients
    if client_name not in clients:
        clients.append(client_name)
    else:
        get_message_client_exist(True)

def list_clients():
    for idx, client in enumerate(clients):
        print('{}: {}'.format(idx,client))

def update_client(client_name, updated_name):
    global clients

    if client_name in clients:
        index = clients.index(client_name)
        clients[index] = updated_name
    else:
        get_message_client_exist(False)

def delete_client(client_name):
    global clients

    if client_name in clients:
        clients.remove(client_name)
    else:
        get_message_client_exist(False)


def search_client(client_name):
    for client in clients:
        if client != client_name:
            continue
        else:
            return True


""" def _add_comma():
    global clients

    clients += ',' """

def _get_client_name():
    client_name = None

    while not client_name:
        client_name = input('What is the client name?')

        if client_name =='exit':
            client_name = None
            break 
        
    if not client_name:
        sys.exit()

    return client_name

def get_message_client_exist(mod):
    if (mod):
        return print('Client already in client\'s list')
    else:
        return print('Client not in client\'s list')


def _print_welcome():
    print('WELCOME TO PLATZI VENTAS')
    print('*'*50)
    print('What would you like to do today?')
    print('[C]reate client')
    print('[L]ist client')
    print('[U]pdate client')
    print('[D]elate client')
    print('[S]earch client')


if __name__ == '__main__':
    _print_welcome()
    
    command = input()
    command = command.upper()

    if command == 'C':
        client_name = _get_client_name()
        create_client(client_name)
        list_clients()

    elif command == 'L':
        list_clients()

    elif command == 'D':
        client_name = _get_client_name()
        delete_client(client_name)
        list_clients()

    elif command == 'U':
        client_name = _get_client_name()
        updated_name = input('What is the new client name?')
        update_client(client_name, updated_name)
        list_clients()
    elif command == 'S':
        client_name = _get_client_name()
        found = search_client(client_name)
        if found:
            print('The client is in the client\'s list')
        else:
            print('The client: {} is not in out client\'s list'.format(client_name))
    else:
        print('Invalid command')

Mi codigo hasta el momento:

import sys

clients= ['Pablo', 'Ricardo']

def create_client(client_name):
    global clients

    if client_name not in clients:
        clients.append(client_name)
    
    else:
        print("Client is already in the client's list")


def list_clients():
    for idx, client in enumerate(clients):
        print(' {}: {}'.format(idx, client))

def update_client(client_name,update_client_name):
    global clients

    if client_name in clients:
        index = clients.index(client_name)
        clients[index] = update_client_name
    else:
        _client_not_in_list ()


def delete_client(client_name):
    global clients

    if client_name in clients:
        clients.remove(client_name)
    else:
        _client_not_in_list ()


def search_client(client_name):
    for client in clients:
        if client != client_name:
            continue
        else:
            return True 

            
def _get_client_name():
    client_name = None

    while not client_name:
        client_name = input('What is the client name? ')

        if client_name == 'exit':
            client_name = None
            break
        
    if not client_name:
        sys.exit()

    return client_name
    

def _client_not_in_list ():
    return print("Client is not in client's list")

def _print_welcome():
    print('WELCOME TO PLATZI VENTAS')
    print('*' * 50)
    print('What would you like to do today?')
    print('[C]reate client')
    print('[D]elete client')
    print('[U]pdate client')
    print('[S]earch client')



def run():
    _print_welcome()

    command = (input('Please, enter your choice: '))
    command = command.upper()

    if command == 'C':
        client_name = _get_client_name ()
        create_client(client_name)
        list_clients()
    
    elif command == 'D':
        client_name = _get_client_name ()
        delete_client (client_name)
        list_clients()
    elif command == 'U' :
        client_name = _get_client_name ()
        update_client_name = input('What is the updated client name? ')
        update_client(client_name, update_client_name)
        list_clients ()
    elif command == 'S':
        client_name = _get_client_name ()
        found = search_client (client_name)

        if found:
            print("The client is the client's list")
        else:
            print("The client : {} is not in our client's list" .format(client_name))
       
    else:
        print('Invalid command')


if __name__ == '__main__':
    run()

wooo exclente que bien ome

Así va el código:

import sys

'''
A Pythobn Project to develop a CRUD(create, read, update, delete)
'''

clients = ['Pablo','Ricardo']

# Función que añade un nuevo cliente a la variable clients
def create_client(client_name):
    global clients              # La función global aumenta el alcance de la función y permite 
                                # utilizar     la variable clients
    if client_name not in clients:
        clients.append(client_name)
    else:
        print("\nClient already is in the client's list\n")


# Función que imprime la lista de clientes
def list_clients():
    global clients
    for idx, client in enumerate(clients):
        print(f' >>> Client {idx}, {client}\n')


# Función que actualiza el nombre del cliente
def update_client(client_name):
    global clients

    if client_name in clients:
        updated_client_name = input(f"\n\t> UPDATE < the client's name\n\tWhat is the new client name?: ")
        index = clients.index(client_name)
        clients[index] = updated_client_name
    else:
        print(f"\n\tXX This name is not in the client's list XX\n")


# Función que borra el nombre de un cliente en la lista
def delete_client(client_name):
    global clients

    if client_name in clients:
        clients = clients.remove(client_name)
        print(f'Client deleted succesfully')
        list_clients()
    else:
        print(f"\n\tXX This name is not in the client's list XX\n")


def search_client(client_name):
    # No se agrega clients como variable global pues solo se leerá no modificará.

    for client in clients:
        if client != client_name:
            continue
        else:
            return True


# # Creación de función privada que será auxiliar para separar por comas los nombres
# def _add_comma():
#     global clients
#     clients += ','


def _print_welcome():
    print(f'\n {"*" * 50}')
    print(f'\n\t\tWELCOME TO THE ECOMMERCE')
    print(f'\n\t\tCLIENT MANAGMENT SYSTEM')
    print(f'\n {"*" * 50}')
    print(f'\n {"*" * 50}')
    print(f'\n What would you like to do today?:')
    print(f'\n\t\t [C]reate client')
    print(f'\n\t\t [U]pdate client')
    print(f'\n\t\t [D]elete client')
    print(f"\n\t\t [P]rint list")
    print(f"\n\t\t [S]earch client")



def _get_client_name():
    client_name = None

    while not client_name:
        client_name = input(f'\n\tWhat is the client name?:').strip().title()

        if client_name == 'exit':
            client_name = None
            break

    if not client_name:
        sys.exit()
    return client_name


if __name__ == '__main__':
    _print_welcome()

    command = input(f'\n\tChoose an option from above C/D/U/P/S: ')
    command = command.upper()

    if command == 'C':
        client_name = _get_client_name()
        create_client(client_name)
        list_clients()
    
    elif command == 'D':
        client_name = _get_client_name()
        delete_client(client_name)
        list_clients()
        

    elif command == 'U':
        client_name = _get_client_name()
        update_client(client_name)
        list_clients()
    
    elif command == 'P':
        list_clients()

    elif command == 'S':
        client_name = _get_client_name()
        found = search_client(client_name)
        if found == True:
            print(f'The client {client_name} is in the list.')
        else:
            print(f'The name {client_name}is not in the client\'s list')

    else:
        print('Invalid command')

El for de la función search_client se puede reemplazar por:

return False if ''.join(clients).find(client_name) == -1 else True

‘’.join(list) transforma la lista en una cadena.
str.find(value) devuelve -1 si el value no es encontrado en la cadena.

Excelente, que buen ejercicio

import sys

clients = ['pablo','ricardo']


def create_client(client_name):
    global clients

    if client_name not in clients:
        clients.append(client_name)
    else:
        print('Client already is in the client\'s list')


def list_clients():
    global clients

    for idx, client in enumerate(clients):
        print('{}: {}'.format(idx, client))


def update_client(client_name, updated_client_name):
    global clients

    if client_name in clients:
        index = clients.index(client_name)
        clients[index] = updated_client_name
    else:
        _print_message_client()


def delete_client(client_name):
    global clients

    if client_name in clients:
        clients.remove(client_name)
    else:
        _print_message_client()


def seach_client(client_name):
    global clients

    for client in clients:
        if client != client_name:
            continue
        else:
            return True