How Can I Use a Variable From One Function in Another - python-3.x

I'm trying to write a code where there are a bunch of if statements in each function. I want to be able to use a variable from a previous function and then add that variable into another function.
Here is an example:
def main():
name = input('What is your name?')
age = int(input('What is your age?'))
number = int(input('What is your favourite number?'))
if number > 0:
print('Your favourite number is %d and it is positive.' % (number))
elif number < 0:
print('Your favourite number is %d and it is negative.' % (number))
else:
print('Your favourite number is %d and it is equal to 0.' % (number))
subtract()
def subtract():
salary = float(input('Enter your monthly salary.'))
expenses = float(input('Enter your monthly expenses'))
result = (salary - expenses)
if result < 0:
print('Save more!')
else:
print('Congratulations on saving!')
def final():
percentage = result / a
finalpercent = percentage * 100
if finalpercent == 0:
print('No money!!')
elif finalpercent < 50:
print('Getting there...')
else:
print('You have lots of money!!')
main()
What I want is to use the result variable from def subtract(): function in the def final(): function?

Make the result variable from the subtract function the return value of that function.
Something like this:
def main():
name = input('What is your name?')
age = int(input('What is your age?'))
number = int(input('What is your favourite number?'))
if number > 0:
print('Your favourite number is %d and it is positive.' % (number))
elif number < 0:
print('Your favourite number is %d and it is negative.' % (number))
else:
print('Your favourite number is %d and it is equal to 0.' % (number))
final(subtract()) # RESULT IS RETURNED BY SUBTRACT AND THEN USED BY FINAL AS PARAMETER
def subtract():
salary = float(input('Enter your monthly salary.'))
expenses = float(input('Enter your monthly expenses'))
result = (salary - expenses)
if result < 0:
print('Save more!')
else:
print('Congratulations on saving!')
return result
def final(result):
percentage = result / a
finalpercent = percentage * 100
if finalpercent == 0:
print('No money!!')
elif finalpercent < 50:
print('Getting there...')
else:
print('You have lots of money!!')
main()
Also the variable a is not defined in the final function, that will cause an error, so check that too :).

Use Global variable. Creating a Global variable means you could access that variable from any function or class.
def main():
name = input('What is your name? ')
age = int(input('What is your age? '))
number = int(input('What is your favourite number? '))
if number > 0:
print('Your favourite number is %d and it is positive.' % (number))
elif number < 0:
print('Your favourite number is %d and it is negative. ' % (number))
else:
print('Your favourite number is Zero.')
subtract()
def subtract():
global salary # Declaring salary as Global Variable
salary = float(input('Enter your monthly salary: '))
expenses = float(input('Enter your monthly expenses: '))
global result # Declaring result as Global Variable
result = (salary - expenses)
if result < 0:
print('Save more!')
else:
print('Congratulations on saving!')
final()
def final():
percentage = result / salary
finalpercent = percentage * 100
if finalpercent == 0:
print('No money!!')
elif finalpercent < 50:
print('Getting there...')
else:
print('You have lots of money!!')
main()
I convert those local variable salary and result using global keyword. so that I could use that two variables outside of that function.
Another Approach is to pass that variable as an argument by calling final function. Like this...
def main():
name = input('What is your name? ')
age = int(input('What is your age? '))
number = int(input('What is your favourite number? '))
if number > 0:
print('Your favourite number is %d and it is positive.' % (number))
elif number < 0:
print('Your favourite number is %d and it is negative. ' % (number))
else:
print('Your favourite number is Zero.')
subtract()
def subtract():
salary = float(input('Enter your monthly salary: '))
expenses = float(input('Enter your monthly expenses: '))
result = (salary - expenses)
if result < 0:
print('Save more!')
else:
print('Congratulations on saving!')
final(result, salary) # calling final function by passing it as argument
def final(result, salary):
percentage = result / salary
finalpercent = percentage * 100
if finalpercent == 0:
print('No money!!')
elif finalpercent < 50:
print('Getting there...')
else:
print('You have lots of money!!')
main()

Related

Number Guessing game Computer Playing

I have created this game. User is giving a number from 1 to 100. Computer is trying to guess it. User is giving hint to computer to go lower or go higher. I am open for any feedback.
Thank you in advance.
import os
import random
os.system('clear')
user = int(input("Please enter a number between 1-100: "))
print("Your Number is: " + str(user))
comp_list = list(range(1,101))
comp_selection = random.choice(comp_list)
count = 0
def game(num, a = 1, b = 100):
global count
print("I have chosen " + str(num) + "\nShould I go Higher or Lower or Correct? ")
user = input("Your Selection: ")
if user == "L":
count = count + 1
low_game(a, num)
elif user == "H":
count = count + 1
high_game(num, b)
else:
print("I have guessed correctly in " + str(count) + " tries")
def low_game(old_low, new_High):
x = new_High
new_comp_list = list(range(old_low, x))
new_comp_selection = random.choice(new_comp_list)
game(new_comp_selection, old_low, x)
def high_game(new_low, old_high):
x = new_low + 1
new_comp_list = list(range(x, old_high))
new_comp_selection = random.choice(new_comp_list)
game(new_comp_selection,x, old_high)
game(comp_selection)
I agree, you have over complicated the game with recursive functons.
Here is a much simplified game with penalties for player who does not answer correctly
or falsifies the answer:)
import sys, random
wins = 0
loss = 0
while 1:
user = input('Please enter a number between 1-100: (return or x = quit) > ' )
if user in [ '', 'x' ]:
break
elif user.isnumeric():
user = int( user )
if user < 1 or user > 100:
sys.stdout.write( 'Number must be between 1 and 100!!\n' )
else:
low, high, count = 1, 100, 0
while 1:
p = random.randint( low, high )
count += 1
while 1:
answer = input( f'Is your number {p}? Y/N > ').upper()
if answer in [ 'Y','N' ]:
break
else:
sys.stderr.write( 'Answer must be Y or N\n' )
if answer == 'N':
if p != user:
if input( f'Is my number (H)igher or (L)ower? > ').upper() == 'H':
if user < p:
high = p - 1
else:
sys.stderr.write( f'Wrong!! Your number was lower. You loss\n' )
loss =+ 1
break
else:
if user > p:
low = p + 1
else:
sys.stderr.write( f'Wrong!! Your number higher. You loss\n' )
loss =+ 1
break
else:
sys.stderr.write( f'Cheat!! Your number is {user}!! You loss\n')
loss =+ 1
break
else:
if user == p:
sys.stdout.write( f'I guessed Correctly in {count} guesses\n' )
wins += 1
else:
sys.stderr.write( f'Cheat!! This is not your number. You loss\n' )
loss =+ 1
break
print( f'Computer won = {wins} : You lost = {loss}' )
Happy coding.
You have really overly complicated the problem. The basic process flow is to have the computer guess a number within a fixed range of possible numbers. If the guess is incorrect, the user tells the computer how to adjust the list by either taking the guessed number as the low end or the high end of the guessing range. So to accomplish this, I would do the following:
from random import randint
# Function to request input and verify input type is valid
def getInput(prompt, respType= None):
while True:
resp = input(prompt)
if respType == str or respType == None:
break
else:
try:
resp = respType(resp)
break
except ValueError:
print('Invalid input, please try again')
return resp
def GuessingGame():
MAX_GUESSES = 10 # Arbritray Fixed Number of Guesses
# The Game Preamble
print('Welcome to the Game\nIn this game you will be asked to provide a number between 1 and 100 inclusive')
print('The Computer will attempt to guess your number in ten or fewer guesses, for each guess you will respond by telling the computer: ')
print('either:\n High - indicating the computer should guess higher\n Low - indicating the computer should guess lower, or')
print(' Yes - indicating the computer guessed correctly.')
# The Game
resp = getInput('Would You Like To Play?, Respond Yes/No ')
while True:
secret_number = None
if resp.lower()[0] == 'n':
return
guess_count = 0
guess_range = [0, 100]
secret_number = getInput('Enter an Integer between 1 and 100 inclusive', respType= int)
print(f'Your secret number is {secret_number}')
while guess_count <= MAX_GUESSES:
guess = randint(guess_range[0], guess_range[1]+1)
guess_count += 1
resp =getInput(f'The computer Guesses {guess} is this correct? (High?Low/Yes) ')
if resp.lower()[0] == 'y':
break
else:
if resp.lower()[0] == 'l':
guess_range[1] = guess - 1
else:
guess_range[0] = guess + 1
if guess == secret_number:
print (f'The Computer has Won by Guessing your secret number {secret_number}')
else:
print(f'The Computer failed to guess your secret number {secret_number}')
resp = getInput('Would You Like To Play Again?, Respond Yes/No ')

Issues with updating an inventory in Python Code

I'm working on a program for a final in a class and I'm having some troubles with updating the created inventory. I've been able to get it to the point where I can do everything else in the code, but when I go to run the update section, nothing updates. I'd be really grateful for any help with this. All of my code is included below
class Automobile:
def __init__(self, make, model, year, color, mileage=0):
self._make = make
self._model = model
self._year = year
self._color = color
self._mileage = mileage
#classmethod
def make_vehicle(cls):
make = input('Enter vehicle make: ')
model = input('Enter vehicle model: ')
while True:
year = input('Enter vehicle year: ')
try:
year = int(year)
break
except ValueError:
print("Year must be a number", file=sys.stderr)
color = input('Enter vehicle color: ')
while True:
mileage = input('Enter vehicle mileage: ')
try:
mileage = int(mileage)
break
except ValueError:
print("Mileage must be an integer", file=sys.stderr)
return cls(make, model, year, color, mileage)
def add_Vehicle(self):
vehicle = Automobile.make_vehicle()
self.vehicles.append(vehicle)
def __str__(self):
return '\t'.join(str(x) for x in [self._make, self._model, self._year, self._color, self._mileage])
class Inventory:
def __init__(self):
self.vehicles = []
def add_vehicle(self):
vehicle = Automobile.make_vehicle()
self.vehicles.append(vehicle)
def viewInventory(self):
print('\t'.join(['','Make', 'Model','Year', 'Color', 'Mileage']))
for idx, vehicle in enumerate(self.vehicles) :
print(idx + 1, end='\t')
print(vehicle)
print("This is the Vehicle Inventory Program.")
inventory = Inventory()
while True:
print ("""
1.Add a Vehicle
2.Delete a Vehicle
3.View Inventory
4.Update Inventory
5.Export Inventory
6.Quit
""")
ans=input("What would you like to do? ")
if ans=="1":
#add a vehicle
inventory.add_vehicle()
elif ans=='2':
#delete a vehicle
if len(inventory.vehicles) < 1:
print('Sorry there are no vehicles currently in inventory')
continue
inventory.viewInventory()
item = int(input('Please enter the number associated with the vehicle to be removed: '))
if item - 1 > len(inventory.vehicles):
print('This is an invalid number')
else:
inventory.vehicles.remove(inventory.vehicles[item - 1])
print ()
print('This vehicle has been removed')
elif ans == '3':
#list all the vehicles
if len(inventory.vehicles) < 1:
print('Sorry there are no vehicles currently in inventory')
continue
inventory.viewInventory()
elif ans == '4':
#edit vehicle
if len(inventory.vehicles) < 1:
print('Sorry there are no vehicles currently in inventory')
continue
inventory.viewInventory()
item = int(input('Please enter the number associated with the vehicle to be updated: '))
if item - 1 > len(inventory.vehicles):
print('This is an invalid number')
else:
if Inventory().add_vehicle() == True :
inventory.vehicles.remove(inventory.vehicles[item - 1])
inventory.vehicles.insert(item - 1, Automobile)
print('This vehicle has been updated')
elif ans == '5':
#export inventory to file
if len(inventory.vehicles) < 1:
print('Sorry there are no vehicles currently in inventory')
continue
f = open('vehicle_inventory.txt', 'w')
f.write('\t'.join(['Make', 'Model','Year', 'Color', 'Mileage']))
f.write('\n')
for vechicle in inventory.vehicles:
f.write('%s\n' %vechicle)
f.close()
print('The vehicle inventory has been exported to a file')
elif ans == '6':
#exit the loop
print('Thank you for utilizing the Vehicle Inventory Program. Have a nice day.')
break
else:
print('invalid')
As already mentioned in the comments, the if condition is wrong and also you are inserting the class Automobile. What you need probably is Automobile.make_vehicle(). So, update the code,
elif ans == '4':
#edit vehicle
if len(inventory.vehicles) < 1:
print('Sorry there are no vehicles currently in inventory')
continue
inventory.viewInventory()
item = int(input('Please enter the number associated with the vehicle to be updated: '))
if item - 1 > len(inventory.vehicles):
print('This is an invalid number')
else:
inventory.vehicles.remove(inventory.vehicles[item - 1])
inventory.vehicles.insert(item - 1, Automobile.make_vehicle())
print('This vehicle has been updated')

Create a function to test a value between two ranges

I want to create a function within this code to kick the user back if the input values are outside of the input ranges, so if the first number with the second number doesn't exceed the high range or fall below the low rang with any of the calculations, if it does it would return with an error message and prompt to try again.
while True:
try:
number1 = int(input('Enter your Lower Range:'))
if number1 < -100 or number1 > 100:
raise ValueError
break
except ValueError:
print("Invalid integer. The number must be between -100 and 100.")
while True:
try:
number2 = int(input('Enter your Higher Range: '))
if number2 < -100 or number2 > 100:
raise ValueError
break
except ValueError:
print("Invalid integer. The number must be between -100 and 100.")
while True:
try:
a = int(input('Enter your first number: '))
if a < -100 or a > 100:
raise ValueError
break
except ValueError:
print("Invalid integer. The number must be between -100 and 100.")
while True:
try:
b = int(input('Enter your second number: '))
if b < -100 or b > 100:
raise ValueError
break
except ValueError:
print("Invalid integer. The number must be between -100 and 100.")
print('{} + {} = '.format(a, b))
print(a + b)
print('{} - {} = '.format(a, b))
print(a - b)
print('{} * {} = '.format(a, b))
print(a * b)
print('{} / {} = '.format(a, b))
print(a / b)
restart = input("Would you like to restart this program?")
if restart == "yes" or restart == "y":
main()
if restart == "n" or restart == "no":
print ("Script terminating. Goodbye.")
print ("Thanks for using my calculator!")
main()
If you need this into a method, you can try the following:
def read_number(text, lower=-100, higher=100):
while True:
number = int(input(text))
if number < lower or number > higher:
print("Invalid integer. The number must be between {} and {}.".format(lower, higher)
pass
else:
return number
The method read_number() above get the input and returns it only on condition, so you can use it directly to a variable:
def main():
number1 = read_number('Enter your Lower Range: ')
number2 = read_number('Enter your Higher Range: ')
a = read_number('Enter your first number: ')
b = read_number('Enter your second number: ')
# do something ...
I don't know if is it you want. If not, try to explain it with more clarity.
However, I hope has helped you.
I've tried my best to design a function. I hope this helps:
def my_calculator():
while True:
try:
number1 = int(input('Enter your Lower Range:'))
if number1 < -100 or number1 > 100:
raise ValueError
break
except ValueError:
print("Invalid integer. The number must be between -100 and 100.")
while True:
try:
number2 = int(input('Enter your Higher Range: '))
if number2 < -100 or number2 > 100:
raise ValueError
break
except ValueError:
print("Invalid integer. The number must be between -100 and 100.")
while True:
try:
a = int(input('Enter your first number: '))
if a < -100 or a > 100:
raise ValueError
break
except ValueError:
print("Invalid integer. The number must be between -100 and 100.")
while True:
try:
b = int(input('Enter your second number: '))
if b < -100 or b > 100:
raise ValueError
break
except ValueError:
print("Invalid integer. The number must be between -100 and 100.")
print('{} + {} = '.format(a, b))
addition = a + b
print(addition)
print('{} - {} = '.format(a, b))
diff = a - b
print(diff)
print('{} * {} = '.format(a, b))
prod = a * b
print(prod)
quo = None
try:
quo = a / b
except ZeroDivisionError as ze:
print("Division by zero not allowed; Please retry.")
my_calculator()
print('{} / {} = '.format(a, b))
print(quo) if quo else print()
results = [addition, diff, prod, quo]
try:
if not all(-100 < i < 100 for i in results):
raise ValueError
except ValueError as ve:
print("Some of the results of calculation exceed 100 or are less than -100."
"The results must be between -100 and 100. Please retry.")
my_calculator()
restart = input("Would you like to restart this program?")
if restart == "yes" or restart == "y":
my_calculator()
if restart == "n" or restart == "no":
print("Script terminating. Goodbye.")
print("Thanks for using my calculator!")
if __name__ == "__main__":
my_calculator()

Python multiplication function not working

I am a beginner to python wanted to make a simple calculator app which takes multiple inputs for the case of operators 'Add' and 'Multiply'. I was having a problem with the operator 'Multiply where wrong outputs are being diplayed. So can any one help me with the syntax. I would also be thankful if you help me improve the other parts of the code.
print("Type Add to add the numbers")
print("Type Subtract to subtract the numbers")
print("Type Multiply to multiply the numbers")
print("Type Divide to divide the numbers")
Operator = input()
if Operator == "Add":
print("Type the number of numbers you want to add" )
Num_Numbers = range(0,int(input()))
Total = 0
for Count in Num_Numbers:
print("Type Num"+str(Count+1))
Count = int(input())
Total = Total + Count
print(Total)
elif Operator == "Subtract":
print("Type the first number")
Num1 = float(input())
print("Type the second number")
Num2 = float(input())
print(Num1 - Num2)
elif Operator == "Multiply":
print("Type the number of numbers you want to multiply" )
Num_Numbers = range(0,int(input()))
Total = 0
Counter = 0
for Count in Num_Numbers:
print("Type Num"+str(Count+1))
count = int(input())
if Counter != 0:
Counter = Counter + 1
while Total == 0:
Total = Total + count
print("Code implemented")
else:
continue
Total = Total * count
print(Total)
elif Operator == "Divide":
try:
print("Type the first number")
Num1 = float(input())
print("Type the second number")
Num2 = float(input())
print(Num1 / Num2)
except ZeroDivisionError:
print("Division by zero not possible")
else:
print("Operator Unidentified!")
elif Operator == "Multiply":
print("Type the number of numbers you want to multiply" )
Num_Numbers = range(0,int(input()))
Total = 1.0
for Count in Num_Numbers:
print("Type Num"+str(Count+1))
count = float(input()) #chances are the number can be float
Total = Total * count
print(Total)
Just simplified your code!
You put the start Total as 0. 0 multiplied by anything is 0, so you should start at 1:
Total = 1
It's more math than programming.
You also need to remove the strange lines (what are they for?!) shown below:
Counter = 0
#some needed lines
if Counter != 0:
Counter = Counter + 1
while Total == 0:
Total = Total + count
print("Code implemented")
else:
continue
Note for the future that:
var=var+1
Is quicker written as:
var+=1
And the same for other operators, and:
else:
continue
Is obsolete, you don't need a else statement for every if.

Cannot keep certain numbers from averaging

I need help. I'm trying to run the program below. When I enter a number above 100 or below 0 I need it to disregard that input any advice?
total = 0.0
count = 0
data = int(input("Enter a number or 999 to quit: "))
while data != "":
count += 1
number = float(data)
total += number
data = int(input("Enter a number or 999 to quit: "))
try:
data = int(data)
except ValueError:
pass
average = round(total) / count
if data == 999:
break
elif data >= 100:
print("error in value")
elif data <= 0:
number = 0
print("error in value")
print("These", count, "scores average as: ", round(average, 1))
You could move the average = ... line behind the checking for invalid numbers and add continue to the checks for invalid numbers. So the last lines would end up like this:
if data == 999:
break
elif data >= 100:
print("error in value")
continue
elif data <= 0:
print("error in value")
continue
average = round(total) / count

Resources