Novice Coder with issue properly looping - python-3.x

So I'm a novice coder having never coded before and am teaching myself Python on the guidance of my CS instructor. I'm walking myself through "Automating the Boring Stuff with Python" and I'm having issues with the Collatz sequence portion at the end of Chapter 3. I've got the sequence down but I'm having issues properly looping the code in order to get the result I want which is looping the sequence until the answer is == to integer 1. This is what I have and I would love some feedback and assistance.
def collatz(number): #defines the collatz sequence
if number%2 == 0:
num1 = number//2
else:
num1 = 3 * (number + 1)
return num1
print("Let's try the collatz sequence. Enter a number")
num = int(input())
num3 = collatz(num)
while num3 != 1: #loops collatz sequence until it equals 1
num2 = collatz(num3)
if num2 == 1:
break
else:
num3 = collatz(num2)
print("ta da!")

You need this code:
def collatz(number):
if number % 2 == 0:
num1 = number//2
else: num1 = 3 * number + 1 # Do not use brackets!!! Or you will have infinite loop
return num1
print("Let's try the collatz sequence. Enter a number")
num = int(input())
while num != 1:
num = collatz(num)
print(num)
if num == 1: break
print("ta da!"); input()

Related

how i can fix this problem in python code

I'm new programmer and I am begginer, this my first time use stack overflow, I trying now to calcul a calculator calcul numbers like normal calculator, I want write something such as (" 7 - 2 * 3") and the code give the result.
The code is chaos im just begginer so please just try understand that and help me.
when you try the code input numbers and operators with space like this 5 + 5.
This the code :
from functools import reduce
question = input("Enter your calcul : ")
nums = question.split()
numbers = nums[0::2]
def calcul(num1, num2):
for x in variation:
if x == '+':
return num1 + num2
elif x == '-':
return num1 - num2
elif x == '*':
return num1 * num2
elif x == '/':
return num1 / num2
def wayy(lt):
for x in lt:
if '+' == x :
yield'+'
if '-' == x :
yield'-'
if '*' == x :
yield'*'
if '/' == x :
yield'/'
variations = [] # [ + , - , * , / ]
variation = wayy(nums)
for x in variation:
variations.append(x)
print(variations)
nm = []
for n in numbers:
n = int(n)
nm.append(n)
calcule = reduce(calcul, nm)
print(calcule)
I try coding a calculator and i have a problem i think it is in calcul function when i input the numbers the result is "None" I know the problem in function (calcul) but I dont know how I can fix it.
Only change "variation" to "variations" in the "calcul" function.
def calcul(num1, num2):
for x in variations:
if x == '+':
return num1 + num2
elif x == '-':
return num1 - num2
elif x == '*':
return num1 * num2
elif x == '/':
return num1 / num2
Since "variation" is a "Generator" object, but "variations" is a list of Strings (what you need).

Problem with a simple calculator program where an error always seems to occur when entering the number zero

I'm new to the stack overflow website, python, and programming as a whole. So pardon me if the title or body of this question isn't apt.
I'm trying to create a simple calculator program in python, which performs only four operations, namely, addition, subtraction (difference), multiplication and division.
Here's my code:
print("Welcome to the calculator \n")
num1 = int(input("Enter the first number \n"))
num2 = int(input("Enter the second number \n"))
operation = (input("""Enter the symbol of the operation to be performed. Your choices are:
+
- (Difference)
*
/
\n """))
add = num1+num2
sub1 = num1-num2
sub2 = num2 - num1
product = num1*num2
quotient = num1 / num2
if operation == "-" :
if num1 > num2:
print(sub1)
else:
print(sub2)
elif operation == "+" :
print(add)
elif operation == "*" :
print(product)
elif operation == "/" :
if num2 == 0:
print("Sorry, can't divide a number by zero")
else:
print(quotient)
else:
print("Please enter a valid operator from among the ones provided above")
Everything runs fine, except, when I enter zero as num2, and no matter what operator I select, the output
is this:
Traceback (most recent call last):
File "test4.py.txt", line 19, in <module>
quotient = num1 / num2
ZeroDivisionError: division by zero
Help would be greatly appreciated.Thanks!
Find the quotient inside the if condition, not before checking num==0, otherwise the division by zero is already done, causing the error.:
elif operation == "/" :
if num2 == 0:
print("Sorry, can't divide a number by zero")
else:
quotient = num1 / num2
print(quotient)
quotient = num1 / num2
That's the line that is giving you the error. You should be checking if num2 is zero before calculating num1 / num2. You can do it as follows and your program would work fine.
quotient
if num2 == 0:
quotient = None
else :
quotient = num1 / num2
Else you could just declare quotient and calculate the quotient when user inputs the operator. If user enters /, then you can check if num2==0 and if it is you can give error message.
Working code -
print("Welcome to the calculator \n")
num1 = int(input("Enter the first number \n"))
num2 = int(input("Enter the second number \n"))
operation = (input("""Enter the symbol of the operation to be performed. Your choices are:
+
- (Difference)
*
/
\n """))
add = num1+num2
sub1 = num1-num2
sub2 = num2 - num1
product = num1*num2
quotient = None # Don't divide by num2 here or you will get error of divisionbyzero
if operation == "-" :
if num1 > num2:
print(sub1)
else:
print(sub2)
elif operation == "+" :
print(add)
elif operation == "*" :
print(product)
elif operation == "/" :
if num2 == 0:
print("Sorry, can't divide a number by zero")
else:
quotient = num1 / num2
print(quotient)
else:
print("Please enter a valid operator from among the ones provided above")
Since you are new, I will explain this in more detail so you actually know what you are doing wrong
Pay attention to these lines
add = num1+num2
sub1 = num1-num2
sub2 = num2 - num1
product = num1*num2
quotient = num1 / num2
When you do this it is actually performing the calculation and assigning it to the respective value (i.e. quotient = num1 / num2 will actually do the calculation and store the result in the quotient variable). So, you are doing every calculation every time regardless of your choice of operator. It would be better to assign the values only if that operator has been chosen like below.
print("Welcome to the calculator \n")
num1 = int(input("Enter the first number \n"))
num2 = int(input("Enter the second number \n"))
operation = (input("""Enter the symbol of the operation to be performed. Your choices are:
+
- (Difference)
*
/
\n """))
if operation == "-" :
sub1 = num1-num2
sub2 = num2 - num1
if num1 > num2:
print(sub1)
else:
print(sub2)
elif operation == "+" :
add = num1+num2
print(add)
elif operation == "*" :
product = num1*num2
print(product)
elif operation == "/" :
if num2 == 0:
print("Sorry, can't divide a number by zero")
else:
quotient = num1 / num2
print(quotient)
else:
print("Please enter a valid operator from among the ones provided above")
This part is just a suggestion. You could also make your Difference operation easier by using the following.
if operation == "-" :
sub1 = num1-num2
print(abs(sub1))
abs gets the absolute value, basically removes the negative.
You should calculate the results only after checking the operators (thus avoiding any errors caused by trying to divide by zero), this way you will also avoid unnecessary calculations:
elif operation == "/" :
if num2 == 0:
print("Sorry, can't divide a number by zero")
else:
quotient = num1 / num2
print(quotient)

My program is not recognizing its using a negative number

I just started programming for school and this assignment requires me to enter a number and then use it to count from 0 up to the number, then choose a math operation, and then use that math operation.
The problem occurs when I enter a negative number, it gives me the correct message "Too small - Try again: " . but once I enter a positive number it still assigns my original negative number to the program.
Here is my noobie code:
num1 = int(input("\nEnter a number 1 or greater:\t"))
counting = num1 + 1
def count():
print("Counting from 0 to", num1,":")
for i in range(0,counting):
print(i, end = ' ')
math_op()
def reset():
num1 = int(input("Too small - Try again: "))
if num1 <= 0:
reset()
else:
count()
def math_op():
ops = input("\n\nChoose math operation (+, -, *)")
if ops in ('+'):
print("Table for",num1,"using +:")
for i in range(1,11):
print(num1 ,'+', i ,'=', num1 + i)
if ops in ('-'):
print("Table for",num1,"using -:")
for i in range(1,11):
print(num1 ,'-', i ,'=', num1 - i)
if ops in ('*'):
print("Table for",num1,"using *:")
for i in range(1,11):
print(num1 ,'*', i ,'=', num1 * i)
if num1 <= 0:
reset()
else:
count()
Yes, you're missing a while loop:
num1 = -1
while num1 < 1:
num1 = int(input("\nEnter a number 1 or greater:\t"))
# remaining code after here
you never set the number to count when the correction is positive:
def reset():
num1 = int(input("Too small - Try again: "))
if num1 <= 0:
reset()
else:
counting = num1 + 1
count()

Finding prime numbers Python

I am making script , that finds prime numbers in specific range from 0 to X. Its works partially , it appends 2 and remove even numbers from list , but it doesnt go over 3.
cis = int(input("xd: "))
list1 = []
list2 = []
num = 2
while (num in range(0,cis)):
list1.append(num)
num += 1
continue
num2 = list1[0]
for i in list1:
if list1[0] in list2:
None
else:
list2.append(list1[0])
if i % num2 == 0:
list1.remove(i)
continue
if all(a % num2 != 0 for a in list1):
num2 += 1
continue
print (list1)
print (list2)
Thanks for help.

When comparing 2 variables output always the same

this is my code for a quiz with ten question.the problem is that whenever I write the answer (the answer gets printed before asking the question) it always say incorrect. please take into consideration that I am very bad at the language and don't correct what doesn't need to be fixed. Thankyou.
from random import randint
name = input("what is your name?")
score = 0
qn = 0
def q():
global qn
global name
global score
qn += 1
if qn < 11:
num1 = randint(1,12)
s = randint(1,3)
num2 = randint(1,12)
if s == 1:
symbal = '+'
answer = num1 + num2
elif s == 2:
symbal = '-'
answer = num1 - num2
elif s == 3:
symbal = '*'
answer = num1 * num2
print(answer)
print(num1 ,symbal ,num2)
sanswer = input("= ?")
if answer == sanswer:
score += 1
print("correct!!!")
else:
print("incorrect")
q()
else:
global name
print("""welldone""")
print(name)
q()
from random import randint
name = input("what is your name?")
score = 0
qn = 0
def q():
global qn
global name
global score
qn += 1
if qn < 11:
num1 = randint(1,12)
s = randint(1,3)
num2 = randint(1,12)
if s == 1:
symbal = '+'
answer = num1 + num2
elif s == 2:
symbal = '-'
answer = num1 - num2
elif s == 3:
symbal = '*'
answer = num1 * num2
print(num1 ,symbal ,num2)
sanswer = int(input("= ?"))
print(answer)
if answer == sanswer:
score += 1
print("correct!!!")
else:
print("incorrect")
q()
else:
global name
print("""welldone""")
print(name)
q()
2 mistake you have:
first: you shouldn't put print(answer) before input
second: you should sanswer = int(input("= ?")) use int() because what you take with input is string
and a simple suggestion try not to use global when coding.

Resources