I am upskilling a bit with my Python and have a passing values question (Got the task off an online python task website).
Call 'UserInput' twice and assign it to two different variables.
Pass the results of this to the Adder function.
Output the result of the Adder function as part of a sentence.
I am unsure about running the same function twice and setting them as separate variables, and running it in main.
This is mine so far:
def Adder(n1,n2):
ans = n1+n2
#print(ans)
print(n1)
def userinput():
try:
n1 = int(input("Please enter an integer!: "))
except:
print("that is not an integer try again!")
else:
print("thank you for this integer")
print(n1)
return(n1)
def main():
userinput()
Adder(n1,n2)
main();
Expecting two numbers in the main and then pass them to "Adder"
Related
Still new to python and this problem is driving me crazy I know I'm missing something really obvious but I just can't figure it out :/ Here is the problem:
Write a function called main that prompts/asks the user to enter two integer values.
Write a value returning function named max that accepts two integer values as arguments and returns the value that is the greater of the two. For example, if 30 and 25 are passed as arguments to the function, the function should return 30.
Call the max function in the main function
The main function should display the value that is the greater of the two.
This is my code, unsure of where I went wrong
def main():
num1 = int(input('Enter the first number'))
num2 = int(input('Enter the second number'))
return num1, num2
max(n1, n2)
print(max)
def max(n1, n2):
return max
main()
When you call a the max function you need to read the returned value. What you're printing at the end of main is the max function itself. The issue would be clearer if you renamed the max function "getMax".
A second issue is that no code is executed after return in a function. So the main function stops on the fourth line when it returns num1 and num2.
You've got a lot of it there. Here's how to pull it all together:
def get_max(n1, n2):
return n1 if n1 > n2 else n2
def main():
num1 = int(input('Enter the first number> '))
num2 = int(input('Enter the second number> '))
print(f"The maximum of {num1} and {num2} is {get_max(num1, num2)}")
main()
Result:
Enter the first number> 345
Enter the second number> 333
The maximum of 345 and 333 is 345
I know the instructions say to create a function named max, but that's the name of a very commonly used function in the standard Python library. It's best that you avoid redefining built in functions by reusing their names.
Here's what you want:
def main():
num1 = int(input('Enter the first number: '))
num2 = int(input('Enter the second number: '))
result = max(num1, num2)
print(result)
def max(n1, n2):
if n1 > n2:
return n1
else:
return n2
main()
If you want to use the built-in max() function under the function you created, rename your function to something different to avoid a recursion error.
For an assignment for class, I am needing to create a program that returns if a number is even or odd, while having the main function get user input and displays the output, while another function checks whether the number is even or odd. My python knowledge so far is very basic.
Here is what I've got so far.
def check(number):
if (number % 2) == 0:
return True
else:
return False
def main():
number = int(input("Enter an integer: "))
if check is True:
print("This is an even number.")
elif check is False:
print("This is an odd number.")
__name__ == "__main__"
main()
When I run the code, I get the input prompt, but nothing in return after.
check is a function, so it should be like
if check(number):
print("This is an even number.")
else:
print("This is an odd number.")
Python is very flexible, you don't even need a function.
I would take advantage of f-strings and a ternary:
number = int(input("Enter an integer: "))
print(f'This is an {"odd" if (number % 2) else "even"} number')
Example:
Enter an integer: 2
This is an even number
Enter an integer: 3
This is an odd number
As you are basic this is not the best function for check using bool.
def check(num):
return num % 2 == 0 # return True if even otherwise odd
This code is simple and easily to read rapidly.
I have worked on many projects (school projects, I'm not too advanced), and have found that in many programs where I require the user to input a value that is an integer, or decimal(float), I need to use a "try-except" statement, within a while loop, in order to make certain that the user inputs the required value type.
For example:
def main():
userValue = input("Please enter an integer: ")
while(True):
try:
userValue = int(userValue)
break
except:
userValue = input("That is not an integer, try again: ")
print("The integer you entered is: " + str(userValue))
main()
# Input: SADASD (A non-integer value)
# Output: "That is not an integer, try again: "
# Second-Input: 3
# Second-Output: "The integer you entered is: 3"
Understandably, typing out this entire section of code repeatedly, in a program that requires user input multiple times, is not really efficient. So understanding, that user-defined functions help when I need to perform one action, multiple times. With this in mind, I defined my own function with that same try-except statement in a while loop. However, now, when I use the function, instead of printing the same output previously, rather, it prints out the first value the user had input.
For example:
def valueCheck_Integer(userInput):
while(True):
try:
userInput= int(userInput)
break
except:
userInput = input("That is not an integer, try again: ")
def main():
userValue = input("Please enter an integer: ")
valueCheck_Integer(userValue)
print("The integer you entered is: " + str(userValue))
main()
# Input: SADASD (A non-integer value)
# Output: "That is not an integer, try again: "
# Second-Input: SASASD
# Second-Output: "That is not an integer, try again: "
# Third-Input: 3
# Third-Output: SADASD (The first value that the user Input, instead of 3)
Can someone please explain to me why this happens, and some suggestions on how to fix it?
Thank you!
It's probably going to be easier to expect the function to get/check/return the integer rather than check input you already have. You can pass it the string to use for asking for the value (you could also pass the error string). It will keep asking until it's successful and then return the number you want:
def get_integer(question):
while(True):
try:
return int(input(question))
except ValueError:
question = "That is not an integer, try again:"
def main():
userValue = get_integer("Please enter an integer: ")
print("The integer you entered is: " + str(userValue))
main()
It is because of you are printing userValue instead of userInput.
I used return make it easier. So the code will be like this
def valueCheck_Integer(userInput):
while(True):
try:
userInput= int(userInput)
break
except:
userInput = input("That is not an integer, try again: ")
return userInput
def main():
userValue = input("Please enter an integer: ")
print("The integer you entered is: " + str(valueCheck_Integer(userValue)))
main()
You can make your code smaller like this:
def valueCheck_Integer(userInput):
while not(userInput.isdigit()):
userInput = input("That is not an integer, try again: ")
return userInput
def main():
userValue = input("Please enter an integer: ")
print("The integer you entered is: " + str(valueCheck_Integer(userValue)))
main()
First off, Good Question.
To understand what is going on, we first have to talk about scope of a variable.
When you define a variable outside a function, it becomes something called a global variable. This basically means that you can access it from anywhere in your code. When you define the variable within a function, it becomes a local variable. This means that it is only accessible from within your function. Finally, when a function gets passed in a variable, it gets its own local copy of the variable to work with.
Now let's look at your code.
when you call valueCheck_Integer(userInput): the function gets its own copy of userInput to work with. thus all the changes that the function does modifies the local userInput while the global userInput stays the same. As such, when the user enters a correct answer, the global userInput is the one that gets printed and the changes the function makes to local userInput is lost.
So, how can we fix this?
There are two main methods:
1)Using the global keyword
def valueCheck_Integer(userInput):
global userInput
while(True):
try:
userInput= int(userInput)
break
except:
userInput = input("That is not an integer, try again: ")
This keyword asks the function to modify the global userInput
2)Returning a value
def valueCheck_Integer(userInput):
while(True):
try:
userInput= int(userInput)
break
except:
userInput = input("That is not an integer, try again: ")
return userInput
def main():
userValue = input("Please enter an integer: ")
print("The integer you entered is: " + str(valueCheck_Integer(userValue)))
main()
This works by returning the local copy of userInput and modifying global userInput to equal local userInput
The second code I used was from
Osadhi Virochana Jayasinghe Si's answer.
It's because, if you see your line of code where you print the final output -:
print("The integer you entered is: " + str(userValue))
you will realise that the value you are printing is the one you take the first time from the input function. But this is not the value you have been working on to achieve in your other function.
So for you to rather get that value, the function in some way has to return it back to you.
For this you should allow the function to return the value in the last line.
like so -:
return userInput
and then change the line where you call function so it saves the value returned.
like so -:
userValue = valueCheck_Integer(userValue)
Also as mentioned by others using the global keyword you can define the variable in global scope.
But this is really not a good practice until really needed as it can increase the amount of space that the var is taking, before the variable only took the space for a limited time for when the function is called, but now the variable takes space throughout the time the program runs.
While return will not do so as it will only return the value and once assigned to the already defined variable it will remove the returned value from space.
This should hopefully fix your problem.
I hope this helps.
And also hope that you're safe during the time of this ongoing pandemic.
The first function simply takes a value (let's say 3)
The second function asks the user if they want to repeat the operation
If the user agrees to perform the operation again, and this time they enter 2
How can I make the final value of the variable be the addition of the two user inputs?
def value():
amt = int(input("enter value: "))
def go_again():
again = input("DO you want to go again(y/n)")
if again == "y":
value()
else:
exit()
value()
again()
(This is a shorter code but similar to what I am working on.)
Just embed value function in go_again and run it in while loop:
def value():
return int(input("enter value: "))
def go_again():
val = value()
while input("DO you want to go again(y/n)") == "y":
val += value()
exit()
go_again()
I'm super new to Python and programming in general. I am following an example off of youtube on how to make a simple calculator but I wanted to add my ideas and functionalities. More or less I want to make it very versatile.
This is the part that is not working out for me. I don't know how to make it work using the two methods I created
def main():
while True:
Num1()
num1 = int.num1()
Num2()
num2 = int.num2()
# Executing the specified calculations with the 'Operation' function (row 13)
Operation(num1, num2)
# --> followed by another nested while asking if the user wants to make another calculation
I want the app to read everywhere that if the user types "exit" it will exit, even if it's asking for a number so I created 2 methods to do so because it wasn't working dealing with the loops and user input directly from main()
def Num1():
while True:
num1 = input("What is the first number? ")
if num1.isdigit():
break
elif num1 == 'exit':
print("Thank you using the SimpleCalculator. Bye!")
time.sleep(3)
exit()
else:
print("I don't understand. Please input a valid number")
continue
def Num2():
while True:
num2 = input("What is the second number? ")
if num2.isdigit():
break
elif num2 == "exit":
print("Thank you using the SimpleCalculator. Bye!")
time.sleep(3)
exit()
else:
print("I don't understand. Please input a valid number")
continue
The problem is that I get this error and I get it but I just don't know how to go about it.
Traceback (most recent call last):
File "C:/Users/Albert/PycharmProjects/HelloWorld - First Py'
Apps/SimpleCalculator.py", line 131, in <module>
main()
File "C:/Users/Albert/PycharmProjects/HelloWorld - First Py'
Apps/SimpleCalculator.py", line 109, in main
Operation(num1, num2)
NameError: name 'num1' is not defined
I see few general errors in your code:
You call function Num1() for entering num1, but num1 is the local
variable. So you can see and use it only in Num1() function. Same
with num2. So, I suggest to use Num1 and Num2 but to return the num1
and num2.
I recommend to use 1 function, there is no need to use 2.
Looks like with num1 = int.num1() you want to convert num1() to int. This is wrong. Correct will be something like num1 = int(num1).
This will convert num1 from string to int and save it to num1. But
better to use different names for strings and int's: num1 =
int(num1_str). And when you use bracket num1(), this means you call
num1 function to complete. But num1 is not a function, so it's not
callable.
You use converting strings to int two times. In programming, when you see two code, which is just copy/paste, you better to make a
function for it. Here we have the function, so just insert
converting to int in function.
Don't forget about indentation. This is the most important thing in Python. In other languages, you use something like {} to define
the beginning and the end of some logical block. But in Python, it
all depends on indentation.
So, using this, it can look like this way:
def main():
while True:
# just call NumEntering - one general function for entering numbers,
# and give to it attribute - message for user.
num1 = int(NumEntering("What is the first number? "))
num2 = int(NumEntering("What is the second number? "))
# Executing the specified calculations with the 'Operation' function (row 13)
Operation(num1, num2)
And the function:
def NumEntering(message): # message - this what function get from outer function.
while True:
num_str = input(message) # show given message
if num_str.isdigit():
return int(num_str) # convert to int and return to outer function
elif num_str == 'exit':
print("Thank you using the SimpleCalculator. Bye!")
time.sleep(3)
exit()
else:
print("I don't understand. Please input a valid number")
continue
case sensitivity, you defined Num1() & Num2() not num1() & num2()
There's plenty wrong with your code.
DRY Do not Repeat Yourself. There's no need to have two functions when they do the same thing. Delete Num2 in its entirety. It's useless.
Num1 isn't returning a value. We want the function to ask the user for a number (which it does), exit if the user inputs "exit" (also done) and return the number entered by the user (not done).
Function names start with a lowercase letter and are descriptive. Num1 does neither, so let's change it to ask_number.
All the problems identified above can be fixed by replacing Num1 and Num2 with the following ask_number function.
def ask_number():
while True:
num = input("What is the first number? ")
if num.isdigit():
return int(num) #This line fixes problem 2
elif num == 'exit':
print("Thank you using the SimpleCalculator. Bye!")
time.sleep(3)
exit()
else:
print("I don't understand. Please input a valid number")
Your main method isn't assigning the return value of your function into the variables.
Fix it by replacing your old code
Num1()
num1 = int.num1()
Num2()
num2 = int.num2()
with
num1 = ask_number()
num2 = ask_number()
We're calling the ask_number function twice and assigning its return value to num1 and num2.
The problem was that Num1() and Num2() asked the questions, but didn't do anything with them. Also, the num1 and num2 that were defined were variables local to the function, so you couldn't access them from the main() function. You should have added "return numX" instead of break and assigned Num1() to num1, which allows you to capture the user's input in a variable accessible by the main() function.
This is what your code should have looked like:
import time
def Num1():
while True:
num1=input("What is the first number? ")
if num1.isdigit():
return int(num1)
elif num1 == 'exit':
print("Thank you using the SimpleCalculator. Bye!")
time.sleep(3)
exit()
else:
print("I don't understand. Please input a valid number")
def Num2():
while True:
num2=input("What is the first number? ")
if num2.isdigit():
return int(num2)
elif num2 == 'exit':
print("Thank you using the SimpleCalculator. Bye!")
time.sleep(3)
exit()
else:
print("I don't understand. Please input a valid number")
def Operation(num_1, num_2):
# code for Operation function
pass
def main():
while True:
num1=Num1()
num2=Num2()
Operation(num1, num2)
if __name__=="__main__": main()
Disclaimer: I'd ask for some clarification, but I don't have the SO privileges yet.
Can you make sure your indentation is correct when you're running the program? For instance, your while loops shouldn't be on the same indentation level as your function definitions.
Also, are you functions all in this file SimpleCalculator.py? If so, you will need to have an additional line to call your methods, since right now they're only being declared.
if __name__ == '__main__':
# And the following line will call your main function which you defined previously
main()
Better yet, just remove your main() function and replace it with the more Pythonic syntax:
if __name__ == '__main__':
while True:
Num1()
Num2()
Also, since you're calling Num1() and Num2() and they're handling the inputs, you don't need to set num1 = int.num1() or num = int.num2() (which both give me errors) or the like. If you want to have the values to be returned to the main method for handling, you'll need to do return num1 when you check if num1.isdigit():, and in your main method set firstNumberInput = Num1()
Hope this helps!
It may just be that you have posted your code with omissions but there are several points to address.
The functions Num1 and Num2 do not return anything. Although the value num1 is assigned within the function, it is not accessible outside that function's scope.
int does not have a method "num1" so calling int.num1() should be replaced with int(num1())
Creating 2 nearly identical functions creates a lot more work for yourself and makes the code hard to change, you could create a more general function.
def getnum():
while True:
mynum = input("What is the first number? ")
if mynum.isdigit():
break
elif mynum == 'exit':
print("Thank you using the SimpleCalculator. Bye!")
time.sleep(3)
exit()
else:
print("I don't understand. Please input a valid number")
return mynum
def main():
while True:
num1 = int(getnum())
num2 = int(getnum())