Passing variables defined inside of one function into another - python

Context:
I'm sure this has been asked elsewhere, but the topics I'm finding thus far are more advanced than what I'm doing and only confusing me further. I am a student in an intro to Python course, and am working on a "Lottery Number" assignment. Basically, randomly generate a 7-digit lottery number and print it back out.
That much I get, but I am trying to approach this from a less literal perspective and a more practical one. As in, I want the user to define how many numbers they need and which numbers to choose from. From there, I want the program to generate random numbers that fit the criteria they set.
My instructor wants everything done inside of functions, so I am trying to attempt the following:
What I'm doing:
main() Function - everything inside of here.
get_info() to collect the data from the user, number of digits (MaxDigits), range minimum (MinChoice), range maximum (MaxChoice).
lottery_pick() take the variables and do the lottery thing with them.
I have it "working", but I can only do so if I have lottery_pick() function run inside of the get_info() function. I imagine there has to be a way to define these variables independently, and just pass the variables from get_info() to lottery_pick().
import random
# Define the main function
def main():
get_info()
exit_prompt()
def get_info():
# Set Variables to 0
MaxDigits = 0
# Let the user know what we are doing
print("Let's choose your lottery numbers!")
print("First, How many numbers do you need for this lottery?")
# Request the user input the number of lottery numbers we need
while True:
try:
MaxDigits = int(input('Please enter how many numbers you need to choose: '))
if MaxDigits > 0:
break;
else:
print('Please enter an integer for how many numbers are being drawn. ')
except:
continue
print('Next, we need to know the smallest and largest numbers allowed to choose from')
# Request user input smallest number in range of numbers to pick from.
while True:
try:
MinChoice = int(input('Please enter the lowest number you are allowed to choose from: '))
if MinChoice >= 0:
break;
else: print ('Please enter an integer, 0 or greater for the smallest number to pick from.')
except:
continue
# Request user input largest number in range of numbers to pick from.
while True:
try:
MaxChoice = int(input('Please enter the largest number you are allowed to choose from: '))
if MaxChoice >= 0:
break;
else: print ('Please enter an integer, 0 or greater for the greatest number to pick from.')
except:
continue
# Define the function to actually assemble the lottery number
def lottery_pick(lot_digits, lot_min, lot_max):
numbers = [0] * lot_digits
for index in range(lot_digits):
numbers[index] = random.randint (lot_min, lot_max)
print('Here are your lottery numbers!:')
print(numbers)
# Execute the function - I've not yet figured out how to pass the variables from the get_info
# function to the lottery_pick function without lottery_pick being inside of get_info.
lottery_pick(MaxDigits, MinChoice, MaxChoice)
def exit_prompt():
while True:
try:
# use lower method to convert all strings input to lower-case. This method
# allows user to input their answer in any case or combination of cases.
ExitPrompt = str.lower(input('Would you like to generate another lottery number? Please enter "yes" or "no" '))
if ExitPrompt == 'yes':
main()
elif ExitPrompt =='no':
print('Goodbye!')
exit()
# If an answer other than yes or no is input, prompt the user again to choose to re-run or to exit
# until an acceptable answer is provided.
else:
print('Please enter "yes" to generate another lottery number, or "no" to exit. ')
except:
continue
main()

Related

How to check user input for multiple conditions within same loop or function in Python 3?

I'm trying to take user-input but I need the input to be an integer, AND be between 1 and 9. I tried putting "in range(1,10)" in a few places in the code but it didn't work. I need the program to keep asking the user for the right input until they give the correct input. So far I've only been able to make sure their input is an integer with he following code. I will be taking input by using int(input("...")), rather than using input("...").
while True:
try:
ui1 = int(input("Player 1, Your move. Select your move. "))
break
except ValueError:
print("You have to choose a number between 1 and 9")
continue
Add a check before the break and move the error message to the end of the loop.
while True:
try:
ui1 = int(input("Player 1, Your move. Select your move. "))
if 1 <= ui1 <= 9:
break
except ValueError:
pass
print("You have to choose a number between 1 and 9")
Why not just check isdigit() and in range ?
while True:
ui1 = input("Player 1, Your move. Select your move. ")
if ui1.isdigit() and int(ui1) in range(1,10):
break
print("You have to choose a number between 1 and 9")
# Continue code out of the loop
# beJeb
# Stack overflow -
# https://stackoverflow.com/questions/51202856/how-to-check-user-input-for-multiple-conditions-within-same-loop-or-function-in
# Our main function, only used to grab input and call our other function(s).
def main():
while True:
try:
userVar = int(input("Player 1, Your move. Select your move: "))
break
except ValueError:
print("Incorrect input type, please enter an integer: ")
# We can assume that our input is an int if we get here, so check for range
checkRange = isGoodRange(userVar)
# Checking to make sure our input is in range and reprompt, or print.
if(checkRange != False):
print("Player 1 chooses to make the move: %d" %(userVar))
else:
print("Your input is not in the range of 1-9, please enter a correct var.")
main()
# This function will check if our number is within our range.
def isGoodRange(whatNum):
if(whatNum < 10) & (whatNum > 0):
return True
else: return False
# Protecting the main function
if __name__ == "__main__":
main()
Note: I tested a couple inputs so I believe this should be enough to help you understand the process, if not please comment, message, etc. Also, if this answer helps you, please select it as answered to help others.
Let the number be the input you are taking from the user.
while(1): #To ensure that input is continuous
number = int(input())
if number>=1 and number<=10 and number.isdigit():
break #if the input is valid, you can proceed with the number
else:
print("Enter a valid Number")
The number can be used for further operations.

UserInput in Python While loop

Following my code which is supposed to take 3 positive integer as input from user. However, it is not working as per expectation.
def getPositiveNumber(prompt):
timeUnits = (input("This is the numnber of time units to simulate > "))
numAtoms = (input("How many atoms should we simulate ? "))
radBeaker = (input("The radius of the beaker is ? "))
while True:
if timeUnits.isnumeric() and numAtoms.isnumeric() and radBeaker.isnumeric():
print("All your values are integers")
break
else:
timeUnits = input("This is the number of units to simulate. >")
numAtoms = input("How many atoms should we simulate ? ")
radBeaker = input("The radius of the beaker is ? ")
return timeUnits, numAtoms, radBeaker
This results in asking the input again after the initial 3 inputs have been placed but i want it to ask again right after the initial part if I put a non number.
There is no point in writing three almost identical code fragments to read three integer numbers. You need one function that gets one number. You can call this function three times or, in fact, as many times as you like:
def get_positive_int(prompt):
while True:
possibly_number = input(prompt + "> ")
try:
number = int(possibly_number)
except ValueError: # Not an integer number at all
continue
if number > 0: # Comment this line if it's ok to have negatives
return number
The function relies on the fact that any string recognized by int() is a valid integer number. If it is, the number is returned to the caller. If it is not, an exception is raised by int() that keeps the loop going.
Example:
>>> get_positive_int("This is the number of units to simulate")
This is the number of units to simulate> ff
This is the number of units to simulate> -10
This is the number of units to simulate> 25
25
Try this:
def getPositiveNumber(prompt):
timeUnits = None
numAtoms = None
radBeaker = None
while True:
timeUnits = input('This is the numnber of time units to simulate > ')
numAtoms = input('How many atoms should we simulate ? ')
radBeaker = input('The radius of the beaker is ? ')
if timeUnits.isnumeric() and numAtoms.isnumeric() and radBeaker.isnumeric():
print 'All your values are integers'
break
return (timeUnits, numAtoms, radBeaker)
You can separate the test to check if the input is a positive integer to a function
def is_positive(n):
"""(str) -> bool
returns True if and only if n is a positive int
"""
return n.isdigit()
Next you can create a function to ask for a positive integer. For this avoid the str.isnumeric method because that returns True for floats as well. Rather, use the str.isdigit method.
def request_input(msg):
"""(str) -> str
Return the user input as a string if and only if the user input is a positive integer
"""
while True:
retval = input(msg)
if is_positive(retval):
return retval
else:
print("Please enter a positive integer")
request_input will loop forever until a positive integer is received. These simple blocks can be combined to achieve what you want. In your particular case:
def get_user_inputs(prompt):
time_units = request_input("This is the number of time units to simulate > ")
num_atoms = request_input("How many atoms should we simulate ? ")
rad_breaker = request_input("The radius of the beaker is ? ")
return time_units, num_atoms, rad_breaker

Using Astericks to Display a Bargraph of User Inputted Numbers in Python

I am currently attempting to solve a homework problem. The problem states to collect user inputted numbers and then arrange them using asterisks to display a graph, with the largest number having forty asterisks and the rest becoming smaller as the numbers decrease.
_NumberList= []
print("Please type 'quit' to stop entering numbers.")
print("Please type 'print' to view the list that has been entered so far.")
a= True
while a:
_number= input("Please enter a number or make a selection. ")
if _number.isdigit():
_number=int(_number)
_NumberList.append(_number)
elif _number.isalpha():
_number= _number.lower()
if _number== 'quit':
a= False
if _number== 'print':
print(_NumberList)
else:
print("Please use digits to enter a number.")
print("For exmaple: 'ten' should be typed at '10'")
else:
print("Invalid entry.")
_NumberList.remove(max(_NumberList))
for i in range(len(_NumberList)):
_NumberList.remove(max(_NumberList))
However, I am unsure as to how to find the given proportions utilizing the numerical data. Thus far, I have considered utilizing the .pop function, but it simply isn't making a ton of sense so far. I considered making them go up by one step, but again, that doesn't seem logical, and the program can run for more than forty numbers. I know I will need to utilize a loop, hence the for loop at the end, but I'm not sure as to how to continue from there.
Your variable name _NumberList makes my eyes hurt, so I'll call it number_list
largest_number = max(number_list)
scale_factor = 40 / largest_number
scaled_number_list = [int(x * scale_factor) for x in number_list]
for scaled_number in scaled_number_list:
print('*' * scaled_number)

Collatz Function: Strange try/except Bugs

So I'm getting into coding and I was doing an exercise from the Automate the Boring Stuff book. I figured out how to write the original function, but then I wanted to try to add a little more to it and see if I could fit it all in one function.
So in Python 3.6.2, this code works fine if I enter strings, positive integers, nothing, or entering "quit". However, if I enter 1 at any point between the others then try "quitting", it doesn't quit until I enter "quit" as many times as I previously entered 1. (like I have to cancel them out).
If I enter 0 or any int < 0, I get a different problem where if I then try to "quit" it prints 0, then "Enter a POSITIVE integer!".
Can't post pics since I just joined, but heres a link: https://imgur.com/a/n4nI7
I couldn't find anything about this specific issue on similar posts and I'm not too worried about this working the way it is, but I'm really curious about what exactly the computer is doing.
Can someone explain this to me?
def collatz():
number = input('Enter a positive integer: ')
try:
while number != 1:
number = int(number) #If value is not int in next lines, execpt.
if number <= 0:
print('I said to enter a POSITIVE integer!')
collatz()
if number == 1:
print('How about another number?')
collatz()
elif number % 2 == 0: #Checks if even number
number = number // 2
print(number)
else: #For odd numbers
number = number * 3 + 1
print(number)
print('Cool, huh? Try another, or type "quit" to exit.')
collatz()
except:
if str(number) == 'quit':
quit
else:
print('Enter an INTEGER!')
collatz()
collatz()

Using random.randint help in python

The following code is my attempt at simulating a lottery.
import random
def lottery(numbers):
lottoNumbers = [randint('0,100') for count in range(3)]
if numbers == lottoNumbers:
print('YOU WIN $10,000')
else:
print('YOU LOSE,DUN DUN DUNNN!')
return numbers
def main():
numbers = int(input('Enter a number: '))
if numbers == lottoNumbers:
numbers = lottery(numbers)
else:
numbers = lottery(numbers)
main()
Hey guys I've gotten this far with the help you've given me. I'm trying to write the code so that 3 lotto numbers at random will be chosen. Then the user must enter 3 of his/her own lotto numbers. If they get all 3 correct then they win the whole prize, if they get the 3 numbers but not in the correct order they win some of the prize. Obviously if they guess all wrong then a print statement would state that. What I'm confused about is how can I write the code so that the user can enter 3 numbers to try matching the random lottery numbers. I also want to print the 3 lottery numbers after the user inputs his/her choices. Any ideas guys?
Thanks for your help everyone.
You seem a bit confused about what the role of the arguments in a function are. You've said that your randm function takes the argument "number", but then you haven't actually used it anywhere. The next time number appears, you've assigned it a completely new value, so any value passed to randm isn't actually being used.
Also, the function is trying to return x, when x hasn't been assigned within the function. Either you already have a global variable called x already defined, in which case the function will just return that variable, or the function will just fail because it can't find the variable x.
Here's a quick example I've done where you pass their three numbers as a list as an argument to the function.
import random
theirNumbers=[5,24,67]
def checkNumbers(theirNumbers):
lottoNumbers = []
for count in range(3)
lottoNumbers.append(random.randint(0,100))
winning = True
for number in theirNumbers:
if not each in lottoNumbers: winning=False
if winning == True: print("Winner!")
There are a few things wrong with your implementation, to name a few:
if you are trying to compare the output of the function randm to x, you will need to include a return value in the function, like so:
def randm():
return return_value
You appear to be printing all the values but not storing them, in the end you will only end up with the final one, you should attempt to store them in a list like so:
list_name = [randint(0,100) for x in range(x)]
This will generate randint(0,100) x times in a list, which will allow you to access all the values later.
To fix up your code as close to what you were attempting as possible I would do:
import random
def randm(user_numbers):
number = []
for count in range(3):
number.append(random.randint(0, 100))
print(number)
return user_numbers == number
if randm(x):
print('WINNER')
If you are looking for a very pythonic way of doing this task,
you might want to try something like this:
from random import randint
def doLotto(numbers):
# make the lotto number list
lottoNumbers = [randint(0,100) for x in range(len(numbers))]
# check to see if the numbers were equal to the lotto numbers
if numbers == lottoNumbers:
print("You are WinRar!")
else:
print("You Lose!")
I'm assuming from your code (the print() specifically) that you are using python 3.x+
Try to post your whole code. Also mind the indentation when posting, there it looks like the definition of your function would be empty.
I'd do it like this:
import random
def lottery():
win = True
for i in range(3):
guess = random.randint(1,100)
if int(raw_input("Please enter a number...")) != guess:
win = False
break
return win
Let so do this in few steps.
First thing you should learn in writing code is to let separate pieces of code( functions or objects) do different jobs.
First lets create function to make lottery:
def makeLottery(slotCount, maxNumber):
return tuple(random.randint(1,maxNumber) for slot in range(slotCount))
Next lets create function to ask user's guess:
def askGuess(slotCount, maxNumber):
print("take a guess, write {count} numbers separated by space from 1 to {max}".format(count = self.slotCount, max = self.maxNumber))
while True: #we will ask user until he enter sumething suitable
userInput = raw_input()
try:
numbers = parseGuess(userInput,slotCount,maxNumber)
except ValueError as err:
print("please ensure your are entering integer decimal numbers separated by space")
except GuessError as err:
if err.wrongCount: print("please enter exactly {count} numbers".format(count = slotCount))
if err.notInRange: print("all number must be in range from 1 to {max}".format(max = maxNumber))
return numbers
here we are using another function and custom exception class, lets create them:
def parseGuess(userInput, slotCount,maxNumber):
numbers = tuple(map(int,userInput.split()))
if len(numbers) != slotCount : raise GuessError(wrongCount = True)
for number in numbers:
if not 1 <= number <= maxNumber : raise GuessError(notInRange = True)
return numbers
class GuessError(Exception):
def __init__(self,wrongCount = False, notInRange = False):
super(GuessError,self).__init__()
self.wrongCount = wrongCount
self.notInRange = notInRange
and finally function to check solution and conratulate user if he will win:
def checkGuess(lottery,userGuess):
if lottery == userGuess : print "BINGO!!!!"
else : print "Sorry, you lost"
As you can see many functions here uses common data to work. So it should suggest you to collect whole code in single class, let's do it:
class Lottery(object):
def __init__(self, slotCount, maxNumber):
self.slotCount = slotCount
self.maxNumber = maxNumber
self.lottery = tuple(random.randint(1,maxNumber) for slot in range(slotCount))
def askGuess(self):
print("take a guess, write {count} numbers separated by space from 1 to {max}".format(count = self.slotCount, max = self.maxNumber))
while True: #we will ask user until he enter sumething suitable
userInput = raw_input()
try:
numbers = self.parseGuess(userInput)
except ValueError as err:
print("please ensure your are entering integer decimal numbers separated by space")
continue
except GuessError as err:
if err.wrongCount: print("please enter exactly {count} numbers".format(count = self.slotCount))
if err.notInRange: print("all number must be in range from 1 to {max}".format(max = self.maxNumber))
continue
return numbers
def parseGuess(self,userInput):
numbers = tuple(map(int,userInput.split()))
if len(numbers) != self.slotCount : raise GuessError(wrongCount = True)
for number in numbers:
if not 1 <= number <= self.maxNumber : raise GuessError(notInRange = True)
return numbers
def askAndCheck(self):
userGuess = self.askGuess()
if self.lottery == userGuess : print "BINGO!!!!"
else : print "Sorry, you lost"
finally lets check how it works:
>>> lottery = Lottery(3,100)
>>> lottery.askAndCheck()
take a guess, write 3 numbers separated by space from 1 to 100
3
please enter exactly 3 numbers
1 10 1000
all number must be in range from 1 to 100
1 .123 asd
please ensure your are entering integer decimal numbers separated by space
1 2 3
Sorry, you lost
>>> lottery = Lottery(5,1)
>>> lottery.askAndCheck()
take a guess, write 5 numbers separated by space from 1 to 1
1 1 1 1 1
BINGO!!!!

Categories

Resources