While loop and calling a function in python - 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)

Related

Stuck in an infinite loop. Python

I am trying to make this code run so that when I enter 'done' it break me out of the loop. The issue is I put a try/except to try and catch anything that isn't a number and feed back and error message. This catches before the if statement that would break me out of the loop and instead feeds back an error message and catches me in an infinite loop. I've tried moving the try/except after all the if/else statements but then the string gets placed inside the value for maximum and this is not what I am trying to accomplish. Is there a way for me to get the try and except to run but still allow me to pass a 'done' command to exit the loop?
largest = None
smallest = None
while True:
num = input("Enter a number: ")
try:
num = float(num)
except:
print('Invalid Input')
continue
if num == "done" :
break
elif largest is None:
largest = num
elif smallest is None:
smallest = num
elif largest < num:
largest = num
elif smallest > num:
smallest = num
print(num)
print("Maximum", largest)
print("Minimum", smallest)
first test for done and then convert to float
And you can simplify the tests
The program should work if you enter none or one number
num = input("Enter a number: ")
if num == "done" :
break
try:
num = float(num)
except:
print('Invalid Input')
continue
largest = largest or num
smallest = smallest or num
largest = max(num, largest)
smallest = min(num, smallest)
The reason is that you're using checking if the input is a float before you're checking for "done" so when it's actually "done" it just continues before it checks for it.
I would fix it this way.
largest = None
smallest = None
while True:
num = input("Enter a number: ")
# check if it's done first
if num == "done" :
break
try:
num = float(num)
except:
print('Invalid Input')
continue
elif largest is None:
largest = num
elif smallest is None:
smallest = num
elif largest < num:
largest = num
elif smallest > num:
smallest = num
print(num)
print("Maximum", largest)
print("Minimum", smallest)
Change this:
try:
num = float(num)
except:
print('Invalid Input')
continue
if num == "done":
break
to this:
try:
num = float(num)
except:
if num == "done":
break
print('Invalid Input')
continue
By putting the if inside the except, you allow the loop to break before it can continue.

Cannot get rid of elif invalid syntax in 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)

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.

Asking the user if they want to play again [duplicate]

This question already has answers here:
Ask the user if they want to repeat the same task again
(2 answers)
Closed 4 years ago.
Basically it's a guessing game and I have literally all the code except for the last part where it asks if the user wants to play again. how do I code that, I use a while loop correct?
heres my code:
import random
number=random.randint(1,1000)
count=1
guess= eval(input("Enter your guess between 1 and 1000 "))
while guess !=number:
count+=1
if guess > number + 10:
print("Too high!")
elif guess < number - 10:
print("Too low!")
elif guess > number:
print("Getting warm but still high!")
elif guess < number:
print("Getting warm but still Low!")
guess = eval(input("Try again "))
print("You rock! You guessed the number in" , count , "tries!")
while guess == number:
count=1
again=str(input("Do you want to play again, type yes or no "))
if again == yes:
guess= eval(input("Enter your guess between 1 and 1000 "))
if again == no:
break
One big while loop around the whole program
import random
play = True
while play:
number=random.randint(1,1000)
count=1
guess= eval(input("Enter your guess between 1 and 1000 "))
while guess !=number:
count+=1
if guess > number + 10:
print("Too high!")
elif guess < number - 10:
print("Too low!")
elif guess > number:
print("Getting warm but still high!")
elif guess < number:
print("Getting warm but still Low!")
guess = eval(input("Try again "))
print("You rock! You guessed the number in" , count , "tries!")
count=1
again=str(input("Do you want to play again, type yes or no "))
if again == "no":
play = False
separate your logic into functions
def get_integer_input(prompt="Guess A Number:"):
while True:
try: return int(input(prompt))
except ValueError:
print("Invalid Input... Try again")
for example to get your integer input and for your main game
import itertools
def GuessUntilCorrect(correct_value):
for i in itertools.count(1):
guess = get_integer_input()
if guess == correct_value: return i
getting_close = abs(guess-correct_value)<10
if guess < correct_value:
print ("Too Low" if not getting_close else "A Little Too Low... but getting close")
else:
print ("Too High" if not getting_close else "A little too high... but getting close")
then you can play like
tries = GuessUntilCorrect(27)
print("It Took %d Tries For the right answer!"%tries)
you can put it in a loop to run forever
while True:
tries = GuessUntilCorrect(27) #probably want to use a random number here
print("It Took %d Tries For the right answer!"%tries)
play_again = input("Play Again?").lower()
if play_again[0] != "y":
break
Don't use eval (as #iCodex said) - it's risky, use int(x). A way to do this is to use functions:
import random
import sys
def guessNumber():
number=random.randint(1,1000)
count=1
guess= int(input("Enter your guess between 1 and 1000: "))
while guess !=number:
count+=1
if guess > (number + 10):
print("Too high!")
elif guess < (number - 10):
print("Too low!")
elif guess > number:
print("Getting warm but still high!")
elif guess < number:
print("Getting warm but still Low!")
guess = int(input("Try again "))
if guess == number:
print("You rock! You guessed the number in ", count, " tries!")
return
guessNumber()
again = str(input("Do you want to play again (type yes or no): "))
if again == "yes":
guessNumber()
else:
sys.exit(0)
Using functions mean that you can reuse the same piece of code as many times as you want.
Here, you put the code for the guessing part in a function called guessNumber(), call the function, and at the end, ask the user to go again, if they want to, they go to the function again.
I want to modify this program so that it can ask the user whether or not they want to input another number and if they answer 'no' the program terminates and vice versa. This is my code:
step=int(input('enter skip factor: '))
num = int(input('Enter a number: '))
while True:
for i in range(0,num,step):
if (i % 2) == 0:
print( i, ' is Even')
else:
print(i, ' is Odd')
again = str(input('do you want to use another number? type yes or no')
if again = 'no' :
break

Categories