while loop in a python class [duplicate] - python

This question already has answers here:
Asking the user for input until they give a valid response
(22 answers)
Closed 6 years ago.
I am trying to incorporate a regex check for user input in my class. I want a scenario where users can't proceed to enter their name until they enter a valid email address. The current code i have isn't working as expected.
I suppose a while-loop is in order here but i am struggling to implement that in this class. Any assistance is much appreciated.
class test:
def __init__(self):
self.email = input("Enter your email: ")
email_check = re.search(r'[\w.-]+#[\w.-]+.\w+', self.email)
if email_check:
print ('email valid')
else:
print ('email not valid')
self.email = input("Enter your email: ")
sys.exit(0)
self.name = input("Enter your name: ")

You can do it like this.
while True:
self.email = input ("Enter email:")
if valid_email:
break
Substitute valid_email with your way of validating the email address.
You may also be interested in Python check for valid email address? for ways to validate an email address.

First of all - you should not implement any activity of this kind into __init__ method, as one is intended for object fields initialization first place. Consider dedicated 'check_email' method, or whatever name applies best.
Now, regarding your case:
class test:
def __init(self):
# whatever initialization applies
pass
def init_emails():
emails = []
proceed = True
# if you really in need of do/while loop
while proceed:
email = self.input_email()
# your logic for input
if email is not None:
emails.append(email)
# invalid input or cancel
else:
proceed = False
return input
def input_email(self):
value = input('Enter your email:')
# TODO: validate/check input
return proper_value

class test:
def __init__(self):
self.email = self.get_name()
def get_name(self) :
while True:
x = input("Enter your email: ")
if (re.search(r'[\w.-]+#[\w.-]+.\w+', x)) :
return x

This script functions as described, in the end printing the name and email. If you need to use python2.7, use raw_input instead of input. I used for i in range instead of while True to avoid an endless loop.
#!/usr/bin/env python3
import re
import sys
class Test(object):
def __init__(self):
self.email = None
self.name = None
def get_email(self):
for i in range(3):
email = input('Enter your email: ')
if re.search('[\w.-]+#[\w.-]+.\w+', email):
return email
print('Too many failed attempts!')
sys.exit(1)
def get_name(self):
for i in range(3):
name = input('Enter your name: ')
if name:
return name
print('Too many failed attempts!')
sys.exit(1)
def initialize(self):
self.email = self.get_email()
self.name = self.get_name()
print('"{}" <{}>'.format(self.name, self.email))
if __name__ == '__main__':
t = Test()
t.initialize()

Instead of input, try to use raw_input. Like this:
self.email = raw_input("Enter your email:")
There'll be no error anymore.
Hope this helps.

Related

How to Construct Method and Attributes using Dictionaries in Python

class print_values:
def __init__(self,username,user_email,displayname):
self.name= username
self.email=user_email
self.DisplayName=displayname
def printing_content(self):
print(f"UserName: {self.name}\n"
f"UserEmail: {self.email}\n"
f"UserDisplayName:{self.DisplayName}\n")
user_one={'username':'userone',
'useremail':'userone#gmail.com',
'displayname':'User One'}
user_two={'username':'usertwo',
'useremail':'usertwo#gmail.com',
'displayname':'User Two'}
user_three={'username':'userthree',
'useremail':'userthree#gmail.com',
'displayname':'User Three'}
users_list=['user_one','user_two','user_three']
obj_name=print_values(user_one['username'],user_one['useremail'],user_one['displayname'])
obj_name.printing_content()
It's working fine, as am getting output as below
UserName: userone
UserEmail: userone#gmail.com
UserDisplayName:User One
Here am only using user_one dict, i want to do the same for multiple dict.
I have tried adding the dict names in list and try to loop through them, like below
for item in user_list:
obj_name=print_values(item['username'],item['useremail'],item['displayname'])
obj_name.printing_content()
But am getting below error
obj_name=print_values(item['username'],item['useremail'],item['displayname'])
TypeError: string indices must be integers
Any one do let me know what am i missing or anyother idea to get this done.
Thanks in advance!
This is because in users_list=['user_one', 'user_two', 'user_three'] you enter the variable name as a string.
class print_values:
def __init__(self,username,user_email,displayname):
self.name= username
self.email=user_email
self.DisplayName=displayname
def printing_content(self):
print(f"UserName: {self.name}\n"
f"UserEmail: {self.email}\n"
f"UserDisplayName:{self.DisplayName}\n")
user_one={'username':'userone',
'useremail':'userone#gmail.com',
'displayname':'User One'}
user_two={'username':'usertwo',
'useremail':'usertwo#gmail.com',
'displayname':'User Two'}
user_three={'username':'userthree',
'useremail':'userthree#gmail.com',
'displayname':'User Three'}
users_list=[user_one,user_two,user_three] # edited
obj_name=print_values(user_one['username'],user_one['useremail'],user_one['displayname'])
obj_name.printing_content()
for item in users_list:
obj_name=print_values(item['username'],item['useremail'],item['displayname'])
obj_name.printing_content()
Explanation
Your users_list=['user_one', 'user_two', 'user_three'] is a string containing the variable names as the string. When you loop on user_list
for item in user_list:
Here item is not the user_one, or user_two as a variable but these are as the string means 'user_one', or 'user_two', so when you try to get values like item['username'], here you got the error because the item is not a dictionary or json or ..., but it is a string here, you can get the only provide an integer inside these brackets [], like 1, 2, 3, 4,..., ∞.
I hope you understand well. Thanks.
Don't make a dictionary for every user.
Use this code
class Users:
def __init__(self) -> None:
self.userList = []
def addUser(self, user):
self.userList.append(user)
class User:
def __init__(self, username, email, name) -> None:
self.username = username
self.email = email
self.name = name
def __str__(self) -> str:
return f"Username = {self.username}\nEmail = {self.email}\nName = {self.name}\n"
users = Users()
users.addUser(User("username1", "email1", "name1"))
users.addUser(User("username2", "email2", "name2"))
# First way of printing
for user in users.userList:
print(user) # Printing user directly prints the formatted output
# Because I have changed the magic `__str__` method in user class
# You can return anything('string data type only') in __str__ it will print when you print the class object.
# Second way of printing.
for user in users.userList:
print("Username = " + user.username)
print("Email = " + user.email)
print("Name = " + user.name)
print() # for adding one extra line

Python class and objects within another function

I’m trying to learn how to utilize class and objects within my Python code. I'm totally overwhelmed by the fact that is is suppose to be a begginingers class and I got this assignment where if something like this:
Class name is IPAdress and there I want properties IP, hostname, ASN and ISP. Also, it has a method which creates similar print like this:
IP: 85.76.129.254
Hostname: 85-76-129-254-nat.elisa-mobile.fi
ASN: 719
ISP: Elisa Mobile
Method can be named as PrintDetails.
Once the class is ready, I want to use it within my Osio9 function as following
Function asks user to input IP, hostname, ASN and ISP. Object is created according to this information.
Object is added to list (initially empty) and information is printed by using the PrintDetails -method
After this user is asked if he/she wants to create a new IP and if answer is yes -> repeat the above process (ask for input), add the new object to a list and print all information from the list with PrintDetails
After input, the list is looped through and it calls each IPAddress object with PrintDetails -method. (Print can look like the example above)
If user doesn’t want to continue inputting IP-addresses, exit the function
I have no clue how to proceed and answer I receive from my teacher is to look from google so here I am.
class IPAddress: ##define class
def __init__(self, IP, hostname, ASN, ISP):
self.ip = ip
self.hostname = hostname
self.asn = asn
self.isp = isp
def PrintDetails(self): ## construction method
print("IP-address: " + str(self.ip) + " | Hostname: " + str(self.hostname) + " | ASN: " + str(self.asn) + "ISP: " + str(self.isp))
def Osio9():
addresses = []
while(true):
ip = str (input("Enter IP address: ")) #ask for user input
hostname = str (input("Enter Hostname: "))
asn = str (input("Enter ASN: "))
isp = str (input("Enter ISP: "))
address = IPAddress
address.isp = isp
addresses.append(address)
for IPAddress in addresses:
IPAddress.PrintDetails(self)
# continueInput = str (input("Do you want to add more IP-addresses (y/n): "))
# if (continueInput == "y"):
# return addresses
#
# else break
I just saw your last update and there are some good ideas in it. Here is one version of the program, which does not completely correspond to your assignment as the main execution is not within a loop but in a if __name__ == '__main__': statement which will execute only when the program is called directly, and not when it is imported or when function part of this program are imported. I highly encourage you to try a small part of the code, one at a time, and then to adapt it to your specific need.
Let's go piece by piece:
#%% Definition of IPAddress
class IPAddress:
def __init__(self, ip, hostname, asn, isp):
self.ip = ip
self.hostname = hostname
self.asn = asn
self.isp = isp
def prettyprint(self):
str2print = f' | IP: {self.ip}\n' +\
f' | Hostname: {self.hostname}\n' +\
f' | ASN: {self.asn}\n' +\
f' | ISP: {self.isp}\n'
print (str2print)
def __key(self):
"""
key method to uniquely identify an object IPAddress.
I defined it as a tuple of the 4 main attributes, but if one of them is
unique it could be directly used as a key.
"""
return (self.ip, self.hostname, self.asn, self.isp)
def __eq__(self, other):
""" == comparison method."""
return isinstance(self, type(other)) and self.__key() == other.__key()
def __ne__(self, other):
""" != comparison method."""
return not self.__eq__(other)
def __hash__(self):
"""Makes the object hashable. Sets can now be used on IPAddress."""
return hash(self.__key())
I am using spyder as an IDE, and the symbol #%% creates sections of code, very similar to matlab, which can be executed in the current console by doing Right-Click -> Run Cell.
I changed the print function to make it more explicit. Strings object can be denoted by 3 symbols: 'str', "str", """str""". Additionnaly, a flag in front can change the behavior of the string. The most usefull ones are f and r.
Formatting a string with either .format() method or the f flag.
value = 1
str1 = 'string to format with value v = {}'.format(value)
str2 = f'string to format with value v = {value}'
You can print both string to see that they are equivalent. The flag f is similar to a .format() call. It allows the element within the brackets {} to be executed before the print. It is especially usefull when you format a string with multiple values.
v1 = 1
v2 = 2
str1 = 'string to format with value v = {} and {}'.format(v1, v2)
str2 = f'string to format with value v = {v1} and {v2}'
I still chose to split the sring into 4 strings and to add them together for a cleaner look of the code. The backslash \ at the end of each line allows python to consider the current line and the next one as the same line. It's a line-split character.
N.B: If you want to know what the flag r does, look into the escape character ;) r flag is especially usefull when working with paths.
Objects can be compared together. For instace, if you try 5==3, python will return False because the integer object 5 is different from the integer object 3. You can implement the == and != method in any object/class you develop. To do so, I first define a unique key for this object in the function __key(). Then the function __eq__ implements == and returns True if both objects compared are created from the same class and have the same key. The method __ne__ implements != and returns True if __eq__ is not True.
N.B: I also added the hash method to make the object hashable. Once the key is define, creating a hash is trivial, since the idea is to be able to uniquely identify each object, which is also done by the key. This definition allows the use of sets, for instance to check if a list has multiple occurence of the same object.
def add_IPAddress(ListOfIPAddresses, IPAddress):
"""
Function adding IPAddress to ListOfIPAddresses if IPAddress is not already
in ListOfIPAddresses.
"""
if IPAddress not in ListOfIPAddresses:
ListOfIPAddresses.append(IPAddress)
print ('IP Address appended:')
IPAddress.prettyprint()
def input_IPAddress():
"""
Ask a user input to create an IPAddress object.
"""
ip = input("Enter IP address: ")
hostname = input("Enter Hostname: ")
asn = input("Enter ASN: ")
isp = input("Enter ISP: ")
return IPAddress(ip, hostname, asn, isp)
Then I splitted the input from the user and the addition to a list of objects into 2 different functions. The function input() already returns a string, thus I removed the str() call to convert.
N.B: Watchout when asking users to input numbers, usually you forget that the input is a string and then your code raises an error because you forget to convert the string to integer or float.
Improvements: I didn't do it here, but usually when using user input, you have to check if the input given is correct. Some simple syntax checks (e.g. the number of '.' characters in the ipadress) can already improve the robustness of a piece of code. You could also use regular expressions with regex to check if the input is conform.
The query_yes_no() is a clean yes/no util which I copied from somewhere.. I usually place it in a util module: folder within the environment path named util with a __init__.py file. More information if you look into the creation of python module.
#%% Main
if __name__ == '__main__':
ListOfIPAddresses = list()
while True:
if not query_yes_no('Do you want to input IP Address?'):
break
ListOfIPAddresses.append(input_IPAddress())
for ipaddress in ListOfIPAddresses:
ipaddress.prettyprint()
print ('--------------------------') # Just pretting a separator
Finally, in the main part, an infinite while loop is broke only if the user replies no (or any of the other negative keyworkds defined in query_yes_no()). Until it is broken, the user will be asked to add a new IPAddress to the list ListOfIPAddresses which will be added if it is not already present inside.
Full code snippet:
# -*- coding: utf-8 -*-
import sys
#%% Definition of IPAddress
class IPAddress:
def __init__(self, ip, hostname, asn, isp):
self.ip = ip
self.hostname = hostname
self.asn = asn
self.isp = isp
def prettyprint(self):
str2print = f' | IP: {self.ip}\n' +\
f' | Hostname: {self.hostname}\n' +\
f' | ASN: {self.asn}\n' +\
f' | ISP: {self.isp}\n'
print (str2print)
def __key(self):
"""
key method to uniquely identify an object IPAddress.
I defined it as a tuple of the 4 main attributes, but if one of them is
unique it could be directly used as a key.
"""
return (self.ip, self.hostname, self.asn, self.isp)
def __eq__(self, other):
""" == comparison method."""
return isinstance(self, type(other)) and self.__key() == other.__key()
def __ne__(self, other):
""" != comparison method."""
return not self.__eq__(other)
def __hash__(self):
"""Makes the object hashable. Sets can now be used on IPAddress."""
return hash(self.__key())
#%% Functions
def add_IPAddress(ListOfIPAddresses, IPAddress):
"""
Function adding IPAddress to ListOfIPAddresses if IPAddress is not already
in ListOfIPAddresses.
"""
if IPAddress not in ListOfIPAddresses:
ListOfIPAddresses.append(IPAddress)
print ('IP Address appended:')
IPAddress.prettyprint()
def input_IPAddress():
"""
Ask a user input to create an IPAddress object.
"""
ip = input("Enter IP address: ")
hostname = input("Enter Hostname: ")
asn = input("Enter ASN: ")
isp = input("Enter ISP: ")
return IPAddress(ip, hostname, asn, isp)
#%% Util
def query_yes_no(question, default="yes"):
"""Ask a yes/no question via raw_input() and return their answer.
"question" is a string that is presented to the user.
"default" is the presumed answer if the user just hits <Enter>.
It must be "yes" (the default), "no" or None (meaning
an answer is required of the user).
The "answer" return value is True for "yes" or False for "no".
"""
valid = {"yes": True, "y": True, "ye": True,
"no": False, "n": False}
if default is None:
prompt = " [y/n] "
elif default == "yes":
prompt = " [Y/n] "
elif default == "no":
prompt = " [y/N] "
else:
raise ValueError("invalid default answer: '%s'" % default)
while True:
sys.stdout.write(question + prompt)
choice = input().lower()
if default is not None and choice == '':
return valid[default]
elif choice in valid:
return valid[choice]
else:
sys.stdout.write("Please respond with 'yes' or 'no' "
"(or 'y' or 'n').\n")
#%% Main
if __name__ == '__main__':
ListOfIPAddresses = list()
while True:
if not query_yes_no('Do you want to input IP Address?'):
break
ListOfIPAddresses.append(input_IPAddress())
for ipaddress in ListOfIPAddresses:
ipaddress.prettyprint()
print ('--------------------------') # Just pretting a separator

How to end a method in a class if user input is blank

I'm new to programming so bear with me please!
I'm creating a class and having trouble getting the return message to show when the users input is empty.
Instead of returning my message it's just throwing me an error.
I want my code to return "please try again" and end, if the user input is blank.
Code:
class BankAccount():
def __init__(self):
# asking for a name
self.name = str(input("Hello! Welcome to the Bank of Alex.\nWhat is your name?"))
if self.name == "":
return "please try again"
else:
print(f"\nWelcome, {self.name.title()}.")
TypeError Traceback (most recent call last)
in
----> 1 account = BankAccount()
TypeError: init() should return None, not 'str
Your program structure is incorrect for using a class. You should not create an object until you know the input is valid. Have the calling program check it:
name = ""
while name == "":
name = input("Enter your name")
if name:
acct = BankAccount(name)
break
else:
print("Please try again")
Your __init__ method then merely crates the account -- no name check. This method implicitly returns the created object; you're not allowed to return anything else.
I was able to solve this with help from #Prune. I used the while loop he mentioned and put it under __ init __
So if user input is blank it will just keep prompting for an input. Not a perfect solution but it works.
class BankAccount():
def __init__(self):
self.name = input("Hello! Welcome to the Bank.\nWhat is your name?")
while self.name == "":
self.name = input("Please enter your name")
if self.name:
print(f"\nWelcome, {self.name.title()}.")

I want to make a class attribute into a tuple that receives its input through raw user inputs and saves the results into a file

The following code works fine. But I want to make some modifications.
from pip._vendor.distlib.compat import raw_input
class User():
'''simulates a user for a social network or pc'''
def __init__(self, first_name, last_name, username,location, interests):
'''initialize attributes of user class'''
self.first_name = first_name.title()
self.last_name = last_name.title()
self.username = username
self.location = location.title()
self.interests = interests
#classmethod
def get_userinfo(cls):
'''each attribute of User is defined by a user input'''
return cls(
raw_input("Welcome. PLease Enter Your First Name: "),
raw_input("Please Enter Your Last Name: "),
raw_input("Username: "),
raw_input("What is your location? : "),
raw_input("List some of your interests: ")
)
def __str__(self):
'''returns all attributes of User as strings'''
return str("User: " + self.first_name + self.last_name +
"\nUsername: " + self.username +
"\nLocation: " + self.location +
"\nInterests: " + self.interests)
'''creates an instance of User object'''
user1 = User.get_userinfo()
'''writes each attribute of User into a file'''
filename = r'''C:\Users\User\Documents\dataset1.txt'''
with open(filename, 'r+') as file_object:
contents = file_object.write(str(user1))
I want to make the parameter 'interests' into a tuple or a list. The user should be able to input many interests and decide when to stop through a flag such as 'active = True', and then finally return the results as a string to be able to write it to the file.
Sorry, I don't follow the flag part. But is this what you had in mind? You stop by just entering your items. * I will update if I misunderstood
$ vi test.txt
$ python test.txt
from pip._vendor.distlib.compat import raw_input
class User():
'''simulates a user for a social network or pc'''
def __init__(self, first_name, last_name, username, location, interests):
'''initialize attributes of user class'''
self.first_name = first_name.title()
self.last_name = last_name.title()
self.username = username
self.location = location.title()
self.interests = interests.split(', ')
#classmethod
def get_userinfo(cls):
'''each attribute of User is defined by a user input'''
return cls(
raw_input("Welcome. PLease Enter Your First Name: "),
raw_input("Please Enter Your Last Name: "),
raw_input("Username: "),
raw_input("What is your location? : "),
raw_input("List some of your interests: ")
)
def __str__(self):
'''returns all attributes of User as strings'''
return "User: {0} {1} \nUsername: {2} \nLocation: {3} \nInterests: {4}".format(self.first_name, self.last_name, self.username, self.location, ','.join(self.interests))
'''creates an instance of User object'''
user1 = User.get_userinfo()
print(user1)
$ python test.txt
Welcome. PLease Enter Your First Name: Hi
Please Enter Your Last Name: How
Username: Are
What is your location? : You
List some of your interests: Ball, Tennis, Python
User: Hi How
Username: Are
Location: You
Interests: Ball, Tennis, Python
I want to make the parameter 'interests' into a tuple or a list. The user should be able to input many interests and decide when to stop through a flag such as 'active = True'
I'm not sure how the user is going to set active=True, but the rest of that sentence just screams "I want a loop":
#classmethod
def get_userinfo(cls):
first = raw_input("Welcome. PLease Enter Your First Name: ")
last = raw_input("Please Enter Your Last Name: ")
user = raw_input("Username: ")
location = raw_input("What is your location? : ")
interests = []
print("List some of your interests (just type Return on its own when you're done)")
while True:
interest = raw_input().strip()
if not interest:
break
interests.append(interest)
OK, that gives us a list, not a tuple. We could create a tuple by doing interests = interests + (interest,), but that's clunky and inefficient. If you really need a tuple, it's actually simpler to just build a list and then convert it at the end:
interests = tuple(interests)
And now we can pass all of those variables to the constructor:
return cls(first, last, user, location, interests)
… and then finally return the results as a string to be able to write it to the file.
Hold on; what kind of file are you creating here?
If this file is mean to be read and edited by a human being, and never looked at by Python again, that's easy. You can, e.g., just join them up with spaces, or commas, or newlines, or whatever you want. Or you can manually loop over them to format them more fancily:
def write_to_file(self, filename):
with open(filename, 'w') as file:
file.write('First Name: {}\n'.format(self.first_name))
file.write('Last Name: {}\n'.format(self.last_name))
file.write('Username: {}\n'.format(self.username))
file.write('Location: {}\n'.format(self.location))
file.write('Interests:\n')
for interest in self.interests:
file.write(' {}\n'.format(interest))
But if it's meant to be used for storing data to be read later by Python, you want to write things in a format that's meant to be parsed. Maybe add a method to serialize your objects to and from JSON, for example:
def to_json(self):
return json.dumps({'first': self.first_name, 'last': self.last_name,
'user': self.username, 'location': self.location,
'interests': self.interests})
#classmethod
def from_json(cls, j):
dct = json.loads(j)
return cls(dct['first'], dct['last'], dct['user'],
dct['location'], dct['interests'])
And now, to write it to a file:
with open(filename, 'w') as f:
f.write(user.to_json())

How to change a global variable in python?

I am accessing data from different accounts from an online platform over their API. I have created a class called Account that holds all the information necessary to access this API. I want to be able to set the account (and the necessary info to gain access) each time before I make an API request. I tried to make a function that will set a global variable Acct to the proper account class instance but after I call choose_account(), Acct continues to return '', is there a better way to handle this type of procedure?
Acct = ''
def choose_account():
global Acct
get = raw_input(r'Adap1, Adap2, Adap3, or Adap4? ')
if get == 'Adap1':
Acct = Adap1
elif get == 'Adap2':
Acct = Adap2
elif get == 'Adap3':
Acct = Adap3
elif get == 'Adap4':
Acct = Adap4
else:
print ("Please type Adap1, Adap2, Adap3, or Adap4 ")
Edit: show Account and Adap1 etc
class Account():
def __init__(self, name, username, password, org_id):
self.name = name
self.username = username
self.password = password
self.org_id = org_id
def update_pw(self, pw):
self.password = pw
Adap1 = Account('Adap1', 'username', 'password', 'org_id')
Sorry, but use of global variables in that way is not usually a good way to go. You are probably new to programming, so I don't want you to feel you are being "told off", but it would be much more sensible to have the function return a value, and then set the global variable with a statement like
Acct = choose_account()
In which case your function ought to look more like this (untested code):
def choose_acct():
while True:
get = raw_input(r'Adap1, Adap2, Adap3, or Adap4? ')
if get == "Adap1":
return Adap1
elif get == "Adap2":
return Adap2
elif get == "Adap3":
return Adap3
elif get == "Adap4":
return Adap4
Better still, you could consider a data-driven approach to the problem, and define a dictionary like
adict = {"Adap1": Adap1, "Adap2": Adap2, "Adap3": Adap3, "Adap4": Adap4}
Then your function could read (again, untested)
def choose_acct():
while True:
get = raw_input(r'Adap1, Adap2, Adap3, or Adap4? ')
result = adict.get(get, None)
if result:
return result
As your experience level grows you will start to recognise the difference between good and bad code, but you made a pretty good attempt.

Categories

Resources