How do you use input function along with def function? - python

I'm new to programming. I have a bit of problem with python coding (with def function).
So basically the code has to give the smaller number out of 2 numbers.
Question:
Write codes to perform the following tasks:
Define a function smaller_num that takes in two numbers to
determine and return the smaller number of the two.
Ask user for two numbers
Use the function to determine the smaller number and display the result
So I had user input instead of calling the function and adding value inside the variable.
This is how my code looks like:
def smaller_num(x,y):
if x>y:
number= y
else:
number= x
return number
smaller_num(x= input("Enter first number:-") ,y= input("Enter second number:-"))
print("The smaller number between " + str(x) + " and " + str(y) + " is " + str(smaller_num))
How do I correct it? For now it's not working because "x" is not defined. But I feel that I defined them clearly both in def function and input function. So how do I fix this?
Thanks for those who respond to this question.

You never actually defined x and y globally. You only defined it in the function when you did def smaller_num(x, y).
When you do smaller_num(x= input("Enter first number:-") ,y= input("Enter second number:-"))
, you aren't creating variables called x and y, you are just creating parameters for your function.
In order to fix your code, create the variable x and y before you call your function:
def smaller_num(x, y): ## Can be rephrased to def smaller_num(x, y):
if x > y: ## if x > y:
number = y ## return y
else: ## else:
number = x ## return x
return number
x = input("Enter first number:-")
y = input("Enter second number:-")
result = smaller_num(x, y)
print("The smaller number between " + str(x) + " and " + str(y) + " is " + str(result))
The other reason your code is not working is because you're not assigning the returned value of the function back into a variable. When you return something from a function, and again when you call the function, you need to assign the value to a variable, like I have: result = smaller_num(x, y).
When you called your function, you never assigned the value to a variable, so it has been wasted.
Also, are you using Python 3 or 2.7? In python 3 using input() will return a string, and to convert this to an integer, you can call int() around the input() function.

This will work:
def smaller_num(x,y):
if x>y:
number= y
else:
number= x
return number
x = input("Enter first number:-")
y = input("Enter second number:-")
smaller = smaller_num(x,y)
print("The smaller number between " + str(x) + " and " + str(y) + " is " + str(smaller))

this should work:
def smaller_num(x,y):
if x>y:
number = y
else:
number = x
return number
x = input("Enter first number:-")
y = input("Enter second number:-")
print("The smaller number between " + str(x) + " and " + str(y) + " is " + str(smaller_num(x,y)))

def smaller_num(x,y):
if x>=y:
number = y
else:
number = x
return number
x = input("Enter first number:-")
y = input("Enter second number:-")
print("The smaller number between " + str(x) + " and " + str(y) + " is " + str(smaller_num(x,y)))

def smaller_num(x,y):
if x>y:
number= y
else:
number= x
return number
k=smaller_num(x= input("Enter first number:-") ,y= input("Enter second number:-"))
print("The smaller number between x & y is ", k)

def smaller_num():
x=int(input('Enter the first number: '))
y=int(input('Enter the second number: '))
if x<y:
return x
else:
return y
print('The smaller number is: ',smaller_num())

Related

adding to a string based on the number of characters

the problem says to print "that's a really really ... big number" with one "really" for every extra digit that the number has (so 15 would be "that's a really big number", 150 would be "that's a really really big number", 1500 would be "that's a really really really big number", and so on.)
the input is an integer, and the only requirements listed are that the code should run correctly with any integer, should use a while loop to keep dividing the number by 10 and should use += to add onto the end of a string
x = input(("input an integer: "))
count = len(x)
y = int(x / 10)
countx = count - 1
print("that's a " + count("really") + " big number")
i don't really know what i did, but i can tell it's not correct
Try this one. Uses while loop to divide number by 10 and += to add onto the string. You will need to take a string variable and then append to it as count increases. Loop will run until number >= 10 as conditions you mentioned.
x = int(input(("input an integer: ")))
str=""
while x>=10:
x=x//10
str+="really "
print("that's a " + str + "big number")
Added the while loop as you stated in your question
strVar = ""
y = 0
length = 0
cnt = 0
finished = False
num = input("Type a number: ")
while not finished:
y = int(num)//10
length = int(len(str(y)))
if length <= cnt:
finished = True
else:
strVar += " really"
cnt += 1
print("That's a" + strVar + " big number!")
Give this a try. It finds how many trailing zeroes there are in a given number and based on that creates a certain amount of really's.
x = input(("input an integer: "))
count = int(len(x) - len(x.rstrip('0')))
if count == 0:count = 1
really = "really "*count
print(f"that's a {really} big number")
Try this
x = int(input("enter an integer"))
print("that's a " + 'really '*(len(str(x))-1) + " big number")
If you want to correct your function use this
x = input(("input an integer: "))
count = len(x)
y = int(x) / 10
countx = count - 1
print("that's a " + countx*" really" + " big number")

Python: I write a code to find value of, x, y or (x+y)2, if given any two parameters among them. That is running fine, until either x or y is float

I edited code here to assign variables to float. It is not working.
This code is to find value of either factor in (x+y)^2 = x^2 + 2xy + y^2
There are three factors, x, y and result. Value must be available for any two.
The only problem here is, you can't find value of x or y if they are float. For that I'm looking forward in google & to use some math's library if I can understand.
x = (input("\nEnter value of x: "))
y = (input("\nEnter value of y: "))
z = (input("\nEnter value of (x+y)^2: "))
#-----------------------------------------------------------------------
#Converting input to integers.
#-----------------------------------------------------------------------
a=0.0
b=0.0
c=0.0
if len(x)!=0:
a = float(x)
else:
print ("\nWe will search value of 'x'")
if len(y)!=0:
b = float(y)
else:
print ("\nWe will search value of 'y'")
if len(z)!=0:
c = float(z)
else:
print ("\nWe will search value of '(x+y)^2'")
#-----------------------------------------------------------------------
#Calculations
#-----------------------------------------------------------------------
from math import sqrt
fv=0.0 #fv = find value
rs=0.0 #rs = result
if len(x)==0:
while True:
rs = ((fv*fv) + (2*fv*b) + (b*b))
fv = fv + 1
if rs==c:
print (f"\nValue of 'x' is either {(fv-1)} or {((sqrt(c)*-1) - b)}")
break
if len(y)==0:
while True:
rs = ((a*a) + (2*a*fv) + (fv*fv))
fv = fv+1
if rs==c:
print (f"\nValue of 'y' is either {(fv-1)} or {((sqrt(c)*-1) - a)}")
break
if len(z)==0:
rs = ((a*a) + (2*a*b) + (b*b))
print (f"\nValue of '(x+y)^2' is {rs}")
print ("\nThank you")
try this
print ("\n\nEnter values in below equations. \nIf you don't know the value, than press \"Enter\" ")
x = (input("\nEnter value of x: "))
y = (input("\nEnter value of y: "))
z = (input("\nEnter value of (x+y)^2: "))
#-----------------------------------------------------------------------
#Converting input to integers.
#-----------------------------------------------------------------------
a=0
b=0
c=0
if len(x)!=0:
a = float(x)
else:
print ("\nWe will search value of 'x'")
if len(y)!=0:
b = float(y)
else:
print ("\nWe will search value of 'y'")
if len(z)!=0:
c = int(z)
else:
print ("\nWe will search value of '(x+y)^2'")
#-----------------------------------------------------------------------
#Calculations
#-----------------------------------------------------------------------
from math import sqrt
fv=0 #fv = find value
rs=0 #rs = result
if len(x)==0:
while True:
rs = ((fv*fv) + (2*fv*b) + (b*b))
fv = fv + 1
if rs==c:
print (f"\nValue of 'x' is either {(fv-1)} or {int((sqrt(c)*-1) - b)}")
break
if len(y)==0:
while True:
rs = ((a*a) + (2*a*fv) + (fv*fv))
fv = fv+1
if rs==c:
print (f"\nValue of 'y' is either {(fv-1)} or {int((sqrt(c)*-1) - a)}")
break
if len(z)==0:
rs = ((a*a) + (2*a*b) + (b*b))
print (f"\nValue of '(x+y)^2' is {rs}")
print ("\nThank you")
just change int to float

Program isn't running

I'm trying to run a code but it's not working and I can't seem to find the errors if there are any
def question3():
x= input("Enter the first value:")
y= input("Enter the second value:")
z= input("Enter the third value:")
if x==y==z:
print("All three inputs have equal values" + x)
elif x==y:
print("x and y have equal values" + x)
elif x==z:
print("x and z have equal values" + x)
elif y==z:
print("y and z have equal values" + y)
else:
print("All three inputs have different values")
def question3():
x= input("Enter the first value:")
y= input("Enter the second value:")
z= input("Enter the third value:")
if x==y==z:
print("All three inputs have equal values" + x)
elif x==y:
print("x and y have equal values" + x)
elif x==z:
print("x and z have equal values" + x)
elif y==z:
print("y and z have equal values" + y)
else:
print("All three inputs have different values")
return

Python 3.4.2 | Loop input until set amount

Learning the basics of python and I am running across a problem. I'm sure it is a simple fix. I'm trying to get my program to get 20 different inputs before calculating the min, max, etc.
def main():
number = valueInput()
display(number)
def valueInput():
print("Please enter 20 random numbers")
values = []
for i in range(20):
value1 =(int(input("Enter a random number " + str(i + 1) + ": ")))
values.append(value1)
return values
def display(number):
print("The lowest number is:", min(number))
print("The highest number is:", max(number))
print("The sum of the numbers is:", sum(number))
print("The average number is:", sum(number)/len(number))
main()
I can get it to work by repeating this line:
value1 =(int(input("Enter a random number " + str(i + 1) + ": ")))
to the 20th number but there must be a way that makes it shorter and cleaner. Again I am a beginner so any explanation would be much appreciated.
All you have to do to fix your program is remove four spaces:
def valueInput():
print("Please enter 20 random numbers")
values = []
for i in range(20):
value1 =(int(input("Enter a random number " + str(i + 1) + ": ")))
values.append(value1)
return values
The last line in the block above has been unindented by one level. Instead of returning after the first time through the loop, it lets the loop complete, and then returns the resulting list.
Also you can change your:
values = []
for i in range(20):
value1 =(int(input("Enter a random number " + str(i + 1) + ": ")))
values.append(value1)
return values
part with:
values = [int(input("Enter a random number " + str(x + 1) + ": ")) for x in list(range(20))]
return values
You can check out build in functions

Syntax error on second def

When running this code I have trouble with the second def, *de*f multiply (): with the de of def being singed out when i receive the syntax error.
import random
def start () :
print "Welcome!"
choose ()
def choose () :
choice = input """would you like to
add, subtract, or multiply?
1 2 3
"""
if choice = 1 :
add ()
if choice = 2 :
subtract ()
if choice = 3 :
multiply ()
def multiply () :
x = random.random ()
x = round ()
y = random.random ()
y = round ()
print "What is the answer to: ", x,"*", y, " ?"
answer = input ": "
z = x*y
if answer == z :
print "you are correct!"
elif answer < z :
print "your answer is low! The correct answer was ", z
elif answer > z :
print "your answer is high! The correct answer was ", z
multiply ()
def add () :
x = random.random ()
x = round ()
y = random.random ()
y = round ()
print "What is the answer to: ", x,"+", y, " ?"
answer = input ": "
z = x+y
if answer == z :
print "you are correct!"
elif answer < z :
print "your answer is low! The correct answer was ", z
elif answer > z :
print "your answer is high! The correct answer was ", z
def subtract () :
x = random.random ()
x = round ()
y = random.random ()
y = round ()
print "What is the answer to: ", x,"*", y, " ?"
answer = input ": "
z = x*y
if answer == z :
print "you are correct!"
elif answer < z :
print "your answer is low! The correct answer was ", z
elif answer > z :
print "your answer is high! The correct answer was ", z
input is a function, so you have to call it like one:
input('Input some stuff: ')
You also have a few lines that look like this:
if choice = 1 :
You want to write choice == 1. Finally, this part right here is a little strange:
x = random.random ()
x = round ()
You probably want to pass x into round:
x = random.random ()
x = round (x)
Or just skip that part entirely and use randint
x = random.randint(0, 1)
Here are some logic and syntax errors in your code:
answer = input ": "
You call input like this:
answer = input(": ")
if choice = 1 :
= is assignment. You mean ==.
x = random.random ()
x = round ()
If you assign x to be the first thing, then the second thing, it's like the first assignment never happened. Did you mean x = round(x)?

Categories