Home > Software design >  Using a Python module
Using a Python module

Time:06-21

I am trying to import the students.py module and call it in another to print out values of the dictionary in that module but it is not working. Where am I going wrong?

Here is students.py

def person1():
  student1 = {
  "name": "Joe",
  "major": "Programming",
  "format": "Campus Live"
  }

Here is the file am calling that module from

import students
x = students.person1("major")
y = students.person1("name")
print(x)
print(y)

I would like it to print the major which is programming and name Joe. They are 2 different .py files remember. Am still new to python

CodePudding user response:

It would be helpful, to also post the error.

(I am also new to python).

But your person1() is a function, but has no return value. I think, what you're looking for, is a class.

class person():
  def __init__(self, name, major, format_):
    self.name = name
    self.major = major
    self.format_ = format_

p1 = person("John", "Programming", "Campus Live")


print(p1.name)
print(p1.major)
print(p1.format_)

this return:

John
Programming 
Campus Live

Adapted from here: https://www.w3schools.com/python/python_classes.asp

Maybe some other people go a bit more into detail, but maybe this helps you to find the correct answer, you're looking for

EDIT:

Or if you have a list of predefined students, you can go for a (nested) dictionary:

students = {
  "student1" : {
  "name": "Joe",
  "major": "Programming",
  "format": "Campus Live"
  },
   "student2" : {
   "name" : "Jane",
   "major" : "Economics",
   "format" : "Offline Campus"}
}

print(students["student1"]["name"])
print(students["student1"]["major"])
print(students["student1"]["format"])

best Christian

CodePudding user response:

You are passing values to a function but it doesn't really take arguments right now. Also you are trying to get any values from a function which doesn't return any values when you call it, so you need to add return keyword with needed value from a dictionary.

So here is the code that will make your function working as you want

def person1(name):
  student1 = {
  "name": "Joe",
  "major": "Programming",
  "format": "Campus Live"
  }
  return student1[name]
  • Related