collatz sequence name not defined [duplicate] - python

This question already has answers here:
Collatz Sequence. (Python 3)
(3 answers)
Closed 4 years ago.
calculation = 0
def collatz(number):
global calculation
if number % 2 == 0:
calculation = number // 2
print(calculation)
return calculation
#odd number
elif number % 2 == 1:
calculation = 3 * number + 1
print(calculation)
return calculation
try:
number = collatz(input('Type a number:')))
except:
while type(number) != int:
print('Please type a numerical value')
number = collatz(int(input('Type a number:')))
while calculation > 1:
collatz(calculation)
Question:
while doing a project from the python book i'm reading i was instructed to create a program that utilizes the collatz conjecrture. I had no problems doing everything up to the point where it wanted me to do exception handling in case the user types a none integer value in. i used the type function to loop through everything in the except statements block of code until the user types an integer value but for some reason it throws an error when it reaches the while loop under the except statement stating that "Name 'number' is not defined' and i'm not sure why its throwing this error

In the except block of your code, where will number have been defined? It could not be in the try block, because if you're executing the except block then by definition the operation of the try block had failed.
As a separate comment, consider what type of data you would get back from input and what can collatz return if neither of the if or else conditions is satisfied?

Related

ATBSWP Chapter 3 Practice Project - Wits end after 6 hours, yeah tell me about it

I have Youtubed,searched stack overflow and reddit for the the question and answer. Which I have found, but don't want to copy and paste the code just to get the answer but want to understand it.
Question and Answers: Making a collatz program automate the boring stuff (What I have learnt, which I thought was B.S. There are thousands of ways to answer a question with little to lots of code, surprising)
#Part 1 of The Collatz Sequence Chapter 3 practice project.
def collatz(number): #Defining the collatz function.
if number % 2 == 0:#If number is even use (number % 2 == 0)
print(number // 2)
return (number // 2) #What to return/print if number is even.
elif number % 2 == 1: #If number is odd use (number % 2 == 1)
print(3 * number + 1)
return (3 * number + 1) #What to return/print if number is odd.
#Part 2 and 3 of The Collatz Sequence Chapter 3 practice project.
print('Enter number:') #Asking the person to enter a number.
while True:
try: #To avoide non number erros.
number = int(input()) #Persons input.
except (NameError, ValueError):#To ignore the errors that occur from strings and other non integers.
print('Enter an integer:')#If person does not enter a number, ask them to.
if number == 1:
break
print('Collatz Sequence Destination Achiveid')
(Yes, there are a lot of comments, but that was just to understand where I was effing up).
From my interpretation of code. I am screwing up where I am under section 2. I am having difficulty linking the user input into Collatz and the while loop but believe I have already done with "number = int(input())?. My code is also not initiating the Collatz sequence I have no idea why? maybe it's not linking to it. I also want to have it, if the person enters 1, it prints xyz after break and have used break to exist the loop if 1 is entered.
Am what I am doing right? I really liked this book upto this point and it's usually highly recommended. I have also read many Reddit threads were people have recommend other books such as python crash course. Would that book be better?. I don't think I am that dumb and understand the concepts and know how use them but this practice project is making me feel otherwise and many others have mentioned the same on threads.
*To whom ever is answering this, please try to nuke it down for me and where I went wrong or be open for me to ask question, thanks.
My code is also not initiating the Collatz sequence I have no idea why?
You don't actually call collatz in your code, so your program just prints out the number that the user inputs, and ends.
Next, your indentation is wrong. Inside the while True loop, your if block is not aligned with the other blocks.
I also want to have it, if the person enters 1, it prints xyz after break and have used break to exist the loop if 1 is entered.
For actual code, here it is. For the explanation, scroll further
#Part 1 of The Collatz Sequence Chapter 3 practice project.
def collatz(number): #Defining the collatz function.
if number % 2 == 0:#If number is even use (number % 2 == 0)
print(number // 2)
return (number // 2) #What to return/print if number is even.
elif number % 2 == 1: #If number is odd use (number % 2 == 1)
print(3 * number + 1)
return (3 * number + 1) #What to return/print if number is odd.
#Part 2 and 3 of The Collatz Sequence Chapter 3 practice project.
print('Enter number:')
while True:
try:
number = int(input())
except (NameError, ValueError):
print('Enter an integer:')
continue
if number == 1:
print("xyz")
break
while number != 1:
number = collatz(number)
print('Collatz Sequence Destination Achiveid')
How I figured it out
Firstly, we have 3 parts
Get the input from the user
Making sure the input is valid. If not, prompt the user again
Actually performing the collatz sequence
1. Getting the input from the user
That is as simple as
number = int(input())
2. Making sure the input is valid. If not, prompt the user again
Now, we know that if the user does not enter a number, python will throw an error when trying to perform int(input()). We also know that we want to repeatedly prompt again and again if the user gives us invalid input, hence we should realise that a loop has to be used. Now, which loop do we use? A while or for loop?
Usually, if we don't know how many times we want to loop, we will use a while. If we know, we will use a for. In this case, we don't know how many times the user might input something that is not valid, hence we will use a while loop. Basically, while the user does not give us a valid input, we ask him for an input.
So first, let us include a loop.
while True:
number = int(input())
if number == 1:
print("xyz")
break
This still does exactly the same thing as before. We have not added any error checking yet. However, we did add the check that if number == 1, we print xyz. We prepare this loop so that we can reprompt the user again if the number fails. Now for the actual error checking,
while True:
try:
number = int(input())
except (NameError, ValueError): non integers
print('Enter an integer:')
continue
if number == 1:
print("xyz")
break
This is your code, with the addition of the number==1 check, and a continue keyword. When python encounters the continue keyword, it will immediately go into the next iteration of the loop. This means that, inside the except block, it will go back up to the top of the loop again, skipping the rest of the loop. This is how you perform the reprompt.
The reason why I put a continue there is because I know that if the user gives me an incorrect input, I should immediately reject it, and reprompt the user once again. I don't have to do any additional checks.
Try to trace the path your code takes if the input is
a number that is not 1
the number 1
not a number
3. Actually performing collatz
Now that we have gotten the input from the user, we know that once we exit the loop, number is a valid number. Now we actually perform collatz.
Basically, while the number is not 1, we will have to continue calling collatz. Hence
while number != 1:
number = collatz(number)
print('Collatz Sequence Destination Achiveid')

Errors when converting input() function into an integer [duplicate]

This question already has an answer here:
Python - How to break while loop after empty value in a int turning input? [duplicate]
(1 answer)
Closed 2 years ago.
I have been trying to simply turn an input() function into an integer as the title of this question suggests. I am essentially trying to run a program that takes in as many inputs as the user inputs, but when an empty string is inputted, it breaks out of a loop and returns the average of all inputted numbers. Currently, my code looks like this:
count = 0
sum = 0.0
number = 1.0
while number != 0:
number = int(input(""))
sum = sum + number
count += 1
if number == 0:
continue
if number == "":
break
else:
print("Average is {}".format(sum / (count-1)))
The issue i face is the error:
ValueError: invalid literal for int() with base 10: ''
Does anyone have a simple solution for this? I feel like i'm overlooking something rather simple?
if number == "":
break
In the case where you want this to happen, number got its value as int(input()). That is, the attempt to convert to int happens first. Since an empty string cannot be converted to int, this test is not reached before the exception is thrown.
You should test for the exception anyway, using try:/except:. But if you want to compare a string to a string, you need to do it at the point where you still have the strings you want to do the comparison with.

How can I get Python to recognize comma as the decimal point in user input? [duplicate]

This question already has answers here:
Convert Python strings into floats explicitly using the comma or the point as separators
(3 answers)
Convert decimal mark when reading numbers as input
(8 answers)
Closed 2 years ago.
Super beginner here.
I'm following along the Automate the Boring Stuff With Python book and I decided to make a little script to help me out with some basic percentage checking. I didn't want to open Excel everytime I wanted to do this.
So the script gets two inputs, an old price and a new price and then calculates the percentage change in price. I think I got that right.
The problem occurs once I try to enter a float (that's the right term, yeah?) and I use the comma here in Europe.
I found a topic here where a similar question was answered, but there seems to be an issue on whether or not to call setlocale and (as far as I understand it) it does not deal with how to convert an input?
My code is below:
def izracun_odstotkov(): #function to calculate the difference in % between original price and new price
while True:
try:
prvotna_cena = float(input('Prosim vnesi prvotno ceno:')) #original price
except ValueError:
print('Oprosti, to ni veljavni podatek. Vnesi stevilko.')
continue
if prvotna_cena == 0:
print('Prvotna cena ne more biti 0.')
else:
break
while True:
try:
nova_cena = float(input('Prosim vnesi novo ceno:')) #new price
except ValueError:
print('Oprosti, to ni veljavni podatek. Vnesi stevilko.')
continue
else:
break
print(round((float (nova_cena)- float (prvotna_cena))/ float (prvotna_cena)*100, 2), '%')
while True:
izracun_odstotkov() #This makes the script run over and over so the user can just keep checking the % changes.
You can use the replace method:
prvotna_cena = float(input('Prosim vnesi prvotno ceno:').replace(',','.'))

How to use input() to only accept positive numbers as int, [duplicate]

This question already has answers here:
Asking the user for input until they give a valid response
(22 answers)
I'm getting an IndentationError. How do I fix it?
(6 answers)
Closed 4 years ago.
im really new in Python 3.7
im testing some stuff out, and i try to understand how can i ask someone his age. but if he enter a letter or a negative number it say, only positive number please then it ask the question again, if the number is positive then the program continue.
here is my code so far giving me an error:
while true :
age = input('Your age : ')
try:
age = int(age)
except ValueError:
print ('Numbers only')
continue
else:
break
giving me as error : ,
> line 10
age = input()
^
SyntaxError: expected an indented block
Does this help? This works:
while True:
age = input('Your age')
try:
age = int(age)
break
except ValueError:
print ('Numbers only')
Explanation: condition 'True' is True by definition, so the loop occurs indefinitely until it hits a "break." Age takes standard input and tries to convert it to an integer. If a non-integer character was entered, then an exception (ValueError) will occur, and "Numbers only" will be printed. The loop will then continue. If the user enters an integer, the input will be converted to an integer, and the program will break from the loop.
In regard to syntax errors: In Python syntax, it the keyword is "True" instead of true. You need to indent all items following a loop or conditional (in this instance, the error occurred when the program encountered age=input('Your age :'), which needs to be indented.

Recursive Power Function Step [duplicate]

This question already has answers here:
Basics of recursion in Python
(5 answers)
Closed 7 years ago.
I have this:
def main():
input1 = input('Enter an integer for the base:')
input2 = input('Enter an integer for the exponent:')
main()
This is what I fully need to do:
Create a main, and a power function. Half done.
prompt the user to enter an integer for the base of the power. Done.
prompt the user for an integer for the exponent of the power. Done.
call the power function and print its returned value. Can do.
The recursive power function, power(base,exponent), must recursively calculate the value of the power and then return it. Need help with this.
I have been trying to learn the recursive function stuff the past two days, and cannot seem to wrap my head around it. Could someone provide me a walk through of this, so I can mess around with it, so I can understand it better? Thanks!
You basically need to multiply a given number to itself until the power reaches zero:
def power(x, y):
if y == 0:
return 1
if y >= 1:
return x * power(x, y - 1)

Categories

Resources