I can't seem to make this program to run. There's no error, there's just nothing showing up when I run it. Any help is appreciated1
#Return multiple values
def load():
name=input("enter a name")
num1=int(input("Enter num1: "))
num2=int(input("Enter num2: "))
num3=int(input("Enter num3: "))
return name, num1, num2, num3
def calc(num1, num2, num3):
sum=num1, num2, num3
avg=sum/3
return sum, avg
def output(name, num1, num2, num3, avg, sum):
print("Your name is: ", name)
print("The 3 numbers are: ", num1, num2, num3)
print('The sum is: ',sum )
print("The average is: ", avg)
def main():
name, num1, num2, num3=load()
sum, avg=calc(num1, num2, num3)
output(name, num1, num2, num3, sum, avg)
You need to call main() function, this line will probably throw an exception:
sum=num1, num2, num3
avg=sum/3
change it to:
sum=num1 + num2 + num3
avg=sum/3
As a friendly commenter noted earlier, you were not calling your main() routine (see last line). You had also mixed the sequence of sum and avg calls in the signature of output. Furthermore sum is a Python built-in function. Avoid those. I used raw_input because I'm using Python 2.x, don't let that confuse you. My use of Python 2.x is also the reason for the extra parentheses you'll see in my output.
Overall you were very close to a working solution, nice job for a Beginner!
#Return multiple values
def load():
name=raw_input("enter a name: ")
num1=int(raw_input("Enter num1: "))
num2=int(raw_input("Enter num2: "))
num3=int(raw_input("Enter num3: "))
return name, num1, num2, num3
def calc(num1, num2, num3):
sum1=num1+num2+num3 # sum is a python keyword
avg=sum1/3.0 # avoiding integer division in case you are using python 2.x
return sum1, avg
def output(name, num1, num2, num3, sum1, avg):
print("Your name is: ", name)
print("The 3 numbers are: ", num1, num2, num3)
print('The sum is: ',sum1 )
print("The average is: ", avg)
def main():
name, num1, num2, num3=load()
sum1, avg=calc(num1, num2, num3)
output(name, num1, num2, num3, sum1,avg)
main()
Output:
enter a name: Anton
Enter num1: 1
Enter num2: 2
Enter num3: 3
('Your name is: ', 'Anton')
('The 3 numbers are: ', 1, 2, 3)
('The sum is: ', 6)
('The average is: ', 2.0)
Related
I'm new to python and trying to understand recursion. I'm trying to write a code where someone inputs 2 numbers (Num1, Num2). A calculation will take place until Num1 is greater than Num 2. The result of the calculation's final value should then be outputted.
This is my code:
def Recursive(Num1, Num2):
if Num1 > Num2:
return(10)
else:
if Num1 == Num2:
return(Num1)
else:
return(Num1+Recursive(Num1 * 2, Num2))
Num1=input("Enter number 1: ")
Num2=input("Enter number 2: ")
print("Final value: ", Recursive(Num1, Num2))
This is the output that comes out:
Enter number 1: 1
Enter number 2: 15
That's it. There's no output of my print statement. I'm confused as to what I'm doing wrong here and what I should do.
def Recursive(Num1, Num2):
if Num1 > Num2:
return 10
if Num1 == Num2:
return Num1
print(Num1, Num2)
return Num1 + Recursive(Num1 * 2, Num2)
Num1=int(input("Enter number 1: "))
Num2=int(input("Enter number 2: "))
print("Final value: ", Recursive(Num1, Num2))
This should be working code, the reason why your code was not working was because without the int in Num1 = int( input("") ) the program was reading the number as a string. As a result instead of getting 2 from Num1 * 2 when Num1 is 1 you got 11 as it was multiplying a string instead of an integer.
# Here is an example
a = input("Input a number: ")
b = int(input("input a number: "))
print(f"a is a:{type(a)}\n b is a:{type(b)}")
print(f"{a * 2}\n{b * 2}")
Copy the code above input the two numbers and it should give you a better understanding of what I just said.
The explanation is below:
def displaySortedNumbers(num1, num2, num3):
smallest = num1
if num2 < smallest:
smallest = num2
if num3 < smallest:
smallest = num3
return smallest
def main():
num1, num2, num3 = eval(input("Enter three numbers seperated by commas:"))
print("The numbers are,",displaySortedNumbers(num1, num2, num3))
main()
After the three numbers are entered, the smallest number prints out but the rest of the numbers do not follow. I need the numbers to print out from smallest to largest. I'm not sure what I did wrong.
Your function is only returning the one smallest number of the provided three, you may consider using a list and sorting it instead if that works for you.
def displaySortedNumbers(num1, num2, num3):
s = ""
for c in sorted([num1, num2, num3]):
s += " " + str(c)
return s
The sorted() function takes an iterable argument and returns it sorted by a key, however in this case, if you are just sorting it in increasing order, you do not need to input a key.
In your return statement there is only ´smallest´, not the other variables.
You can store the values in a list, sort it and then return that list, just like this
def displaySortedNumbers(num1, num2, num3):
list = [num1, num2, num3]
list.sort()
return list
In your return statement, you only return one of the three numbers, the one you deem the smallest. But your function is expected to return all three numbers sorted. I'm guessing you can't use the built-in sorted() function and so you need to program the sort manually. You can do a simple bubble sort on 3 numbers by changing your function to be the following:
def displaySortedNumbers(num1, num2, num3):
if num2 < num1:
num1, num2 = num2, num1
if num3 < num2:
num2, num3 = num3, num2
if num2 < num1:
num1, num2 = num2, num1
return num1, num2, num3
This will print all three numbers, properly sorted.
If you CAN use built-in functions, you could simply say:
def displaySortedNumbers(num1, num2, num3):
return sorted((num1, num2, num3))
Try to rewrite like this:
if smallest > num2:
smallest = num2
elif smallest > num3:
smallest = num3
I'm trying to make a list that takes the input from the user and adds it to the list to be printed later when the user asks for it as a part of my final in an intro to python class.the program is supposed to be a payroll calculator
I've tried making an empty list named employees and appending the printout to the list but it won't accept the user input
employees = []
while yes_no == 1:
emp_name = str(input("please enter the employees name"))
num1 = int(input("Please enter the hours you worked "))
num2 = int(input("Please enter your hourly wage "))
print("Employee", emp_name, "Worked ", num1, "hours, and are paid", num2, "$ per hour. Making your salary",
num1 * num2, "$")
employees.append("Employee", emp_name, "Worked ", num1, "hours, and are paid", num2,
"$ per hour. Making your salary",
num1 * num2, "$")
yes = int(input("If you would like to calculate more employees salaries yes or no "))
emp_name = str(input("please enter the employees name"))
num1 = int(input("Please enter the hours you worked "))
num2 = int(input("Please enter your hourly wage "))
print("Employee", emp_name, "Worked ", num1, "hours, and are paid", num2, "$ per hour. Making your salary"
, num1 * num2, "$")
employees.append(str("Employee", emp_name, "Worked ", num1, "hours, and are paid", num2,
"$ per hour. Making your salary",
num1 * num2, "$"))
yes_no = int(input("If you would like to calculate more employees salaries type 1 for yes or or type 0 for no "))
if yes_no == 0:
break
print("Thanks for using my calculator, ", name)
I expected the list to be filled with the inputs but all that happened was my IDE said that append is expecting 1 argument and it got 9.
The bit
employees.append("Employee", emp_name, "Worked ", num1, "hours, and are paid", num2,
"$ per hour. Making your salary",
num1 * num2, "$")
is attempting to call append with 9 different pieces of data (each separated by a ,). If you're thinking of how print takes multiple objects separated by ,s and concatenates them, that's a behavior specific to print and a few other functions. append doesn't behave like that.
You need to format that data as one string. f-strings would be the simplest way:
employees.append(f"Employee {emp_name} worked {num1} hours, and are paid {num2} $ per hour."
f"Making your salary {num1 * num2} $")
Now one single string is being added to the list.
Also note that you'll need to make a similar change for the bit
employees.append(str("Employee", emp_name, "Worked ", num1, "hours, and are paid", num2,
"$ per hour. Making your salary",
num1 * num2, "$"))
str doesn't take that many arguments either.
I would advise you to slow down and test code as you go. Writing massive chunks when you aren't sure what even works will just leave you with headaches and hinder your learning.
I'm trying to build a calculator using 'lambda' as the options for operators. The problem is - I can not find a way to print it so that I will get an answer using 2 numbers that the user selects and one of the operators in the list when all this is equal to what the user chose.
I know I can use 'if' & 'elif' for each operator individually to solve this problem but I deliberately want to use 'lambda'.
I do this to learn how to use this function in this way and also to allow me or anyone who wants to use it in the future to add operators more easily and quickly.
def InputNumber(message):
while True:
try:
userinput = int(input(message))
except ValueError:
print("Not an integer! Please try again.")
else:
return userinput
operators = {
"+": lambda n: num1 + num2,
"*": lambda n: num1 * num2,
"-": lambda n: num1 - num2,
"/": lambda n: num1 / num2,
}
def cal_fund(message):
while True:
operator = (input("Please enter your operation (+, -, *, /): "))
if operator in list(operators.keys()):
return operator
else:
print("Not an operation! Please try again.")
while True:
num1 = InputNumber("Please enter a number: ")
opera = cal_fund("Please enter your operation (+, -, *, /): ")
num2 = InputNumber("Please enter another number: ")
print(operators(num1, num2))
print("-" * 15)
for now, this is the error I get (I know that the problem is that I use dictionary but I didn't find anything else to use for this particular way):
Traceback (most recent call last):
File "", line 34, in <module>
print(operators(num1, num2))
TypeError: 'dict' object is not callable
Problems:
operators is a dictionary that cannot be called. So, operators(..) is not allowed.
lambda in your dictionary values should receive two values for the operation to work.
Fix:
Update your dictionary as:
operators = {
"+": lambda num1, num2: num1 + num2,
"*": lambda num1, num2: num1 * num2,
"-": lambda num1, num2: num1 - num2,
"/": lambda num1, num2: num1 / num2,
}
And then use:
print(operators[opera](num1, num2))
I am trying to write a simple code that prompts users to enter two numbers to determine whether they are evenly divisible:
print 'Enter the following'
num1 = input("Integer:")
num2 = input("Integer:")
evaluation = ((num1 / num 2) / 2)
print num1, "/2", num2, "/2" = ",evaluation
I am new to Python and am seeking advice on how to tweak this code. Any help would be greatly appreciated. Thank you for your time!
You need the modulo operator
print "Enter the following"
num1 = input("Integer:")
num2 = input("Integer:")
evaluation = num1 % num2
if evaluation == 0:
print num1, "/", num2, " evenly divides"
else:
print num1, "/", num2, " does not evenly divide"