NameError: name 'number' is not defined [duplicate] - python

This question already has answers here:
Why does the expression 0 < 0 == 0 return False in Python?
(9 answers)
Why does this not work as an array membership test? [duplicate]
(1 answer)
Closed 4 years ago.
I have a code like below
a=25
b=20
#number=0
if a < b == True:
number = 1
elif a >b == True:
number = 2
print(number)
When i execute this i get the following error
NameError: name 'number' is not defined
When i initialize the number = 0 like below
a=25
b=20
number=0
if a < b == True:
number = 1
elif a >b == True:
number = 2
print(number)
then i am not getting the output as 2, i am getting 0 instead, what am i missing here

Put a parenthesis around the condition.
Ex:
a=25
b=20
#number=0
if (a < b) == True:
number = 1
elif (a > b) == True:
number = 2
print(number)
or:
if a < b:
number = 1
elif a > b:
number = 2
print(number)
You are currently doing (a < b) and (b == True) & (a > b) and (b == 20)

Related

Loop is not repeating

I am trying to make this "algorithm", which will take the number and get it down to 4, 2, 1. If anyone have seen the youtube video regarding this math problem, they will understand.
done = False
while True:
num = int(input("Enter a number: "))
if (num % 2) == 0:
print(num/2)
else:
print(num * 3 + 1)
if num == 1 or 2 or 4:
break
The output is this algorithm not repeating itself.
If I type in number 5 it will x3+1, and print only 16. What I want is it doing this, but keep going till the number is either 1,2 or 4. Hope yall can help :D
The error is in line if num == 1 or 2 or 4:. That always evaluates to True and thus breaks your loop.
Your intention is to have if num == 1 or num == 2 or num == 4:. Or if num in (1,2,4): to be more concise.
(Explanation of your mistake: the if statement has an expression that is being tested. You're chaining a couple of expressions with the or operator, resulting in if expr1 or expr2 or expr3. The if-expression is True if any of those OR'd expressions is True.
Your expr1 is num == 1 which is True only if num equals 1.
Your expr2 is 2 which is True always (!).
Your expr3 is 4 which is True always.
So, your if-expression is always evaluating to True.)
It isn't testing for all three of those numbers (1, 2 and 4).
Here's the fixed code:
done = False
while True:
num = int(input("Enter a number: "))
if (num % 2) == 0:
print(num/2)
else:
print(num * 3 + 1)
if num == 1:
break
if num == 2:
break
if num == 4:
break
I think you want to repeat num/2 or num*3+1 every output. If you use odd number like 7, it calculates 22 and 22 is a even number and 22 is calculated 11 and it returns 34 and so on. I figure it out like this. But it always ends with 4 :)
done = False
num = int(input("Enter a number: "))
while True:
if (num % 2) == 0:
num/=2
print(num)
else:
num = num * 3 + 1
print(num)
if int(num) in [1,2,4]:
break

getting only the odd digits in a number with recursion [duplicate]

This question already has answers here:
getting only the odd digits in a number with recursion
(3 answers)
Closed 2 years ago.
So my problem is this i have an number like 123 and as the tilte sugests i want the result to be 13.
The problem is that firstly with the method im using im going to get the invert result (31 for example), secondly im getting a zero at the end that shouldn't be there and instead of joining the digits its summing them and i dont understand why.
So to clarify:
My output:
>>> apenas_digitos_impares(123)
40
Correct output:
>>> apenas_digitos_impares(123)
13
program:
def apenas_digitos_impares(n):
if n == 0:
return 0
elif (n%10)%2 == 0:
return apenas_digitos_impares(n//10)
elif (n%10)%2 == 1:
return 10*(n%10) + apenas_digitos_impares(n//10)
You could do it as -
def apenas_digitos_impares(n):
if n == 0:
return 0
elif (n%10)%2 == 0:
return apenas_digitos_impares(n//10)
elif (n%10)%2 == 1:
return (n%10) + 10*apenas_digitos_impares(n//10)
print(apenas_digitos_impares(123))
OUTPUT :
13
Solution#1: You can do the operation with a single method
import math
def convert_int_to_list(n):
result = []
while n > 0:
if (n % 10) % 2 == 1:
result.append(n % 10)
n = math.floor(n / 10)
return result
print(convert_int_to_list(1345986))
Output:
[9, 5, 3, 1]
Solution#2 You don't have to change your method, just declare an array before the method
result = []
You want odd numbers, then place the array into the correct place.
elif (n%10)%2 == 1:
res.append(n%10)
return 10*(n%10) + apenas_digitos_impares(n//10)
print res
[3, 1]
For various examples:
apenas_digitos_impares(1235)
apenas_digitos_impares(12356789)
[5, 3, 1]
[9, 7, 5, 3, 1]

Generate Random Math in Python 3

This program will ask the user a series of questions about two numbers. These two numbers will be generated randomly between 1 and 10 and it will ask the user 10 times. At the end of these 10 questions the program will display how many the user got correct out of those questions.
Each question should randomly decide between asking for the product, sum, or difference. Separate the question asking into a function, as well as the validating user input.
I tried using with three product, sum or difference in random to generate. I tried to use z = random.randint(1, 4) is to select from 1 is product, 2 is sum, or 3 is difference and then I used with if variable z is 1, then do product math or if var z is 3, then it should be difference like this x / y, but I couldn't figure it finish it up. I have the expected result when I first run with product but it works so I just need to add with sum and difference included.
EXPECTED OUTPUT with product (Some are incorrect for testing with scores):
> python3 rand3.py
What is 3 x 4
Enter a number: 12
What is 3 x 7
Enter a number: 27
What is 6 x 3
Enter a number: 18
What is 7 x 10
Enter a number: 70
What is 9 x 10
Enter a number: 90
What is 9 x 7
Enter a number: 72
What is 5 x 9
Enter a number: 54
What is 6 x 8
Enter a number:
Incorrect Input!
Enter a number: 48
What is 1 x 5
Enter a number: 5
What is 10 x 3
Enter a number: 30
You got 7 correct out of 10
My Work for Product Only (Success):
import random
def askNum():
while(1):
try:
userInput = int(input("Enter a number: "))
break
except ValueError:
print("Incorrect Input!")
return userInput
def askQuestion():
x = random.randint(1, 100)
y = random.randint(1, 100)
print("What is " + str(x) + " x " +str(y))
u = askNum()
if (u == x * y):
return 1
else:
return 0
amount = 10
correct = 0
for i in range(amount):
correct += askQuestion()
print("You got %d correct out of %d" % (correct, amount))
My Currently Work: (I am working to add sum and difference like the expected output
UPDATED: After the expected output works well with product so I am trying to add new random int for z with 1-3 which means I am using with 1 is for product, 2 is for sum and 3 is difference by using if-statement by given random select. I am struggle at this is where I stopped and figure it out how to do math random because I am new to Python over a month now.
import random
def askNum():
while(1):
try:
userInput = int(input("Enter a number: "))
break
except ValueError:
print("Incorrect Input!")
return userInput
def askQuestion():
x = random.randint(1, 10)
y = random.randint(1, 10)
z = random.randint(1, 4)
print("What is " + str(x) + " "+ str(z)+ " " +str(y))
u = askNum()
if (z == 1):
x * y #product
return 1
else if (z == 2):
x + y #sum
return 1
else if (z == 3):
x / y #difference
return 1
else
return 0
amount = 10
correct = 0
for i in range(amount):
correct += askQuestion()
print("You got %d correct out of %d" % (correct, amount))
OUTPUT:
md35#isu:/u1/work/python/mathquiz> python3 mathquiz.py
File "mathquiz.py", line 27
if (z == 1):
^
IndentationError: unexpected indent
md35#isu:/u1/work/python/mathquiz>
With this currently output, I double checked with corrected Python formatting and everything are sensitive, and still the same as running output. Any help would be more appreciated with explanation. (I hope my English is okay to understand since i'm deaf) I have started this since on Saturday, than expected on time to meet.
Your problem is that python 3 does not allow mixing spaces and tabs for indentation. Use an editor that displays the whitespace used (and fix manually) or one that replaces tabs into spaces. It is suggested to use 4 spaces for indentation - read PEP-0008 for more styling tips.
You can make your program less cryptic if you use '+','-','*','/' instead of 1,2,3,4 to map your operation: ops = random.choice("+-*/") gives you one of your operators as string. You feed it into a calc(a,ops,b) function and return the correct result from it.
You can also shorten your askNum and provide the text to print.
These could look like so:
def askNum(text):
"""Retunrs an integer from input using 'text'. Loops until valid input given."""
while True:
try:
return int(input(text))
except ValueError:
print("Incorrect Input!")
def calc(a,ops,b):
"""Returns integer operation result from using : 'a','ops','b'"""
if ops == "+": return a+b
elif ops == "-": return a-b
elif ops == "*": return a*b
elif ops == "/": return a//b # integer division
else: raise ValueError("Unsupported math operation")
Last but not least you need to fix the division part - you allow only integer inputs so you can also only give division problems that are solveable using an integer answer.
Program:
import random
total = 10
correct = 0
nums = range(1,11)
for _ in range(total):
ops = random.choice("+-*/")
a,b = random.choices(nums,k=2)
# you only allow integer input - your division therefore is
# limited to results that are integers - make sure that this
# is the case here by rerolling a,b until they match
while ops == "/" and (a%b != 0 or a<=b):
a,b = random.choices(nums,k=2)
# make sure not to go below 0 for -
while ops == "-" and a<b:
a,b = random.choices(nums,k=2)
# as a formatted text
result = askNum("What is {} {} {} = ".format(a,ops,b))
# calculate correct result
corr = calc(a,ops,b)
if result == corr:
correct += 1
print("Correct")
else:
print("Wrong. Correct solution is: {} {} {} = {}".format(a,ops,b,corr))
print("You have {} out of {} correct.".format(correct,total))
Output:
What is 8 / 1 = 3
Wrong. Correct solution is: 8 / 1 = 8
What is 5 - 3 = 3
Wrong. Correct solution is: 5 - 3 = 2
What is 4 - 2 = 3
Wrong. Correct solution is: 4 - 2 = 2
What is 3 * 1 = 3
Correct
What is 8 - 5 = 3
Correct
What is 4 / 1 = 3
Wrong. Correct solution is: 4 / 1 = 4
What is 8 * 7 = 3
Wrong. Correct solution is: 8 * 7 = 56
What is 9 + 3 = 3
Wrong. Correct solution is: 9 + 3 = 12
What is 8 - 1 = 3
Wrong. Correct solution is: 8 - 1 = 7
What is 10 / 5 = 3
Wrong. Correct solution is: 10 / 5 = 2
You have 2 out of 10 correct.
def askQuestion():
x = random.randint(1, 10)
y = random.randint(1, 10)
z = random.randint(1, 4)
print("What is " + str(x) + " "+ str(z)+ " " +str(y))
u = askNum()
if (z == 1):
x * y #product
return 1
elif (z == 2):
x + y #sum
return 1
elif (z == 3):
x / y #difference
return 1
else:
return 0
Write your block like this your u = askNum() and next if loop should be on same vertical line.
To Generate n number of random number you can use
random.sample(range(from, to),how_many_numbers)
User this as reference for more info on random
import random
low=0
high=4
n=2 #no of random numbers
rand = random.sample(range(low, high), n)
#List of Operators
arithmetic_operators = ["+", "-", "/", "*"];
operator = random.randint(0, 3)
x = rand[0];
y = rand[1];
result=0;
# print(x, operator, y)
if (operator == 0):
result = x + y# sum
elif(operator == 1):
result = x - y# difference
elif(operator == 2):
result= x / y#division
else :
result=x * y# product
print("What is {} {} {}? = ".format(x,arithmetic_operators[operator],y))
The following stores a random number(int)
operator = random.randint(0, 3)
to compare it with the list for operators.
Example: operator = 2
elif(operator == 2):
result= x / y#division
than this code will executed and because operator=2, 3rd element from list(/) will be selected
Output:
What is 3 / 2?

Python-Why aren't my elif statements not getting evaluated in this recursive multiplication which takes into account negative numbers

Hi I have looked up a few recursive multiplication of 2 numbers in python, but none of them take into account the possibility of negative numbers or if they do they don't explain the entire steps.
I have coded the following the program but I am getting an error, can someone please let me know what is wrong with it?
def mult(a,b):
if a==0 | b==0:
return 0
elif a==1:
return b
elif a > 0 & b >0:
return b + mult(a-1,b)
elif a < 0 & b > 0:
return - b + mult(a+1,b))
elif a > 0 & b < 0:
return - b + mult(a-1, b))
else:
return -b + mult(a+1, b)
print(mult(-4,5))
| and & are bitwise operators, not logical operators, and their (relatively) high precedence means that a > 0 & b >0 is parsed as a > (0 & b) > 0, which is not what you want. Use or and and instead.
You have some python syntax errors and some sign problems. This works for mult(-4,5) and mult(5,-4).
def mult(a,b):
if a == 0 or b == 0:
return 0
elif a == 1:
return b
elif b == 1:
return a
elif a >0 and b > 0:
return b + mult(a-1,b)
elif a < 0 and b > 0:
return -b+mult(a+1,b)
elif a > 0 and b < 0:
return b+mult(a-1,b)
else:
return b + mult(a+1,b)
In your elif statement, you're using a bitwise "and" operator rather than the logical and operator. Everywhere that you have "&" replace it with "and"

Writing an algorithm to generate prime numbers in Python within a given range [duplicate]

This question already has answers here:
Fastest way to list all primes below N
(39 answers)
Closed 6 years ago.
I see that there are many different ways to generate prime numbers. My code is very long and redundant but I know it can definitely be condensed and made less repetitive with a few changes and I was hoping I could be pointed in the right direction. Essentially I would like to automate the process that is being shown in my code so it can work for any range and all prime numbers.
Here is my code:
def primes():
multiplesList1 = []
multiplesList2 = []
multiplesList3 = []
multiplesList4 = []
multiplesList5 = []
multiplesList6 = []
multiplesList7 = []
multiplesList8 = []
multiplesList9 = []
for i in range(2,1000):
if i % 2 != 0 or i == 2:
multiplesList1.append(i)
for j in multiplesList1:
if j % 3 != 0 or j == 3:
multiplesList2.append(j)
for x in multiplesList2:
if x % 5 != 0 or x == 5:
multiplesList3.append(x)
for y in multiplesList3:
if y % 11 != 0 or y == 11:
multiplesList4.append(y)
for z in multiplesList4:
if z % 13 != 0 or z == 13:
multiplesList5.append(z)
for a in multiplesList5:
if a % 17 != 0 or a == 17:
multiplesList6.append(a)
for b in multiplesList6:
if b % 19 != 0 or b == 19:
multiplesList7.append(b)
for c in multiplesList7:
if c % 23 != 0 or c == 23:
multiplesList8.append(c)
for d in multiplesList8:
if d % 29 != 0 or d == 29:
multiplesList9.append(d)
return multiplesList9
print(primes())
All you need to do is create a second for loop with a range up until the previous number and check each modulus. If 0 is the result then it must not be prime.
if __name__ == "__main__":
prime = True
for i in range(2, 1000):
for x in range(2, i):
if i % x == 0:
prime = False
if prime:
print(i)
prime = True

Categories

Resources