How to simulate series of user input in Python - python

Let's say we have a function like this
def function():
while True:
user_input = input("enter a number: ")
if user_input == "0":
print("finish")
break
print("the number is " + user_input)
And in the main() we call the function
function()
Then it will ask for user input until it gets a "0".
What I want to do is like have something can store all the input, and automatically give it to the console. So, I don't need to manually type them in the console.
Please note that I'd like to have the function not accepting arguments and use something_taken_as_input without passing it as an argument.
something_taken_as_input = ["1","2","3","0"]
function()
# enter a number: 1
# enter a number: 2
# enter a number: 3
# enter a number: 0
# finish
# all done by the program, no manually typing!

A fun way to do this would be to pass the input method to the function.
This way, you can do this:
def function(inp_method):
while True:
user_input = inp_method("enter a number: ")
if user_input == "0":
print("finish")
break
print("the number is " + user_input)
if you want to take input from the user,
call it like this:
function(input)
otherwise, define a class with the data you want to input:
class input_data:
def __init__(data):
self.data = data
self.count = 0
def get(self, str = ""):
if(self.count == len(self.data)):
return 0
else:
count+=1
x = self.data[count-1]
and call function using:
d = input_data(["1", "2", "3", "0"])
function(d.get)
Fundamentally, you are just passing the method through the parameters of the function.

Related

How to return an answer from Yes/No answer out of respective function?

I am asking a Yes or No prompt to a user as a function and I want to return what the answer was back to the rest of the code.
How could I get the answer from the yesNo() function to figure out if the user would like to run the intro variable/function?
prompt = " >>> "
def yesNo():
answer = input('(Y/N)' + prompt)
i = 1
while i > 0:
if answer == str.lower("y"):
tutorial()
i = 0
elif answer == str.lower('n'):
startGame()
i = 0
else:
print("command not understood. try again.")
def newGame():
print("would you like a tutorial?")
yesNo()
I think you'll want something closer to this:
def get_user_input(choices):
prompt = "Please enter ({}): ".format("/".join(f"'{choice}'" for choice in choices))
while True:
user_input = input(prompt)
if user_input in choices:
break
prompt = "Unsupported command '{}', Try again: ".format(user_input)
return user_input
def main():
print("Would you like a tutorial?")
user_input = get_user_input(["Yes", "No"])
if user_input == "Yes":
tutorial()
startGame()
The function that gets user input should only be responsible for getting user input, and returning the user's provided input to the calling code. It should not have any other side-effects, like starting a tutorial, or starting the game.
To get the answer of the user outside the yesNo() method, you can use return, and then store the returned value in a variable
Like this:
prompt = " >>> "
def yesNo():
i = 1
while i > 0:
answer = input('(Y/N)' + prompt)
if answer == str.lower("y"):
tutorial()
i = 0
elif answer == str.lower('n'):
startGame()
i = 0
else:
print("command not understood. try again.")
return answer
def newGame():
print("would you like a tutorial?")
answer = yesNo()

While loop is not breaking even after the condition is satisfied

I've provided the code below.
What is want to do is run the first input box where it will check the condition if true it will go for next input(), but if not it will run the code again. The problem is first input() is running fine, but second one is not getting out of the loop where I'm checking if the input is integer or not
class AC ():
def __init__(self):
self.owner=input("Enter The Name: ")
while True:
if self.owner.isalpha():
self.balance=(input("Enter The Amount: "))
def lol():
while True:
if self.balance.isdigit():
break
else:
print("Enter The Amount: ")
lol()
break
else:
AC()
break
The problem is that your lol() function is never being called for, so it will stay in the first while-loop indefinitely.
lol() function is never being called as Tim said
input() function return string value you can change str to float
try this:
`
def __init__(self):
self.owner = input("Enter The Name: ")
while True:
if self.owner.isalpha():
self.balance = input("Enter The Amount: ")
def lol():
while True:
try:
self.balance = float(self.balance)
except ValueError:
break
if self.balance.isdigit():
break
else:
lol()
else:
AC()
break

Python words generator

I'm currently trying to run a program where the user inputs a word and then after they input the first word, the program will ask if they want to continue putting words. Once the user replies "no", the program will generate the list of words that has been input. I seem to be having trouble calling the array for my code below:
def word():
w1 = input("Please enter a word: ")
group = []
group.append(w1)
decide = input("Do you want to continue? yes/no: ")
if (decide == "yes"):
return -1
elif (decide == "no"):
return 1
while (True):
crit = word()
if (crit == -1):
continue
elif (crit == 1):
print("words are: ", group)
break
How I can make this work properly?
I think you meant to pass the list into the function:
def word(group):
w1 = input("Please enter a word: ")
group.append(w1)
decide = input("Do you want to continue? yes/no: ")
return decide == "yes"
group = []
while True:
crit = word(group)
if crit:
continue
else:
print("words are: ", group)
break
The array ‘group’ is defined inside the function word(). This means if the function is returned, the list ‘group’ disappears also.
You can either
Use global variable
Define group outside the function (in this case, at the top) and use that global list inside the function. I.e. add the line
global group in the first line of the function.
However, using global variable when not needed is not so recommandable.
Define group list outside the function and pass it to the function as an argument
Instead of def word(), use def word(group) and pass the list to the function when calling the function.
group = []
def word():
w1 = input("Please enter a word: ")
group.append(w1)
decide = input("Do you want to continue? yes/no: ")
if (decide == "yes"):
return -1
elif (decide == "no"):
return 1
while (True):
crit = word()
if (crit == -1):
continue
elif (crit == 1):
print("words are: ", group)
break
The variable group is not available outside the function.
A variable created outside of a function is global and can be used by anyone.

Using Variables From Other Functions

Hopefully my code and question(s) are clear for understanding. If they are not please provide feed back.
I am fairly new to programing/coding so I decided to develop a program using Python that acts like a pizza ordering system. I eventually would like to use this code to develop a website using Django or Flask.
I have just finished the first step of this program where I am asking the user if this will be for delivery of pickup. Depending on what the user chooses the program will ask for specific information.
The area I feel like I am struggling with the most is developing classes and functions. specifically taking a variables from one function and using that variable in another function. I posted a past example of my code and I was advised that Global variables are not good to use in code. So I am trying really hard to refrain from using them.
Here is the code for reference:
import re
running = True
class PizzaOrderingSys():
"""order a customized pizza for take out or delivery """
def delivery_or_pickup(self): # Is the order for devilery or pickup?
print("\nWill this order be for pickup or delivery?")
self.delivery = input("P - pick up / D - delivery : ")
self.delivery = self.delivery.title()
if self.delivery == "D":
while running == True:
customerName = input("\nName for the order: ")
if not re.match("^[a-zA-Z ]*$", customerName):
print("Please use letters only")
elif len(customerName) == 0:
print("Please enter a vaild input")
else:
customerName = customerName.title()
break
while running == True:
customerPhoneNumber = input("\nEnter a phone number we can contact you at: ")
if not re.match("^[0-9 ]*$", customerPhoneNumber):
print("Please use numbers only")
elif len(customerPhoneNumber) == 0:
print("Please enter a a contact phone number")
else:
break
while running == True:
house_num = input("\nWhat is your house or unit number: ")
if not re.match("^[0-9 /]*$", house_num):
print("Please use numbers only")
elif len(house_num) == 0:
print("Please enter a valid input ")
else:
break
while running == True:
streetName = input("\nStreet name: ")
if not re.match("^[a-zA-Z ]*$", streetName):
print('Please use letters only.')
elif len(streetName) == 0:
print("Please enter a valid input")
else:
streetName = streetName.title()
break
while running == True:
city = input("\nCity: ")
if not re.match("^[a-zA-Z ]*$", city):
print("Please use letters only")
elif len(city) == 0:
print("Please enter a valid input")
else:
city = city.title()
break
while running == True:
zip_code = input("\nZip Code:")
if not re.match("^[0-9 /]*$", zip_code):
print("Please use numbers only")
elif len(zip_code) == 0 or len(zip_code) > 5:
print("Please enter a valid input")
else:
break
elif self.delivery == "P":
while running == True:
customerName = input("\nName for the order: ")
if not re.match("^[a-zA-Z ]*$", customerName):
print("Please use letters only")
elif len(customerName) == 0:
print("Please enter a valid input")
else:
customerName = customerName.title()
break
while running == True:
customerPhoneNumber = input("\nEnter a phone number we can contact you at: ")
if not re.match("^[0-9 ]*$", customerPhoneNumber):
print("Please use numbers only")
elif len(customerPhoneNumber) == 0:
print("Please enter a valid input")
else:
break
else:
print("Please enter P or D ")
delivery_or_pickup()
order = PizzaOrderingSys()
order.delivery_or_pickup()
My question is this: How would I use variables found in one function of my class and use it in another future function??
For example if I wanted to retrieve variables the functions customerName, customerPhoneNumber, house_num, streetName, city, Zip_code found in delivery_or_pick() function and use them in a function called:
def customer_receipt():
What would I need to do to my exiting code or to the def customer_receipt() function to obtain that information?
Any help with my questions or advise on any other area that stick out to you would be be greatly appropriated.
This is my second post on Stackoverflow so I apologize if what i am asking is unclear or the format of my question might is off, I am still learning.
Thank you again.
The idea here is that you can use your class variables to save data between method calls. Methods are functions that belong to a class. For example you could use Python's class initialization and create a dict of orders. Here is a simple example of such system, take a note of the usage of self keyword. self refers to the instance of the class and you can use it to access the variables or methods of the instance:
class PizzaOrderingSys:
def __init__(self):
# Initializing some class variables
self.running = True # Now you can use self.running instead of global running variable
self.orders = {}
def delivery_or_pickup(self):
# Somewhere at the end where you have collected the needed info
order = {
"zip_code": zip_code,
"city": city,
# You can enter all of the needed data similarly
}
order_id = "SomeIdHere" # ID could be anything, it just should be unique
self.orders[order_id] = order
return order_id
def customer_receipt(self, id):
# Now you can access all of the order here with self.orders
order = self.orders.get(id) # Select some specific order with id.
# Using get to avoid the situation
# where no orders or invalid id would raise an exception
if order:
receipt = f"Order {id}:\nCustomer city {order['city']}"
else:
receipt = None
return receipt
pizzasystem = PizzaOrderingSys()
order_id = pizzasystem.delivery_or_pickup()
receipt = pizzasystem.customer_receipt(order_id)
print(receipt)
# >>> Order 1235613:
# Customer city Atlantis
I recommend that you read more about classes, for example, python docs have great material about them.

python array count each elements

I want a small program to count each part numbers enter by user.
here is so far I can do.
Is there a way I can export part numbers and their frequency to .csv file?
from collections import Counter
thislist = []
frequency = []
partnumber = ""
def mainmanu():
print ("1. Create List")
print ("2. Print list")
print ("3. Exit")
while True:
try:
selection = int (input("Enter Choice: ")
if selection ==1:
creatlist(thislist)
elif selection ==2:
counteach(thislist)
elif selection ==3:
break
except ValueError:
print ("invalid Choice. Enter 1-3")
def creatlist(thislist)
# while True:
partnumber = input ("Enter Part number: ")
if partnumber =="end":
print(thislist)
mainmanu()
break
thislist.append(partnumber)
def counteach(thislist)
Counter(thislist)
mainmanu()
mainmanu()
Welcome to the StackOverflow.
You are calling the mainmanu function inside another function which is called by mainmanu function. Instead what you should be doing is letting mainmanu calling all the other helper functions. Antoher thing, you can't call break in another function and expect where it is called to break.
The execution goes like this:
mainmanu is called, it calls creatlist, after it finishes execution it continues to execute the instructions where it is left from.
from collections import Counter
thislist = []
frequency = []
partnumber = ""
def mainmanu():
print ("1. Create List")
print ("2. Print list")
print ("3. Exit")
while True:
try:
selection = int (input("Enter Choice: ")
if selection ==1:
if creatlist(thislist): # line x
break
elif selection ==2:
counteach(thislist)
elif selection ==3:
break
except ValueError:
print ("invalid Choice. Enter 1-3")
def creatlist(thislist)
# while True:
partnumber = input ("Enter Part number: ")
if partnumber =="end":
print(thislist)
return True #this value will make the the condition to be true see line x
thislist.append(partnumber)
return false
def counteach(thislist)
Counter(thislist)
mainmanu()

Categories