Cannot get rid of elif invalid syntax in python - python

def func(val):
num = int(input("Enter a number:"))
if num>val:
print ("Too high!")
return 1
elif num:
print ("Too low!")
return -1
else:
print ("Got it!!")
return 0
ch=1
while(ch!=0):
ch=func(15)
I keep getting the error:
"elif num:
^
SyntaxError: invalid syntax"
Is it simply a formatting issue that is causing this error message? or my code?

return statements should be indented
def func(val):
num = int(input("Enter a number:"))
if num>val:
print ("Too high!")
return 1
elif num:
print ("Too low!")
return -1
else:
print ("Got it!!")
return 0
ch=1
while(ch!=0):
ch=func(15)

Related

Python - How to check if user input is a Complex type input

i want to print a message depending on the type of the input but every time i input a complex number, FOR EXAMPLE (5j) it's detected as a string input. How do i solve this please? Thanks.
while True:
a = input("a ? ")
if (isinstance(a, complex)):
print("Valid number, please not Complex!")
try:
a = float(a)
except ValueError:
print ('please input a int or float')
if (type(a)==str):
print("Valid number, please not String!")
continue
if 0.5 <= a <= 100:
break
elif 0 <= a < 0.5:
print ('bigger number, please: 0.5-100')
elif a < 0:
print ('positive number, please')
elif a > 100:
print ('smaller number, please: 0.5-100')
Example of execution:
a ? 5j
please input a int or float
Valid number, please not String!
i tried doing this :
while True:
try:
a = input("a ? ")
if ('j' in a):
print("Valid number, please not Complex!")
a = float(a)
except ValueError:
print ('please input a int or float')
if (type(a)==str and 'j' not in a):
print("Valid number, please not String!")
continue
if 0.5 <= a <= 100:
break
elif 0 <= a < 0.5:
print ('bigger number, please: 0.5-100')
elif a < 0:
print ('positive number, please')
elif a > 100:
print ('smaller number, please: 0.5-100')
but it's not "Perfect"
You can add the first block of code into try block
Like this -
while True:
try:
a = input("a ? ")
if (isinstance(a, complex)):
print("Valid number, please not Complex!")
a = float(a)
except ValueError:
print ('please input a int or float')
if (type(a)==str):
print("Valid number, please not String!")
continue
if 0.5 <= a <= 100:
break
elif 0 <= a < 0.5:
print ('bigger number, please: 0.5-100')
elif a < 0:
print ('positive number, please')
elif a > 100:
print ('smaller number, please: 0.5-100')
Is this what you meant?
You can use nested try-except and the inbuilt function complex() instead.
So, your code needs to be like this
while True:
a = input("a? ")
try:
a = float(a)
if 0.5 <= a <= 100:
break
elif 0 <= a < 0.5:
print ('bigger number, please: 0.5-100')
elif a < 0:
print ('positive number, please')
elif a > 100:
print ('smaller number, please: 0.5-100')
except ValueError:
try:
a = complex(a)
print("Valid number, please not Complex!")
except ValueError:
print ("Valid number, please not String!")
continue

how to close my python loop after user tried three time

I made a loop which gives the user the chance to guess the right number. The problem is that my loop is continuing after the user guesses the right or wrong number. I want that the user can try up to three times. If they can't guess the right number within three chances then the loop will be closed.
Here is my code:
secret_number = 9
guess_count = 0
guess_limit = 3
while guess_count < guess_limit:
try:
give_number = int(float(input("give your number: ")))
if give_number == secret_number:
print("you won")
elif give_number != secret_number:
print("you guess wrong number")
except ValueError:
print("only integer or float value allowed")
you need to inclement value by 1 otherwise you loop will be continue.
secret_number = 9
guess_count = 0
guess_limit = 3
while guess_count < guess_limit:
guess_count += 1
try:
give_number = int(float(input("give your number: ")))
if give_number == secret_number:
print("you won")
elif give_number != secret_number:
print("you guess wrong number")
except ValueError:
print("only integer or float value allowed")
else:
guess_count = guess_limit
print("you tried maximum time")
secret_number = 9
guess_count = 0
guess_limit = 3
while guess_count < guess_limit:
try:
give_number = int(float(input("give your number: ")))
if give_number == secret_number:
print("you won")
break# break loop
elif give_number != secret_number:
print("you guess wrong number")
except ValueError:
print("only integer or float value allowed")
else:
guess_count += 1# increment count
First you should increase the guess_count, Doing that will make the loop automatically exit after 3 tries.
Also, you should include a break if the user guesses correctly. The break keyword exits the loop immediately.
secret_number = 9
guess_count = 0
guess_limit = 3
while guess_count < guess_limit:
try:
give_number = int(float(input("give your number: ")))
if give_number == secret_number:
print("you won")
break
elif give_number != secret_number:
print("you guess wrong number")
guess_count += 1
except ValueError:
print("only integer or float value allowed")

While loop and calling a function in python

def func(val):
num = int(input("Enter a number:"))
while(num!=val):
if num < val:
print ("Too low!")
return -1
num = int(input("Try again: "))
elif num > val:
print ("Too high!")
return 1
num = int(input("Try again: "))
else:
print ("Got it!!!")
break
return 0
print
func(20)
With this code, it does not loop. It asks me what my number is and lets me know if it's right or not, but it does not re-ask me to input a new number. Did I call the function in the incorrect place? Or is it my condition in my while loop that is incorrect?
Is this what you are looking for?
def func(val):
while True:
num = int(input("Enter a number:"))
if num < val:
print ("Too low!")
elif num > val:
print ("Too high!")
else:
print("Got it")
break
func(20)
It will never ask you the number again, because you are returning a value in every condition before asking for a number. So it gets out of the loop at the very first time.
# the function can be like this
def func(val):
while True:
num = int(input("Enter a number:"))
if num < val:
print ("Too low!")
elif num > val:
print ("Too high!")
else:
print("Got it")
break
func(20)
You can try to put "num" row into the while loop.
Firstly, break line exits loop, in your case when the loop is exited, the function is exited too. return -1 statement exits function, so you shouldn`t use it too if you want to get user's input no matter what user inputs first time and so on.
The correct code will look like this.
def func(val):
num = int(input("Enter a number:"))
while(num!=val):
if num < val:
print ("Too low!")
num = int(input("Try again: "))
elif num > val:
print ("Too high!")
num = int(input("Try again: "))
else:
print ("Got it!!!")
return 0
func(20)
P.S. Identation is very important in Python, so forat your code properly.
2nd last line print is unusable,
here is correct code :
def func(val):
num = int(input("Enter a number:"))
while(num!=val):
if num < val:
print ("Too low!")
return -1
num = int(input("Try again: "))
elif num > val:
print ("Too high!")
return 1
num = int(input("Try again: "))
else:
print ("Got it!!!")
break
return 0
func(20)

why my code not working AttributeError: 'int' object has no attribute 'isdigit'

#Guess the num
import random
def is_valid_num(num):
if num.isdigit() and 1 <= int(num) <= 100:
return True
else:
return False
def main():
number = random.randint(1,100)
guessed_number = False
guess = input('enter a num')
#guess = (input('enter a num'))
num_of_guesses = 0
while not guessed_number:
if not is_valid_num(guess):
#return False
guess = input('i count only digits enter 1<num<100')
continue
else:
num_of_guesses += 1
#break
guess = int(guess)
if guess < number:
print ('entered number is low')
elif guess > number:
print ('entered number is high')
else:
print ('you got in',num_of_guesses, 'guesses')
guessed_number = True
main()
Expected Out
if random number is system is 51 and we pressed 50 it will print too low, then continue this process lets say we gave input 51
output will you got in 2 guesses
isdigit() is a string method, it doesn't work on int inputs.
change this :
guess = int(input('enter a num'))
to this:
guess = input('enter a num')
your code after editing:
#Guess the num
import random
def is_valid_num(num):
if num.isdigit() and 1 <= int(num) <= 100:
return True
else:
return False
def main():
number = random.randint(1,100)
guessed_number = False
guess = input('enter a num')
#guess = (input('enter a num'))
num_of_guesses = 0
while not guessed_number:
if not is_valid_num(guess):
#return False
guess = input('i count only digits enter 1<num<100')
continue
else:
num_of_guesses += 1
break
guess = int(guess)
if guess < number:
print ('entered number is low')
elif guess > number:
print ('entered number is high')
else:
print ('you got in',num_of_guesses, 'guesses')
guessed_number = True
main()
#Thanks Issac Full code is below
#Guess the num
import random
def is_valid_num(num):
if num.isdigit() and 1 <= int(num) <= 100:
return True
else:
return False
def main():
number = random.randint(1,100)
guessed_number = False
guess = input('enter a num')
#guess = (input('enter a num'))
num_of_guesses = 0
while not guessed_number:
if not is_valid_num(guess):
#return False
guess = input('i count only digits enter 1<num<100')
continue
else:
num_of_guesses += 1
#break
guess = int(guess)
if guess < number:
guess = (input('entered number is low try again'))
elif guess > number:
guess = (input('entered number is high try again'))
else:
print ('you got in',num_of_guesses, 'guesses')
guessed_number = True
main()
Output is below
>>enter a num55
entered number is high try again55
entered number is high try again45
entered number is high try again88
entered number is high try again30
entered number is high try again10
entered number is low try again20
entered number is low try again25
entered number is high try again22
entered number is low try again23
you got in 10 guesses

The returned value not defined

I am creating a guessing game and I have created two functions. One to take the user input and the other to check whether the user input is correct.
def getGuess(maxNum):
if maxNum == "10":
count=0
guess = -1
guessnum = [ ]
while guess >10 or guess<0:
try:
guess=int(input("Guess?"))
except:
print("Please enter valid input")
guesses.append(guess)
return guesses
return guess
def checkGuess(maxNum):
if maxNum == "10":
if guess>num1:
print("Too High")
elif guess<num1:
print ("Too Low")
else:
print("Correct")
print (guesses)
and the main code is
if choice == "1":
count = 0
print("You have selected Easy as the level of difficulty")
maxNum= 10
num1=random.randint(0,10)
print (num1)
guess = 11
while guess != num1:
getGuess("10")
checkGuess("10")
count = count+1
print (guess)
Although the function returns the users guess the code always takes the guess as 11. If I don't define guess, it doesn't work either. Please help.
First, you are returning two values. A return statement also acts as a break, so the second return will not be called. Also, you are not storing the returned value anywhere, so it just disappears.
Here is your edited code:
def getGuess(maxNum):
if maxNum == "10":
guess = -1
while guess >10 or guess<0:
try:
guess=int(input("Guess?"))
except:
print("Please enter valid input")
return guess
def checkGuess(maxNum, guess, num1):
if maxNum == "10":
if guess>num1:
print("Too High")
elif guess<num1:
print ("Too Low")
else:
print("Correct")
return True
return False
if choice == "1":
count = 0
print("You have selected Easy as the level of difficulty")
maxNum= 10
num1=random.randint(0,10)
print (num1)
guess = 11
guesses = []
while guess != num1:
guess = getGuess("10")
guesses.append(guess)
hasWon = checkGuess("10", guess, num1)
if hasWon:
print(guesses)
break
count = count+1
You have selected Easy as the level of difficulty
2
Guess?5
Too High
Guess?1
Too Low
Guess?2
Correct
[5, 1, 2]
>>>
You have a programming style I call "type and hope". maxNum seems to bounce between a number and a string indicating you haven't thought through your approach. Below is a rework where each routine tries do something obvious and useful without extra variables. (I've left off the initial choice logic as it doesn't contribute to this example which can be put into your choice framework.)
import random
def getGuess(maxNum):
guess = -1
while guess < 1 or guess > maxNum:
try:
guess = int(input("Guess? "))
except ValueError:
print("Please enter valid input")
return guess
def checkGuess(guess, number):
if guess > number:
print("Too High")
elif guess < number:
print("Too Low")
else:
print("Correct")
return True
return False
print("You have selected Easy as the level of difficulty")
maxNum = 10
maxTries = 3
number = random.randint(1, maxNum)
count = 1
guess = getGuess(maxNum)
while True:
if checkGuess(guess, number):
break
count = count + 1
if count > maxTries:
print("Too many guesses, it was:", number)
break
guess = getGuess(maxNum)
A couple of specific things to consider: avoid using except without some sense of what exception you're expecting; avoid passing numbers around as strings -- convert numeric strings to numbers on input, convert numbers to numeric strings on output, but use actual numbers in between.

Categories