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')
Related
Complete beginner here, I'm currently reading through "Automate the Boring Stuff With Python" by Al Sweigert. I'm running into an issue where my program is returning a None value and I can't figure out how to change that.
I understand that at some point collatz(number) doesn't have a value, therefor None is returned- but I don't understand how to fix it. The book hasn't touched on yield yet. I've tried using return instead of print within the function, but I haven't been able to fix it.
def collatz(number):
while number != 1:
if number % 2 == 0:
number = number // 2
print(number)
elif number % 2 == 1:
number = 3 * number + 1
print(number)
print('Enter number:')
try:
number = int(input())
print(collatz(number))
except ValueError:
print ('Please enter an integer.')
As #chepner proposed you need to remove the print statement which is enclosing your collatz(number) call. The correct code would look like
def collatz(number):
while number != 1:
if number % 2 == 0:
number = number // 2
print(number)
elif number % 2 == 1:
number = 3 * number + 1
print(number)
print('Enter number:')
try:
number = int(input())
collatz(number)
except ValueError:
print ('Please enter an integer.')
hi there i'm learning python
i like to know if this script can be better or shorter
import sys
g = 1
def trying():
q = input('enter (y or yes) to retry')
if not q == 'y' or q == 'yes':
return 0
while g == True:
try:
t = int(input('please enter an integer:'))
r = t % 2
if r == 0:
print('your number is even')
if trying() == 0:
g = 0
else:
print('your number is odd')
if trying() == 0:
g = 0
except ValueError:
print('sorry you need to enter numbers only')
If you want in shorter, here is my version..
while True:
try:
print('Your number is %s' % ('even' if int(input('Please enter an integer: ')) % 2 == 0 else 'odd'))
if input('Enter (y or yes) to retry: ') not in ['y', 'yes']: break
except ValueError:
print('Sorry you need to enter numbers only')
What you want here is a do-while loop. You can easily implement it by adding a break statement to a infinite while-loop. More on this topic can be found here.
Next thing, you have to add a try-except statement as there is a string to integer conversion is happening.
print('Your number is %s' % ('even' if int(input('Please enter an integer: ')) % 2 == 0 else 'odd'))
This statement will return "Your number is even" if the input is even else it will return "Your number is odd". This method is called python ternary operator.
Then you can wrap it with a print-function to print the returned string. Look here.
input('Enter (y or yes) to retry: ') not in ['y', 'yes']
This check whether the user input is not there in the given list. So if user input is neither "y" or "yes", while-loop will break.
Here is an example of how the code can be made simpler. Remember that code should rarely be repeated. In most cases, if you have repeating lines of code it can be simplified.
while True:
try:
t = int(input('please enter an integer:'))
if t % 2 == 0: print('your number is even')
else: print('your number is odd')
q = input('enter (y or yes) to retry')
if not (q == 'y' or q == 'yes'): break
except ValueError:
print('sorry you need to enter numbers only')
def trying():
question = input('enter (y or yes) to retry')
if not (q == 'y' or q == 'yes'):
return 1
return 0
while True:
try:
num1 = int(input('please enter an integer:'))
num2 = t % 2
if not num2:
print('your number is even')
else:
print('your number is odd')
if trying():
break
except ValueError:
print('sorry you need to enter numbers only')
You don't have to import sys in your program as you didn't used it and you don't have to. You don't have to store anything in a variable for a while loop. Just assigning True and breaking out will do. If you're looking for anything that is True (this includes an unempty list, string, and dictionaries; and numbers not equal to 0). You should make if var:. If the variable evaluates to True. The conditional block will be executed. This is a clearer syntax so it is recommended. Name your variables with words, not with letters. This will not make your code longer and it will make your code better.
This is all I can do with your code. If there is more, please state them.
why do i get an error whitch says invalid, about this code?
line = input("Enter an integer number : ")
num = int(line)
if (num % 2 == 0):
print("The number is even" ,num)
else:
print("The number is odd ", num)
You need to indent your code properly:
line = input("Enter an integer number : ")
num = int(line)
if (num % 2 == 0):
print("The number is even" ,num)
else:
print("The number is odd ", num)
If you're fairly new to python, a good point to start could be the documentation to learn about Block indentation.
Another problem could arise if its not possible to change the input within the variable line into an integer with int(line). You might want to have a look how to work with try and except to handle errors like that.
I wrote this script but it always returns the same answer ("Your guess is too high"), no matter what the user inputs. Any insight would be helpful.
import random
number = random.randint(1, 10)
guess = input("Guess a number between 1 and 10: ")
if type(guess == int):
print(number) # this prints the randint to show the code isn't working
while(number != 0):
if(guess > number):
print("Your guess is too high!")
break
elif(guess < number):
print("That's too low.")
break
elif(guess == number):
print("Thats's right!")
break
else:
print("Please enter a number.")
Your while loop is useless, the problem of testing the input as an int is better handled with a try/except.
All together the correct answer is in Python3 :
import random
number = random.randint(1, 10)
found = False
while not found:
try:
guess = int(input("Guess a number between 1 and 10: "))
if guess > number:
print("Your guess is too high!")
elif guess < number:
print("That's too low.")
elif guess == number:
print("Thats's right!")
found = True
except ValueError:
print("Please enter a number.")
if type(guess == int):
This isn't doing what you expect. It always returns True because it's the equivalent to bool(type(False)). First make sure to convert your input to an int
guess = int(input("Guess a number between 1 and 10: "))
and then remove this if statement:
if type(guess == int):
Your problem is that this code:
if(guess > number)
is always comparing a string to an int, so once you correct that your code will be fixed.
I have just copied and pasted your code and it seems to function mostly correctly. There are some issues with it though. First, it appears that this is written for python 2 based on the way you are using the input function. However this is bad practice as the input() function in python 2 includes an implicit call to the eval() function which could allow for arbitrary code to be run.
In python 2 the better practice would be to use guess = int(raw_input("Guess a number between 1 and 10: ")).
In python 3, raw_input() has been removed and input() replaces it. So in python 3 you would use guess = int(input("Guess a number between 1 and 10: ")).
Your final else block is also indented where it should not be, although if you revise your code to make use of the advice given above, your if...else block is no longer necessary.
That's because input returns a string in Python 3. You need to call int() to make it an integer type:
guess = int(input("Guess a number between 1 and 10: "))
You're also using the type() function incorrectly. You probably want the function isinstance(): if isinstance(guess, int):
Also, in Python, we don't need parentheses like you've used. You can simply do if guess > number:
import random
print("Pick a number from 1-50")
randomNumber = random.randint(1,50)
correct = False
while not correct:
try:
userInput = int(input("Insert your number here. "))
except ValueError:
print("That is not a Number!")
continue
if userInput > randomNumber:
print("Guess lower.")
elif userInput < randomNumber:
print("Guess Higher.")
else:
print("You got it!")
break
So this code currently takes the user input and says whether the user guessed the random integer, or if they should guess higher/lower. I want to edit the code to now say whether the user input is within 5,10,15, etc of the random integer.
So if the random integer was 30, and the user inputs 20, the program would say something like "You are within 10; guess higher."
Any advice? I'm extremely new to python, so please respond with more simple methods if possible.
Thanks.
PS: Oh, preferably without the use of modules, mainly because I'm still learning.
I think this does what you want, and it cuts down on the if chains a little:
import random
print("Pick a number from 1-50")
randomNumber = random.randint(1,50)
correct = False
while not correct:
try:
userInput = int(input("Insert your number here. "))
except ValueError:
print("That is not a Number!")
continue
if randomNumber == userInput: # Let's check this first!
print ("YOU WIN!!!")
break # We use break b/c changing correct would still run rest of loop
acceptable_ranges = [5, 10, 15, 20, 25, 30, 25, 40, 45, 50]
guess_error = userInput - randomNumber
i = 0
while abs(guess_error) > acceptable_ranges[i]: # see how close they are
i += 1
if guess_error < 0: # let's figure out where they need to go
next_guess_direction = "higher"
else:
next_guess_direction = "lower"
print (("You are within %i: Please guess %s")
%(acceptable_ranges[i], next_guess_direction))
Let's look. at the last if statement a little further and the final print line. We are checking to see if guess_error, defined above (line 15) guess_error = userInput - randomNumber is less than 0 (negative). If it is less than zero, then we make the variable next_guess_direction equal to the string "higher," because the next guess needs to be larger than the last one (randomNumber was larger than userInput. If guess_error is not negative, then it is positive, because we already eliminated the we eliminate the possibility of 0 using:
if randomNumber == userInput: # Let's check this first!
print ("YOU WIN!!!")
So, if guess_error is positive, we know that userInput was larger than randomNumber and we set next_guess_direction equal to the string "lower." Finally, we print out everything that we have found:
print (("You are within %i: Please guess %s")
%(acceptable_ranges[i], next_guess_direction))
I am using an older version of formatting where %i and %s are placeholders for integer and string, respectively. I then define what should be formatted there using %(acceptable_ranges[i], next_guess_direction), which simply means to put acceptable_ranges[i] in for the integer and next_guess_direction in for the string. Keep in mind, we found i in acceptable_ranges[i] right above the if statement.
I know that is all long, but I did not know how much detail you needed!
Update: I see you ask to do it without modules. Here's a solution:
def ceil(xx):
if int(xx) < xx:
return int(xx) + 1
else:
return int(xx)
def generate_response(actual, guess, interval=5):
diff_interval_units = (guess - actual) / float(interval)
within = ceil(abs(diff_interval_units)) * interval
response = "You are within %d" % within
if diff_interval_units > 0:
response += "; guess lower"
elif diff_interval_units < 0:
response += "; guess higher"
return response
-- original answer:
You can do this with numpy's ceil function.
For instance:
import numpy as np
def generate_response(actual, guess, interval=5):
diff_interval_units = (guess - actual) / np.float(interval)
within = np.ceil(np.abs(diff_interval_units)) * interval
response = "You are within %d" % within
if diff_interval_units > 0:
response += "; guess lower"
elif diff_interval_units < 0:
response += "; guess higher"
return response
A solution using the modulo operator:
import random
randomNumber = random.randint(0,100)
def guess(divisor = 5):
while 1:
try:
print("Pick a number from 0-100")
userInput = int(input("Insert your number here: "))
except ValueError:
print("That is not a Number!")
continue
delta = randomNumber - userInput
if delta == 0:
print("You got it!")
return
remainder = delta % divisor
# this takes advantage of python truncating non-floating point numbers
rounded_delta = (abs(delta) / divisor) * divisor + divisor * bool(remainder)
high_or_low = 'higher' if delta > 0 else 'lower'
print("You are within %s. Guess %s." % (rounded_delta, high_or_low))