I have this code which returns a Nonetype, when I thought it would return a string. And I have been trying to find solutions on stack, but I am yet to find one.
Here is the code:
members = ['Alex', 'Danny', 'Kieran', 'Zoe', 'Caroline']
visitors = ['Scott', 'Helen', 'Raj', 'Danny']
def check_group(members, visitors):
for person in visitors:
if person in members:
print(f"Member present: {person}")
break
else:
print("No members visited")
output: Member present: Danny
You have forgottent a sin when typing members line 2.
Also, your code won't return anythings, just print the value you asked it to print.
You need to have a return statement.
So if this is part of a function then it should be something like this
def find():
members = ['Alex', 'Danny', 'Kieran', 'Zoe', 'Caroline'] visitors = ['Scott', 'Helen', 'Raj', 'Danny']
for person in visitor:
if person in member:
print(f"Member present: {person}")
retrun person
else:
print("No members visited")
return None
Related
contacts = {'John Smith': '1-123-123-123',
'Jane Smith': '1-102-555-5678',
'John Doe': '1-103-555-9012'}
def add_contact(contacts, name, number):
"""
Add a new contact (name, number) to the contacts list.
"""
if name in contacts:
print(name, "is already in contacts list!")
else:
contacts[name] = number
print(add_contact(contacts, 'new_guy', '1234'))
When I print this I get none
but if I add another line print(contacts)
it will give me a none and the new dictionary with 'new_guy' :'1234'. What is the correct way to print out the new dictionary without printing none?
You're adding to the dictionary correctly. Yor print statement is the issue.
Change this:
print(add_contact(contacts, 'new_guy', '1234'))
You need to separate this out some.
add_contact(contacts, 'new_guy', '1234')
print(contacts)
Also, since your contacts dictionary is declared globally, you don't need to pass it to the function should name it something different in the function for clarity. You could change the function to:
def add_contact(current_contacts, name, number):
But don't for get to change inside the function as well.
if name in current_contacts:
print(name, "is already in contacts list!")
else:
current_contacts[name] = number
The final code:
contacts = {'John Smith': '1-123-123-123',
'Jane Smith': '1-102-555-5678',
'John Doe': '1-103-555-9012'}
def add_contact(current_contacts, name, number):
"""
Add a new contact (name, number) to the contacts list.
"""
if name in current_contacts:
print(name, "is already in contacts list!")
else:
current_contacts[name] = number
add_contact(contacts, 'new_guy', '1234')
print(contacts)
The way you have it right now, you are printing what the function returns (which is none). All you need to do is separate your functional call and print statement like so:
add_contact(contacts, 'new_guy', '1234')
print(contacts)
def add_contact(name, number):
"""
Add a new contact (name, number) to the contacts list.
"""
if name in contacts:
print(name, "is already in contacts list!")
else:
contacts[name] = number
return contacts #put a return statement that will return the updated contacts dictionary
print(add_contact('John Doe', '1234'))
#for simplified version try a dictionary comprehension:
#using the dict.update(), we can use a comprehension inside to iterate from the contacts itself and have a condition if the name is already exists
contacts.update({key: value for key, value in contacts.items() if key not in contacts})
#tho, we can't have a print statement that will tell if the name already exist in the contacts
print(contacts)
>>>output: {'John Smith': '1-123-123-123', 'Jane Smith': '1-102-555-5678', 'John Doe': '1-103-555-9012'}
I have a dictionary of people's online statuses, and I am able to count the number of people who are online, but I want to show the names of the people who are online.
Example:
def online_count(people):
return len([person for person in people if people[person] == "online"])
statuses = {
"Alice": "online",
"Bob": "offline",
"Eve": "online",
}
print(online_count(statuses))
How do I show the names of the people who are online?
Do this:
def online_names(people):
return [name for name, status in people.items() if status == 'online']
Use items() to iterate over both the keys and values of the dictionary. Then you can return the keys when the value matches your criteria.
def online_people(people):
return [person for person, status in people.items() if status == "online"]
No need for a spurious list. You can also disregard keys completely for the count:
def online_count(people):
return sum(v == "online" for v in people.values())
For the names, you can do:
def online_names(people):
return [p for p in people if people[p] == "online"]
>>> online_count(statuses)
2
>>> online_names(statuses)
['Alice', 'Eve']
What I want to accomplish is to calculate the ranking of the most active users in a group.
My approach to it was to first iterate through all message history in a group, get the user name, assign the message to it and then sort it in python from highest (most often sent from a given user) to lowest, but I have no idea how to make it programmatically and I've been stuck in this code:
async def calculate_ranking(event):
#client.on(events.NewMessage)
async def calculate_ranking(event):
messages = {}
if "!ranking" in event.raw_text:
chat_id = event.chat_id
async for message in client.iter_messages(chat_id, reverse=True):
author = message.sender.username
messages[author] += 1
print(messages)
I have no idea on how to assign a message to a user
so the output would be as for example:
user1: 12 messages
user2: 10 messages
For the rank itself, you can use collections.Counter()
import collections
collections.Counter(['jon', 'alan', 'jon', 'alan', 'bob'])
# Output: Counter({'jon': 2, 'alan': 2, 'bob': 1})
So all you have left to do is to get the username.
# Your job! :)
data = dict(
username = ['jon', 'alan', 'jon', 'alan', 'bob'],
message = ['hello!', 'hey jon!', 'How are you doing?', 'Im fine', 'hola!']
)
Counter(data.username)
I am new to Python 2.7 and I want the 1st column as the key column in employees and it has to check on dept 1st column and generate results.
Employees comes from a text file and dept comes from a database. I tried a lot but didn't get an easy answer. What is wrong with my code?
**Inputs :**
employees=['1','peter','london']
employees=['2','conor','london']
employees=['3','ciara','london']
employees=['4','rix','london']
dept=['1','account']
dept=['2','developer']
dept=['3','hr']
**Expected Output :**
results=['1','peter','london','account']
results=['2','conor','london','developer']
results=['3','ciara','london','hr']
results=['4','rix','london',null]
your input makes no sense. Each line overwrites the previous one data-wise. Here it seems that the digits (as string) are the keys, and some default action must be done when no info is found in dept.
To keep the spirit, just create 2 dictionaries, then use dictionary comprehension to generate the result:
employees = dict()
dept = dict()
employees['1'] = ['peter','london']
employees['2'] = ['conor','london']
employees['3'] = ['ciara','london']
employees['4'] = ['rix','london']
dept['1']=['account']
dept['2']=['developer']
dept['3']=['hr']
result = {k:v+dept.get(k,[None]) for k,v in employees.items()}
print(result)
which yields a dictionary with all the info. Note that null is None in python:
{'1': ['peter', 'london', 'account'], '4': ['rix', 'london', None], '3': ['ciara', 'london', 'hr'], '2': ['conor', 'london', 'developer']}
You could go for a class. Consider this:
class Employee:
def __init__(self, number, name, location, dept):
self.number = str(number)
self.name = name
self.location = location
self.dept = dept
def data(self):
return [self.number,
self.name,
self.location,
self.dept]
peter = Employee(1, 'peter', 'london', 'account')
print(peter.data())
['1', 'peter', 'london', 'account']
>>>
Let's say I have a data item person with two properties, name and age, such that;
person
name
age
I want to return this to a caller, but am unsure of what method to use. My ideas so far are however:
A dictionary for each person placed in a list -- Have tried, the syntax to perform were a little tedious, also I got AttributeError
A class with two properties -- I don't even know how to go about this, nor if it even works
My code is looking something like this at the moment:
persons = []
for person in people: # "people" fetched from an API
persons = {
"name": "Foo"
"age": "Bar"
}
return persons
# And then to access returned result
for person in persons:
print(person["name"]) # Gives AttributeError
# DoMoreStuff
First of all - the error you are not returning a list of dicts. Just a single dict. Instead of appending your persons to the list you created, you replace the list with your persons. So if you try to iterate over it, you in fact iterate over the keys. What you wanted is probably:
persons.append({
"name": "Foo"
"age": "Bar"
})
Second of all: to get a "class with two properties" I would recommend looking on namedtuple. https://docs.python.org/3/library/collections.html#collections.namedtuple
zefciu is correct and I would like to expand on his idea. First of all, before dealing with a list of persons, you need to know how to work with a single person. There are three ways to represent a person: a dictionary, a class, and a namedtuple.
Dictionary
Given a person name (John) and age (32), you can represent a person as:
person = {'name': 'John', 'age': 32 } # or
person = dict(name='John', age=32)
You can then access this person's name as person['name'] and age as person['age'].
Class
You can define a person class, along with an initializer as:
class Person:
def __init__(self, name, age):
self.name = name
self.age = age
Now, you can create and access a person object:
person = Person('John', 32) # or
person = Person(name='John', age=32)
print('Name:', person.name)
print('Age:', person.age)
namedtuple
namedtuple is part of the collections library, so you need to import it. Here is how to define it:
from collections import namedtuple
Person = namedtuple('Person', ['name', 'age'])
To use it:
person = Person('John', 32) # or
person = Person(name='John', age=32)
print('Name:', person.name) # like a class
print('Name:', person[0]) # like a tuple
Populate a List
persons = []
for person in people:
name = ... # extract name from person
age = ... # extract age
persons.append(dict(name=name, age=age)) # For dictionary
persons.append(Person(name=name, age=age)) # For class or namedtuple