Why doesn't function loop, loop on input? - python-3.7

I want to use the function serial_circuit with three different inputs (1,2,3). The function is suppose to accept multiple inputs from user until
user hits return, end program and sums up all inputs. The program only takes one input and display it.
def serial_circuit(num1):
num = 0
while(True):
try:
num += num1
except:
break
return num
print("1.Solve for serial resistance: ")
print("2.Solve for serial coils: ")
print("3.Solve for parallel capacitors: ")
choice = input("Enter choice: ")
if choice == '1':
num1 = float(input("Enter resistor value: "))
num = serial_circuit(num1)
print(f"Total resistance = {(num)} ohms")
elif choice == '2':
num1 = float(input("Enter coil value: "))
num = serial_circuit(num1)
print(f"Total inductance = {(num)} henrys")
elif choice == '3':
num1 = float(input("Enter capacitor value: "))
num = serial_circuit(num1)
print(f"Total capacitance = {(num):.6f} farads")

One of your problems is that you have the return statement inside the loop - notice your indentation - during the first iteration of the loop the last thing that will happen within the loop is returning from the serial_circuit function.
Another problem is that you are asking for the input only once - outside of the loop.
Take a look at this solution:
def serial_circuit(text):
num = 0
finishedEntering = False
while(not finishedEntering):
try:
received_input = input(text)
if received_input == "":
finishedEntering = True
else:
num1 = float(received_input)
num += num1
except:
break
return num
print("1.Solve for serial resistance: ")
print("2.Solve for serial coils: ")
print("3.Solve for parallel capacitors: ")
choice = input("Enter choice: ")
if choice == '1':
num = serial_circuit("Enter resistor value or hit enter to finish: ")
print(f"Total resistance = {(num)} ohms")
elif choice == '2':
num = serial_circuit("Enter coil value or hit enter to finish: ")
print(f"Total inductance = {(num)} henrys")
elif choice == '3':
num = serial_circuit("Enter capacitor value or hit enter to finish: ")
print(f"Total capacitance = {(num):.6f} farads")

Related

I'm having trouble with the code where the budget variable wasn't deducting throughout the loop. It instead do nothing or sometimes add up

enter image description hereI'm making an inventory system code and I'm a bit stuck finding a solution to the substraction problem, when I choose "ADD" and entering the input the formula wasn't getting the accurate outcome. For example, if I input Paper001 then its quantity, the output is fine at first but when input another item, the deduction instead becoming addition or sometimes doesn't do anything.
I tried dividing the values in the dictionary in 3 conditions but it turns out even worse.
while True:
try:
bg = float(input("Enter your budget : "))
print("-----------------------------------------------------------")
print(" Item name Item code Item price(Per set) \n")
print("1.Bond Paper : Paper001 100 PHP\n2.Yellow Paper : Paper002 50 PHP\n3.Intermediate Paper : Paper003 20 PHP\n\n")
s = bg
except ValueError:
print("PRINT NUMBER AS A AMOUNT")
continue
else:
break
a ={"name":[], "quant":[], "price":[]}
# converting dictionary to list for further updation
b = list(a.values())
# variable na value of "name" from dictionary 'a'
na = b[0]
# variable qu value of "quant" from dictionary 'a'
qu = b[1]
# This loop terminates when user select 2.EXIT option when asked
# in try it will ask user for an option as an integer (1 or 2)
# if correct then proceed else continue asking options
while True:
try:
print("-----------------------------------------------------------")
ch = int(input("1.ADD\n2.STORAGE LIST\n3.Customer purchase\n4.EXIT\nEnter your choice : "))
except ValueError:
print("\nERROR: Choose only digits from the given option")
continue
else:
# check the budget is greater than zero and option selected
# by user is 1 i.e. to add an item
if ch == 1 and s>0:
p_list={'Paper001':100,'Paper002':50,'Paper003':20}
pn = input("Enter item code : ")
if pn in p_list.keys():
q = int(input("Enter quantity : "))
else:
print("-----------------------------------------------------------")
print("Code is invalid")
continue
#checks if item name is already in the list
if pn in na:
ind = na.index(pn)
# remove quantity from "quant" index of the product
qu.remove(qu[ind])
# new value will be added to the previous value of user's quantity
qu.insert(ind, q)
tpr = (q+q)*p_list[pn]
print(f" Total product price:",tpr)
s = bg-tpr
print("\namount left", s)
else:
# append value of in "name", "quantity", "price"
na.append(pn)
# as na = b[0] it will append all the value in the
# list eg: "name"🙁"rice"]
qu.append(q)
# after appending new value the sum in price
# as to be calculated
tpr = q*p_list[pn]
print("\nTotal product price:",tpr)
s = bg-tpr
if s==0:
print("No more budget left")
print("\nAmount left :", s)
elif s>0:
print("\nAmount left :", s)
else:
print("Insufficient budget. Cannot buy item.")
print("Please restart and re-enter your budget.")
break
elif ch ==2 :
print("\n\n\nStorage list")
print("Item name Stocks ")
for i in range(len(na)):
print(f"{na[i]} {qu[i]}")
continue
elif ch == 3:
print("-----------------------------------------------------------")
p_list={'Paper001':100,'Paper002':50,'Paper003':20}
print("\n\n\nStorage list")
print("Item name Stocks ")
for i in range(len(na)):
print(f"{na[i]} {qu[i]}")
co = input("\nEnter customer's order : ")
if co in p_list.keys():
q = int(input("Enter quantity : "))
sl = qu[i]-q
print("Item is sold!")
print("Stocks left :",sl)
if sl <=0:
print("Please add new items!")
else:
print("-----------------------------------------------------------")
print("Code is invalid")
continue
elif ch==4:
print("")
print("\nThank your for shopping with us!")
break
elif s==0:
print("NO BUDGET LEFT. UNABLE TO ADD ITEMS.")
else:
print("ERROR: Choose only the digits given from the option.")

Math operations with one line input. Any suggestions to improve this code?

'''I wrote this program so I could do the math operations like I do in a terminal. just add the numbers and the operators and hit enter. that will give me the result.
With this code same can be done. I am sharing this so I can get some feedback on how to make this more efficient, add more functionality to it, etc...'''
# Basic operator functions
def add(num1, num2):
return num1 + num2
def sub(num1, num2):
return num1 - num2
def mul(num1, num2):
return num1 * num2
def dev(num1, num2):
return num1 / num2
operators = {'+': add, '-': sub, '*': mul, '/': dev}
def splitter(text):
"""Function to split an input string containing number and operators
in a list separating numbers and operators in given sequence"""
numbers = ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9', "."]
delimiter = ["+", "-", "*", "/"]
elist = []
num = ""
for char in text:
if char in numbers:
num += char
elif char in delimiter:
elist.append(float(num))
elist.append(char)
num = ""
elif char == " ":
continue
else:
print(f"Invalid input: {char}")
break
elist.append(float(num))
return elist
def calculator(splitter1):
result = splitter1
# print(result)
total = 0
while len(result) > 1:
if "/" in result:
o_index = result.index("/")
n1 = (o_index - 1)
n2 = (o_index + 1)
total = dev(result[n1], result[n2])
result[o_index] = total
result.pop(n1)
result.pop(o_index)
elif "*" in result:
o_index = result.index("*")
n1 = (o_index - 1)
n2 = (o_index + 1)
total = mul(result[n1], result[n2])
result[o_index] = total
result.pop(n1)
result.pop(o_index)
elif "+" in result:
o_index = result.index("+")
n1 = (o_index - 1)
n2 = (o_index + 1)
total = add(result[n1], result[n2])
result[o_index] = total
result.pop(n1)
result.pop(o_index)
elif "-" in result:
o_index = result.index("-")
n1 = (o_index - 1)
n2 = (o_index + 1)
total = sub(result[n1], result[n2])
result[o_index] = total
result.pop(n1)
result.pop(o_index)
else:
continue
# print(result)
return total
repeat = "y"
while repeat == "y":
cal = input('calc: ')
calculation = calculator(splitter(cal))
print(calculation)
repeat = input("Would you like to continue to a new calculation? type 'y' to continue: ").lower()
else:
print("Thank you!")

Is it possible to use an alternative to if/else statements in repl python 3.7?

Is there a better solution in python for making large strings of if/else statements for a random input using import random on version 3.7? I feel like it's a bit counterproductive to write the same if else statements for each input. If not, are there any ways to make my code more efficient?
if G.casefold() == "a":
Boss_Health = Boss_Health - A
print("user dealt", A, "damage with A")
print("Boss health:", Boss_Health)
print("Health:", Health)
print("Bosses turn")
print("")
G = random.randint(1, 20)
if G == 1:
Boss_L = Boss_L + Boss_A
print("Boss_L has been upgraded by", Boss_A, "and now deals",
Boss_L, "damage")
print("Boss Health:", Boss_Health)
print("Health:", Health)
print("users turn")
str(G)
G = input()
if G == 2:
Boss_Health = Boss_Health + Boss_B
print("Boss healed", Boss_B, "hp to Boss")
print("Boss Health:", Boss_Health)
print("Health:", Health)
print("users turn")
str(G)
G = input()
if G == 3:
Boss_M = Boss_M + Boss_B
print("Boss_M has been upgraded by", Boss_B, "and now deals",
Boss_M, "damage")
print("Boss Health:", Boss_Health)
print("Health:", Health)
print("users turn")
str(G)
G = input()
Usually, the first bit to look for is where there is duplication of code. In your program, I saw the following lines entered repeatedly:
print("Boss Health:", Boss_Health)
print("Health:", Health)
print("users turn")
str(G)
G = input()
Those would be a candidate to group into some type of function. Realizing that the value of "G" gets either a manual entry or a random entry, following is a version of your code with repeated code pulled out and placed into a separate function.
import random
def Vitals(b_h, h, rndm = None): # Separate function to handle repeated statements
print("Boss health:", b_h)
print("Health:", h)
print("Bosses turn")
print("")
z = " "
if rndm == "gen":
z = random.randint(1, 20)
else:
z = input("Enter your choice: ")
return z
def game_loop():
A = 1
G = " "
Boss_Health = 10
Boss_A = 2
Boss_B = 2
Boss_L = 1
Health = 20
while True:
if G.casefold() == "a":
Boss_Health = Boss_Health - A
print("user dealt", A, "damage with A")
G = Vitals(Boss_Health, Health, "gen")
if G == 1:
Boss_L = Boss_L + Boss_A
print("Boss_L has been upgraded by", Boss_A, "and now deals", Boss_L, "damage")
G = Vitals(Boss_Health, Health)
if G == 2:
Boss_Health = Boss_Health + Boss_B
print("Boss healed", Boss_B, "hp to Boss")
G = Vitals(Boss_Health, Health)
if G == 3:
Boss_M = Boss_M + Boss_B
print("Boss_M has been upgraded by", Boss_B, "and now deals", Boss_M, "damage")
G = Vitals(Boss_Health, Health)
if G == "q" or G == "Q":
break
G = Vitals(Boss_Health, Health)
return
game_loop()
Not having your full program, I improvised to create a user input loop to test this out. But the net effect is a shorter program that cuts down on repeated code which also reduces the chance of some inconsistencies creeping into the various blocks of code that utilize the function.
Give that a try.

How to remove a single number from a list with multiples of that number

As I'm a beginner in coding I wanted to try to find the first three repeated numbers in a list. My problem is that in my code when there is a number repeated three, the code breaks.
The usual, remove, pop, and del, don't work as they delete one element in the list.
import random
r = random.randint
string = ""
def first_repeat(myList):
myList = sorted(list(myList))
print(myList)
number = 0
final_numbers = []
loop = 0
while loop < 2:
try:
if number == 0:
number += 1
else:
if myList[loop] == myList[loop-1]:
final_numbers.append(myList[loop])
else:
myList.pop(loop)
myList.pop (loop-1)
number = 0
if loop == 0 :
loop += 1
else:
loop -= 1
if len(final_numbers) > 3:
return final_numbers[0], final_numbers[1], final_numbers[2]
if len(myList) <=1:
loop += 2
except:
continue
return final_numbers
for n in range(20):
string = string+str(r(0,9))
print(first_repeat(string))
the expected result should be at the first three repeated numbers.
I added some print statements so you can go through your program and find out where the logic is wrong with your code.
import random
r = random.randint
string = ""
def first_repeat(myList):
myList = sorted(list(myList))
print(myList)
number = 0
final_numbers = []
loop = 0
while loop < 2:
print( 'inside while loop: loop = {}'.format( loop ))
try:
if number == 0:
number += 1
else:
if myList[loop] == myList[loop-1]:
print( 'in -> if myList[loop] == myList[loop-1]' )
final_numbers.append(myList[loop])
print( 'final_numbers: [{}]'.format( ','.join( final_numbers )))
else:
print( 'in first -> else' )
myList.pop(loop)
myList.pop (loop-1)
number = 0
print( 'myList: [{}]'.format( ','.join( myList ) ))
if loop == 0 :
loop += 1
else:
loop -= 1
if len(final_numbers) > 3:
print( 'returning final numbers' )
print( final_numbers )
return final_numbers[0], final_numbers[1], final_numbers[2]
if len(myList) <=1:
loop += 2
except:
continue
print( 'at end of this loop final numbers is: [{}]'.format( ','.join( final_numbers)))
print( 'press any key to continue loop: ')
input()
return final_numbers
for n in range(20):
string = string+str(r(0,9))
print(first_repeat(string))
Following is a method to do it taking advantage of pythons defaultdict
https://docs.python.org/2/library/collections.html#collections.defaultdict
#import defaultdict to keep track of number counts
from collections import defaultdict
#changed parameter name since you are passing in a string, not a list
def first_repeat( numbers_string ):
#create a dictionary - defaulddict( int ) is a dictionary with keys
#instantiated to 0 - (instead of throwing a key error)
number_count = defaultdict( int )
#convert your string to a list of integers - look up list iterations
numbers = [ int( s ) for s in list( numbers )]
# to store the repeated numbers
first_three_repeats = []
for number in numbers:
# for each number in the list, increment when it is seen
number_count[number] += 1
#at first occurence of 3 numbers, return the number
if number_count[number] == 2:
first_three_repeats.append( number )
if len( first_three_repeats ) == 3:
return first_three_repeats
#if here - not three occurrences of repeated numbers
return []
for n in range(20):
string = string+str(r(0,9))
print( findFirstThreeNumbers( string ))

find out min and max in python 3

5.2 Write a program that repeatedly prompts a user for integer numbers until the user enters 'done'. Once 'done' is entered, print out the largest and smallest of the numbers. If the user enters anything other than a valid number catch it with a try/except and put out an appropriate message and ignore the number. Enter 7, 2, bob, 10, and 4 and match the output below.
largest = None
smallest = None
while True:
num = input("Enter a number: ")
if num == "done":
break
print(num)
print("Maximum", largest)
and the output must be like this
Invalid input
Maximum is 10
Minimum is 2
somebody please help me with this????? enter image description here
I think this will do your work,
With simple if conditions
# Defining two variables to None.
largest = None
smallest = None
# starting an infinite loop
while True:
num = input("Enter a number: ")
# try block to capture ValueError
try:
if num == "done":
break
# assign the values of largest and smallest to num if its None ( on first iteration)
if largest is None:
largest = int(num)
if smallest is None:
smallest = int(num)
# changing the values of it greater or smaller
if int(num) > largest:
largest = int(num)
if int(num) < smallest:
smallest = int(num)
# capture the type error and ignores.
except ValueError:
print("ignored.")
continue
print("Maximum: " + str(largest))
print("Minimum: " + str(smallest))
By making use of list and it's methods
# Defining an empty list.
myList = []
# starting an infinite loop
while True:
num = input("Enter a number: ")
# try block to capture ValueError
try:
if num == "done":
break
# append the entered number to list if valid
myList.append(int(num))
# catches value error and ignores it
except ValueError:
print("ignored.")
continue
# prints maximum and min
if len(myList) > 0:
print("Maximum: " + str(max(myList)))
print("Minimum: " + str(min(myList)))
else:
print("List is empty")
largest = None
smallest = None
while True:
try:
num = input("Enter a number: ")
if num == "done":
break
num = int(num)
if largest is None or largest < num:
largest = num
elif smallest is None or smallest > num:
smallest = num
except ValueError:
print("Invalid input")
print ("Maximum is", largest)
print ("Minimum is", smallest)
largest = None
smallest = None
while True:
num = input("Enter a number: ")
if num == "done" :
break
try:
n = int(num)
except:
print ('Invalid input')
continue
if largest is None or n > largest:
largest = n
if smallest is None or n < smallest:
smallest = n
print("Maximum is", largest)
print("Minimum is", smallest)
#Print out largest and smallest number
largest=None
smallest=None
while True:
n = input('Enter a number: ')
if n == "done":
break
try:
num=int(n)
if largest is None:
largest = num
elif num > largest:
largest = num
if smallest is None:
smallest = num
elif num < smallest:
smallest = num
except:
print("Invalid input")
print('maximum:', largest)
print('Minimum:', smallest)