Reverse number in python - Recursion [duplicate] - python

I’m trying to create a Python program that can tell you how many digits there are in a number. For example, the input 2345 yields the output 4 digits. I tried making it a while loop but now it prints how many digits are in the number infinitely.
interger = int(input('please type an interger and the programme will tell you how many digits it has!: '))
while interger != 0:
if 0 < interger < 10:
print ('1 digit')
elif 9 < interger < 100:
print('there are 2 digits')
elif 99 < interger < 1000:
print('there are 3 digits')
elif 999 < interger < 10000:
print('there 4 digits')
elif 9999 < interger < 100000:
print('there are 5 digits')
elif 99999 < interger < 1000000:
print ('there are 6 digits')
elif 999999 < interger < 10000000:
print('there are 7 digits')
elif 9999999 < interger < 100000000:
print('there are 8 digits.')
break
elif interger == interger:
print('that is correct')

Your 'while' condition is the cause of the infinite printing, as the value of interger is never changed. If you would like it to simply execute the print once, change
while interger!=0:
to
if interger != 0:
My suggestion for your script:
run = None
while run != 'q':
integer = input("Enter number: ")
print(f'There are {len(integer)} digits')
run = input("Enter q to quit, enter any other key to do another")

If not helpful for you, I will suggest another way.
interger= int(input('please type an interger and the programme will tell you how many digits it has!: '))
dig = 0
while(interger != 0) :
interger /= 10
dig += 1
print("There are " + str(dig) + " digits.")
How about this?

Python code to tell number of digits in an input number and print answer only once
interger = int(input('please type an interger and the programme will tell you how many digits it has!: '))
#to print once
print(f"given input {interger} has {len(str(interger))} digits")
output
please type an interger and the programme will tell you how many digits it has!: 65
given input 65 has 2 digits

Leaving aside the fact that the algorithm is less than ideal, you just don't need a loop.
interger= int(input('please type an interger and the programme will tell you how many digits it has!: '))
if 0<=interger<10: # zero is also 1 digit
print ('1 digit')
elif 9<interger<100:
print('there are 2 digits')
#etc.

Related

Why does my program to calculate the average of numbers entered into a while loop not work as expected?

I am new to coding. I would like to attend a course but there are assessments first in order to be chosen.
The question I am stuck on is:
Write a program that always asks the user to enter a number. When the user enters the negative number -1, the program should stop requesting the user to enter a number. The program must then calculate the average of the numbers entered excluding the -1.
num = 0
inputs = []
while True:
num = int(input("Please enter a number between -1 and 5: "))
if num > -1:
break
else:
inputs.append(int(num))
print (sum(inputs) / len(inputs))
so lets break this down together.
This is fine.
num = 0
inputs = []
You will want to modify this while true statement to be while True (if using python) like below
while True:
Next, it doesn't explicitly say integers, and technically there are different number types, but for simplicity sake we check to see if the number entered is an integer to avoid trying convert a letter to an integer. (This will cause a ValueError). We make a decision to ignore this type of bad input and continue.
input_value = input("Please enter a number between -1 and 5: ")
try:
num = int(input_value)
except ValueError:
continue
The condition for stopping the loop is entering -1 (if I understood the question properly). So, first check to see if the number entered matches the condition to stop: if num == -1: break.
if num == -1:
break
otherwise, you will want to check to be sure the number is in range before it is added to your inputs array, otherwise ignore it and wait for the next input. The question asks for any number, but since you're prompting for specific input, we're making a decision here not to accept numbers out of bounds of what was prompted for.
elif num < -1 or num > 5:
continue
Finally, if input is not -1, and the input is a number between 0-5 inclusive, add it to the array and await the next input.
else:
inputs.append(num)
Finally at the end of the return after -1 was received, it is possible the first number entered was -1, or all values entered were invalid. Both of these scenarios would result in division by 0, and an error being thrown. So you would want to set the minimum number that can be set as the divisor to 1 to ensure you don't crash trying to calculate your answer:
print(sum(inputs) / max(len(inputs), 1))
And now putting it all together:
num = 0
inputs = []
while True:
input_value = input("Please enter a number between -1 and 5: ")
try:
num = int(input_value)
except ValueError:
continue
if num == -1:
break
elif num < -1 or num > 5:
continue
else:
inputs.append(num)
return sum(inputs) / max(len(inputs), 1)
Maybe this is the code you are looking for just changing if num > -1 to if num == -1 to agree with the question you posted:
num = 0
inputs = []
while True:
num = int(input("Please enter a number between -1 and 5: "))
if num == -1:
break
else:
inputs.append(num)
print(sum(inputs) / len(inputs))
and it works just fine having as a result:
Please enter a number between -1 and 5: 5
Please enter a number between -1 and 5: 4
Please enter a number between -1 and 5: 3
Please enter a number between -1 and 5: 2
Please enter a number between -1 and 5: 1
Please enter a number between -1 and 5: -1
3.0

I get a syntaxt error when I try to run the program

I get a syntax error on the last else statement. This is supposed to be a grade calculator. If someone enters anything that isn't between 0 and 100, then the program should send a message, and then loop until a valid number is entered. Also I am new to programming, so if there is something else wrong with my code, please let me know!
number = int(input("Enter the numeric grade: "))
if number > 89:
letter = 'A'
elif number > 79:
letter = 'B'
elif number > 69:
letter = 'C'
else:
letter = 'F'
print("The letter grade is", letter)
number = int(input("Enter the numeric grade: "))
if number > 100:
print("Error: grade must be between 100 and O")
elif number < 0:
print("Error: grade must be between 100 and O")
else:
# The code to compute and print the result goes here
number = int(input("Enter the numeric grade: "))
if number > 100 or number < 0:
print("Error: grade must be between 100 and 0")
else:
# The code to compute and print the result goes here
number = int(input("Enter the numeric grade: "))
if number >= 0 and number <= 100:
else:
print("Error: grade must be between 100 and O")
Your issue is at the bottom, where you've got an empty if statement followed by an else statement, as well as incorrect indenting. From your code, I believe you are trying to use not.
I would suggest doing one of two things:
1.
if not (number >= 0 and number <= 100):
2.
if number < 0 or number > 100:
These two pieces of code will both produce the same result.
Also, it seems as though you are repeating the same code several times to try to ensure that the user inputs a number between 0 and 100. If so, this can be achieved with a while loop. I've put an example of this below:
number = int(input("Enter the numeric grade: "))
while number < 0 or number > 100:
print("Error: grade must be between 100 and O")
number = int(input("Enter the numeric grade: "))
In the last line.
if number >= 0 and number <= 100:
else:
print("Error: grade must be between 100 and O")
you didn't write anything after the if statement.
This code will run
if number >= 0 and number <= 100:
print('Write something here')
else:
print("Error: grade must be between 100 and O")
or you can just remove the last if statement its really of no use like try doing something else because there are a lot of if and else statements which don't look nice.
try this:
n = int(input())
first = 0
last = 100
while n < first or n > last:
print(n,'is not a valid input')
n = int(input())
From what I've understood, you're trying loop indefinitely until the user input is between 0 and 100.
My solution would be this:
Define a function that starts by requesting an input from the user.
Use a while loop that will check if the input is 'correct'. In case the input is not correct, the loop will print the error and call back the function again indefinitely till the user's input is between 0 and 100.
if the input is between that range, it will then evaluate the grade and return it.
def yfunc():
n = int(input('Enter the numeric grade: '))
while n < 0 or n > 100:
print("Error: grade must be between 100 and O")
return yfunc()
if n > 89:
letter = 'A'
elif n > 79:
letter = 'B'
elif n > 69:
letter = 'C'
else:
letter = 'F'
return letter
yfunc()
If you have any questions, feel free to ask.

Python program to read whole numbers and stop when 0 entered, then prints total positive numbers entered

I am trying to write a program where a user enters a bunch of numbers and when 0 is entered the program ends and prints how many positive numbers were entered. I am fairly close to solving this but can't get the positive sum to print.
Could you please explain where I have gone wrong?
Thanks in advance.
Please see attached my code.
userInput = None
oddNum = 0
evenNum = 0
while(userInput != 0):
userInput = int(input("Enter a number: "))
if(userInput > 0):
if(userInput % 2 == 0):
evenNum += 1
elif(userInput % 2 != 0):
oddNum += 1
print("positive numbers were entered".format(evenNum, userInput))
You are missing some of the required syntax for the string.format() command.
For each variable you want injected into the string to be printed, you must include a pair of curly braces {}. Otherwise, the arguments you pass to string.format() are just ignored.
userInput = None
oddNum = 0
evenNum = 0
while(userInput != 0):
userInput = int(input("Enter a number: "))
if(userInput > 0):
if(userInput % 2 == 0):
evenNum += 1
elif(userInput % 2 != 0):
oddNum += 1
print("positive numbers were entered; {} even numbers, and {} odd numbers".format(evenNum, userInput))

Python Odd and Even

I am very new to python. I am trying to write a program that tests if a number is between a given range, then tells you if the number is odd or even. I am having trouble with the part that detects if it is odd or even. It seems that if it just repeats my even statement. Here is the code:
while True:
num = int(input("Please enter an integer between 1 and 50: "))
if num >= 1 and num <= 50:
for num in range (1, 50):
if (num % 2 == 0):
print("Your number is even.")
else:
print("Your number is odd.")
else:
print("Try again. Number must be 1 through 50.")
I don't think you need a for loop at all, and you forgot to indent the else part if your inner if-else:
while True:
num = int(input("Please enter an integer between 1 and 50: "))
if num >= 1 and num <= 50:
for num in range (1, 50): # not needed
if (num % 2 == 0):
print("Your number is even.")
else: # here
print("Your number is odd.")
else:
print("Try again. Number must be 1 through 50.")
for-else constructs exist (and are pretty neat), but it you're starting to learn Python, it's a story for another time.
Nope, you don't need the for loop:
while True:
num = int(input("Please enter an integer between 1 and 50: "))
if 1 <= num <= 50:
if num % 2 == 0:
print("Your number is even.")
else:
print("Your number is odd.")
else:
print("Try again. Number must be 1 through 50.")
I think you don't need for loop, Remove for loop and try again.
while True:
num = int(input("Please enter an integer between 1 and 50: "))
if num >= 1 and num <= 50:
if (num % 2 == 0):
print("Your number is even.")
else: # here
print("Your number is odd.")
else:
print("Try again. Number must be 1 through 50.")

What's wrong with my use of if / then in this script?

I'm learning if and then statements. I'm trying to write code that takes any decimal number input (like 2, 3, or even 5.5) and prints whether the input was even or odd (depending on whether the input is actually an integer.)
I get an error in line 8
#input integer / test if any decimal number is even or odd
inp2 = input("Please enter a number: ")
the_number = str(inp2)
if "." in the_number:
if int(the_number) % 1 == 0
if int(the_number) % 2 == 0:
print("Your number is even.")
else:
print("Your number is odd.")
else:
print("You dum-dum, that's not an integer.")
else:
the_number = int(inp2)
if the_number % 2 == 0:
print("Your number is even.")
else:
print("Your number is odd.")
I'm just starting with python so I appreciate any feedback.
You have to include a colon at the end of second if statement, like you did in your other conditional statements.
if int(the_number) % 1 == 0:
Next time, give a closer look at the error message. It'll give you enough hints to fix it yourself, and that's the best way to learn a language.
EOL.
You forgot a :. Line 8 should read if int(the_number) % 1 == 0:.
Try putting the : at the end of the if statement
if int(the_number) % 1 == 0:
You can test your input as following code snippet
num = input('Enter a number: ')
if num.isnumeric():
print('You have entered {}'.format(num))
num = int(num)
if num%2:
print('{} is odd number'.format(num))
else:
print('{} is even number'.format(num))
else:
print('Input is not integer number')

Categories

Resources