Syntax error on second def - python

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)?

Related

How to limit incorrect answers from users input?

I'm here with my code, here you can see it:
def generate_integer(level):
score = 0
i = 0
false = 0
level = int(level)
while i != 10:
# Choosing the numbers of digit if 1 >> 1-9 / if 2 >> 11-99 / if 3 >> 100-999
end = 10**level-1
# Define x and y
x = random.randint(0,end)
y = random.randint(0,end)
answer = x + y
# Users cal
user = int(input(f'{x} + {y} = '))
if user == answer:
score = score + 1
while user != answer:
false + 1
print('EEE')
user = int(input(f'{x} + {y} = '))
if false == 3:
print(f'{x} + {y} = {answer}')
i = i + 1
print(f'score: {score}/10')
Let me explain: I defined false for, if user inputs the answer 3 times and all of them for that question are false, show user the answer and continue asking
Actually this code asks 10 different math questions, this is a part of my code, I'm checking if answer is not true print('EEE') and re ask it again, but if user tries 3 time and all incorrect, then I show the answer, pass that question and keep asking other questions.
If you have any ideas for re asking question, when users input was non-numerical, I'll be thankful.
You just have an indentation wrong
def generate_integer(level):
score = 0
i = 0
false = 0
level = int(level)
while i != 10:
# Choosing the numbers of digit if 1 >> 1-9 / if 2 >> 11-99 / if 3 >> 100-999
end = 10**level-1
# Define x and y
x = random.randint(0,end)
y = random.randint(0,end)
answer = x + y
# Users cal
user = int(input(f'{x} + {y} = '))
if user == answer:
score = score + 1
while user != answer:
false + 1
print('EEE')
user = int(input(f'{x} + {y} = '))
if false == 3:
print(f'{x} + {y} = {answer}')
break
i = i + 1
print(f'score: {score}/10')
Would probably work, because you want to be checking for how many times they messed up within the while loop.
OTHER PIECES OF ADVICE
I would also rename false to num_incorrect_tries, and replace 10**level-1 with 10**(level-1)
You can also just for for i in range(11), instead of doing a while loop, and incrementing i
What you can do is ask for the input in a separate function inside of a while True loop that only exits when it detects the input to be an integer. In my example below the getint function does just that.
I made a few other minor adjustments to your function to simplify it a little as well. I have tested and can confirm it does work the way you describe.
I left some inline notes to explain where I made changes
import random
def getint(x,y):
while 1:
user = input(f'{x} + {y} = ') # get user input
if user.isdigit(): # check if it is an integer
return int(user) # return integer value
print("Non-Integer Input Detected: Try Again") # print Error
def generate_integer(level):
score = false = i = 0 # all three are zero
level = int(level)
while i != 10:
end = 10**level-1
x = random.randint(0,end)
y = random.randint(0,end)
answer = x + y
while getint(x, y) != answer: # while the user input != answer
false += 1 # increment false number
if false == 3: # if 3 wrong answers
print(f'{x} + {y} = {answer}') # print the answer
false = 0 # reset false
break # end while loop
print('EEE') # show error
else:
score = score + 1 # increase score for correct answer
i = i + 1
print(f'score: {score}/10')
def check(user_answer,correct_answer):
for a chance in range(2):
print("Wrong answer, try again")
user_answer=input('User please type your answer for the question')
if user_answer == correct_answer:
return 'True' # Given the Right answer
else:
print('Again wrong answer')
return 'False' #Given all wrongs answers
user_answer=input('User please type your answer for the question')
correct_answer=10
if user_answer != correct_answer:
result=check(user_answer,correct_answer)
if result:
print("your answer is correct")
else:
print("your all answers were wrong, the right answer is: ",correct_answer)
else:
print("Perfect your answer was right in the first guess")

Most efficient way to compare lists Python

How can I compare lists to one another. I am looking to compare the first - fourth digit of two lists.
I'm aware of being able to do
if list[1] == list[1]: but id assume there is a more efficient way to get it done. Thank you. I don't want to compare the lists overall, just x part of one list to x part of another
import random
import replit
import numpy
import time
number = 0
answer = 0
guesses = 0
x = 0
useranswer = []
generated = []
for i in range (0,4):
num = random.randrange(1,9)
generated.append(num)
replit.clear()
print("---------------------------------------------------------------------\nWelcome to MASTERMIND! you must guess the number that was generated!\n---------------------------------------------------------------------\n")
def useranswer():
answer = str(input("Select a 4 digit number: "))
if len(answer) != 4:
print("Invalid answer type")
time.sleep(999999999)
answer = ' '
else:
useranswer = list((str(answer)))
if useranswer == generated:
print("Good job! You became the MASTERMIND in one turn!")
else:
while useranswer != generated:
useranswer()
guesses +=1
if useranswer == generated:
print("You have become the mastermind in " + guesses + " tries!")
else:
c = numpy.intersect1d(useranswer, generated, return_indices=True)[1]
print("You got " + c + " correct! ")```
You can always use list slicing to compare the specified range of items between lists.
a = [1, 2, 3, 4, 7, 8]
b = [1, 2, 3, 4, 5, 6]
a[:3] == b[:3]
The above will yield a True if they match.
If you want to return the indexes of common elements between the two lists, there's a library called Numpy which has powerful features to do such jobs efficiently.
import numpy
a = [1, 2, 3, 4]
b = [0, 4, 6, 2]
_, c, d = numpy.intersect1d(a, b, return_indices=True)
This would return the following indexes:
print(c)
print(d)
array([0, 1, 3]
array([0, 3, 1])
But the answer to your question:
import random
import replit
import copy
import numpy
import time
number = 0
answer = 0
guesses = 0
x = 0
useranswer = []
generated = []
for i in range (0,4):
num = random.randrange(1,9)
generated.append(num)
replit.clear()
print("---------------------------------------------------------------------\nWelcome to MASTERMIND! you must guess the number that was generated!\n---------------------------------------------------------------------\n")
def useranswer_func():
answer = str(input("Select a 4 digit number: "))
if len(answer) != 4:
print("Invalid answer type")
time.sleep(9) # The time provided by you is too much to wait!
answer = ' '
else:
useranswer = list(answer)
# You need to return values to use them outside the function.
# Also your generated has int values but useranswer have str. So convert them to int or else they would never compare!
return [int(i) for i in useranswer]
if useranswer == generated:
print("Good job! You became the MASTERMIND in one turn!")
else:
while useranswer != generated:
# The returned values need to be stored in a variable.
# Never use function name and variable name same. That could cause the error that you posted in the comment!
useranswer = useranswer_func()
guesses += 1
if useranswer == generated:
print("You have become the mastermind in " + str(guesses) + " tries!")
else:
c = []
temp = copy.deepcopy(generated) # So that the change you make in temp is not reflected in generated variable too.
for i in range(len(generated)):
if generated[i] == useranswer[i]:
c.append(temp.index(temp[i]))
temp[i] = None # If your generated has repeated values, the index returned will be different or else it would be always same.
print("You got " + str(c) + " correct! ")

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

Making a simple calculator in Python and not sure how to do nothing for else

I'm trying to make a program that simply adds or subtracts 2 numbers. I have the code below:
x = int(input("Enter a number: "))
y = int(input("Enter a number: "))
print("Would you like to add or subtract?")
txt = input("Type 'a' for add or 's' for subtract")
if txt == "a" or "A":
x + y == z
if txt == "s" or "S":
x - y == z
else:
return
else:
return
print (z)
I know the return isn't right but not sure how I should work this out.
first of all when you write:
x + y == z
you are not defining a new z variable, but just making the logical operation "is x + y equal to z?" where z is not even defined. If you want to define z as the sum or difference of x and y you should use:
z = x + y or z = x - y
Also, when you want to make a structure of the kind "if condition is equal to something, else if condition is equal to something else" you can use if, else and elif (which is both else and if togheter), but you have to be sure that they have the same indentation.
The following code should do the job: (Edited)
x = int(input("Enter a number: "))
y = int(input("Enter a number: "))
print("Would you like to add or subtract?")
txt = input("Type 'a' for add or 's' for subtract")
if txt == "a" or txt=="A":
z = x + y
elif txt == "s" or txt=="S":
z = x - y
print (z)
Edit: you did not define a function, therefore you don't need to use "return". Return is used to give the result of a function, for example:
def sum(x, y):
z = x + y
return(z)
Edit #2: Thank you for making me note that txt == 'a' or 'A' would always be true, i've now repaired the code.
First: x + y == z is a test for equality. It checks if x + y and z are equal. To assign the result of x + y to z, you need to do z = x + y.
For such problems, it really helps to draw a flowchart or at least write out the steps you are going to implement in your code, especially when you're beginning programming. Here's an example. Pay attention to the indentation of my numbered list. This is similar to the indentation that you will expect to see in your Python code.
Take two numbers
input() returns a string, so convert to integers
Ask for the operator
input() to take a string.
If the operator is "a" or "A" (See note 1)
do addition
Instead, if the operator is "s" or "S"
do subtraction
If the operator is none of the above
do nothing? Show an error?
In the end, print the output
The code for the algorithm we discussed above would be:
x = int(input("Enter a number: ")) # 1.
y = int(input("Enter a number: ")) # 1.
print("Would you like to add or subtract?") # 2.
txt = input("Type 'a' for add or 's' for subtract")
if txt == "a" or txt == "A": # 3.
z = x + y
elif txt == "s" or txt == "S": # 4.
z = x - y
else: # 5.
z = 0
print("Invalid choice!")
print (z) # 6.
Your code goes wrong here:
If the operator is "a" or "A"
do addition
Now, if the operator is "s" or "S" (Can it be "s" or "S"? No, because we already established that it's "a" or "A" in 3. above )
do subtraction
Note 1: In human languages, we say
Check if txt is "a" or "A"
But Python works with booleans for the if condition. If we did if txt == "a" or "A", this would evaluate to if [[(txt == "a") is true] or ["A" is true]]. Because non-empty strings are truthy in Python, ["A" is true] would always be correct and so [[(txt == "a") is true] or ["A" is true]] would always be true, so we'd always go into the if statement. Not what we wanted to happen!
We have to compare each one separately like so:
if txt == "a" or txt == "A":
Alternatively, we can convert txt to lower or upper case and have a single check
if txt.lower() == "a":
Or,
if txt.upper() == "A":
Alternatively, we could check whether txt is one of the elements in a list.
if txt in ["a", "A"]:
You need to do z = x + y and z = x - y instead of x + y == z and x - y == z. Double equals to is a comparison operator.
The below code should work:
x = int(input("Enter a number: "))
y = int(input("Enter a number: "))
z = 0
print("Would you like to add or subtract?")
txt = input("Type 'a' for add or 's' for subtract")
if txt == "a" or "A":
z = x + y
elif txt == "s" or "S":
z = x - y
//you can use return if it's a function
return z;
print (z)

How do you use input function along with def function?

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())

Categories